Java showInputDialog select 自定义文本

Java showInputDialog select custom text

我有重命名文件的重命名对话框

String renameTo = JOptionPane.showInputDialog(gui, "New Name", currentFile.getName());

它是这样工作的,但我有一个问题。 问题是我用文件的扩展名设置了默认值 但我只想将文件名设为 selected.

sample : my file name = yusuf.png

我要select只有yusuf喜欢;

JOptionPane内部发生了很多事情,这是让它如此强大的原因之一,也让它有点不灵活。

两个直接的问题很明显...

  1. 您无法直接访问 JTextField 用于获取用户输入的
  2. JOptionPane 想要控制首次显示对话框时哪些组件具有焦点。

设置 JTextField 其实很简单...

String text = "yusuf.png";
int endIndex = text.lastIndexOf(".");

JTextField field = new JTextField(text, 20);
if (endIndex > 0) {
    field.setSelectionStart(0);
    field.setSelectionEnd(endIndex);
} else {
    field.selectAll();
}

这将基本上 select 从 String 开始到最后 . 的所有文本,或者如果找不到 . 则所有文本。

现在困难的部分是从 JOptionPane

收回焦点控制
// Make a basic JOptionPane instance
JOptionPane pane = new JOptionPane(field, 
        JOptionPane.PLAIN_MESSAGE, 
        JOptionPane.OK_CANCEL_OPTION, 
        null);
// Use it's own dialog creation process, it's simpler this way
JDialog dialog = pane.createDialog("Rename");
// When the window is displayed, we want to "steal"
// focus from what the `JOptionPane` has set
// and apply it to our text field
dialog.addWindowListener(new WindowAdapter() {
    @Override
    public void windowActivated(WindowEvent e) {
        // Set a small "delayed" action
        // to occur at some point in the future...
        // This way we can circumvent the JOptionPane's
        // focus control
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                field.requestFocusInWindow();
            }
        });
    }
});
// Put it on the screen...
dialog.setVisible(true);
dialog.dispose();
// Get the resulting action (what button was activated)
Object value = pane.getValue();
if (value instanceof Integer) {
    int result = (int)value;
    // OK was actioned, get the new name
    if (result == JOptionPane.OK_OPTION) {
        String newName = field.getText();
        System.out.println("newName = " + newName);
    }
}

而且,祈祷吧,我们最终得到的东西看起来像...

就我个人而言,我会将其包装在一个很好的可重复使用的 class/method 调用中,该调用根据用户的操作返回新文本或 null,但我就是这样

Isn't there an easier way?

当然,我只是想向您展示最困难的解决方案...(讽刺)...这就是为什么我建议将其包装在它自己的实用程序中的原因 class,这样您就可以重新- 稍后使用它