gpt4 book ai didi

java - JOptionPane 取消按钮和获取输入

转载 作者:行者123 更新时间:2023-11-29 04:33:17 24 4
gpt4 key购买 nike

我试图让用户输入那里的名字,如果它留空,它会再次询问,如果他们填写它,它会设置一个 JLabel 或点击取消退出。
我的最后一个 if 语句是错误的,它不喜欢 nameEnt

public Player() {
//setBackground(Color.green);
setSize(600, 400);
name = new JLabel();//Input hint
JOptionPane nameOption = new JOptionPane();
String nameEnt = nameOption.showInputDialog("First Name: ");
if (!nameEnt.matches("[a-zA-Z]+")) {
name.setText(nameEnt);
}
if (nameEnt.length() == 0) {
//if this condition is true JOption stays until name is entered or canceled
}
if (nameEnt == nameOption.CANCEL_OPTION) {
System.exit(0);
}
}

最佳答案

JOptionPane.CANCEL_OPTION 是一个静态 int 字段,您不能将 Stringint==.


良好做法

在你的情况下,你想一次性使用确定和取消按钮 JOptionPane.showConfirmDialogJOptionPane.showInputDialog() 这是不可能的,我建议使用这个代替:

JTextField nameF = new JTextField(20);//create TextField

JPanel myPanel = new JPanel();//cerate JPanel
myPanel.add(new JLabel("Name"));
myPanel.add(nameF);//add your JTextField to your panel

int result;
do {
result = JOptionPane.showConfirmDialog(null, myPanel,
"Title of Panel", JOptionPane.OK_CANCEL_OPTION);//add your panel to JOptionPane
if (result == JOptionPane.OK_OPTION) {//if the user press OK then
if (nameF.getText().isEmpty()) {//check if the input is empty
//if this condition is true JOption stays until name is entered or canceled
} else if (!nameF.getText().matches("[a-zA-Z]+")) {//check if the input match with your regex
//name match exactly
//name.setText(nameF.getText());
}
}
} while (result != JOptionPane.CANCEL_OPTION);//If the user hit cancel then exit

关于java - JOptionPane 取消按钮和获取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42878842/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com