这是我创建登录对话框的代码,但是我想在Enter键上自动登录,而这个代码没有完成。我试过getRootPane().setDefaultButton(..);
,但我没有JButton对象。
String _options = {"ok", "Exit"};
JOptionPane pane = new JOptionPane(this, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION, null, _options, null);
JDialog dialog = pane.createDialog("Login");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
dialog.requestFocus();
dialog.toFront();
我正在考虑设置默认按钮,但有没有办法从JOptionpane获取JButton对象?
其次我们可以设置
JOptionPane pane = new JOptionPane(this, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION, null, _options, _options[0]); //set to _options[0]
但问题是它将焦点转移到“确定”按钮并且名称不可调焦?怎么能解决这个问题?
答案 0 :(得分:0)
您可以创建自己的JDialog
并在ActionListener
字段中添加JPassword
。
这是一个简单的例子。
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class Password {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new PasswordDialog();
}
});
}
static class PasswordDialog extends JDialog {
public PasswordDialog() {
final JLabel label = new JLabel("Type: stackoverflow");
final JPasswordField field = new JPasswordField(20);
final JLabel status = new JLabel(" ");
status.setForeground(Color.RED);
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
panel.add(label, BorderLayout.NORTH);
panel.add(field, BorderLayout.CENTER);
panel.add(status, BorderLayout.SOUTH);
field.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (Arrays.equals(field.getPassword(), "stackoverflow".toCharArray())) {
JOptionPane.showMessageDialog(PasswordDialog.this, "Correct Password");
} else {
status.setText("Invalid Password");
}
}
});
add(panel);
pack();
setLocationRelativeTo(null);
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
}