(问题仅在Ubuntu中出现。在Windows中工作正常。我不知道在其他Linux环境中)
我已经使用componentListener的方法在一个对话框中调用了jtextfield中的focus,但对于这种情况,我不知道为什么。它在文本字段中显示焦点,并快速切换到按钮。运行并查看:
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class User {
private String username = "";
private String password = "";
public User() {
// default constructor
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
/** Create a panel containing the componet and tha label. */
public JPanel createLabeledComponent(JLabel label, Component comp) {
GridLayout layout = new GridLayout(2, 1);
JPanel panel = new JPanel(layout);
panel.add(label);
panel.add(comp);
label.setLabelFor(comp);
return panel;
}
public void showEditDialog() {
JLabel usernameLbl = new JLabel(username);
final JTextField usernameField = new JTextField();
usernameField.setText(username);
JPanel usernamePnl = createLabeledComponent(usernameLbl, usernameField);
JLabel passwordLbl = new JLabel(password);
JPasswordField passwordField = new JPasswordField(password);
JPanel passwordPnl = createLabeledComponent(passwordLbl, passwordField);
Object[] fields = { "User:", usernamePnl, "Password:", passwordPnl };
JOptionPane optionPane = new JOptionPane(fields, JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION, null, null);
JDialog dialog = optionPane.createDialog("User Data");
dialog.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
usernameField.requestFocusInWindow();
}
});
}
});
dialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new User().showEditDialog();
}
});
}
}
知道怎么解决这个问题吗?
--更新
现在一切都在EDT上运行。不幸的是,同样的行为。
顺便说一下,使用joptionpane构造函数的最后一个参数(object initialvalue)都不起作用。