(问题出现在Ubuntu只在Windows工作正常。我不知道在其他Linux环境)
我已经使用了的ComponentListener的方法在对话中呼吁焦点JTextField中,但这种情况下,只是不工作,我不知道为什么。 它显示在文本字段和快速变化给该按钮的焦点。 运行看看:
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();
}
});
}
}
不知道如何解决这个问题?
--update
一切都在EDT现在正在运行。 可悲的是具有相同的行为。
顺便说一句,无论是使用JOptionPane构造函数的最后一个参数(对象初值)不起作用。