当我将updateComponentTreeUI用于非空的JTextField时,光标的位置从文本的末尾移动到前面,如给定的示例所示。任何人都可以想到一个原因,一个修复,或者经历过这个吗?由于我在许多不同的类中有许多文本字段,因此不需要为每个文本字段添加监听器的全局解决方案。这是一个简单的例子:
import java.awt.*;
import java.awt.Dialog.*;
import java.awt.event.*;
import java.lang.reflect.*;
import javax.swing.*;
public class DialogTest {
final JFrame frame = new JFrame("DialogTest");
JDialog dlg;
public DialogTest() {
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JButton(action1), BorderLayout.NORTH);
frame.add(new JButton(action2), BorderLayout.CENTER);
frame.pack();
frame.setLocation(200, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
new DialogTest();
}
});
} catch (InvocationTargetException | InterruptedException e1) {
}
}
private void setStuff() {
dlg = new JDialog(frame, "Dialog", ModalityType.DOCUMENT_MODAL);
dlg.getContentPane().setLayout(new BorderLayout());
dlg.getContentPane().add(new JTextField("test 123", 20), BorderLayout.NORTH);
dlg.getContentPane().add(new JTextField("Bla bla bla bla bla", 20), BorderLayout.CENTER);
dlg.getContentPane().add(new JButton(new AbstractAction("Close") {
@Override
public void actionPerformed(ActionEvent e) {
dlg.setVisible(false);
}
}), BorderLayout.SOUTH);
dlg.setLocation(250, 250);
}
final Action action1 = new AbstractAction("Dialog") {
@Override
public void actionPerformed(ActionEvent e) {
setStuff();
dlg.pack();
dlg.setVisible(true);
}
};
final Action action2 = new AbstractAction("UpdateComponentTree") {
@Override
public void actionPerformed(ActionEvent e) {
setStuff();
SwingUtilities.updateComponentTreeUI(dlg);
dlg.pack();
dlg.setVisible(true);
}
};
}