java - 将从 JDialog 输入的值传递给两个类导致两个 JDialog 提示
问题描述
我正在尝试将存储在 UserInput 类的数组中的 JDialog 的输入值传递给 MainClass 和 CheckUserInput 类。但是,为了做到这一点,我需要从接受用户输入的 UserInput 类中调用 promptUser 方法。但是当我在两个类中都这样做时,我得到了两个 JDialog 提示。我不知道该怎么做。
任何帮助表示赞赏。我是java和编程的初学者。感谢您花时间阅读我的问题。
主类
public class MainClass {
public static void main(String[] args) {
UserInput input = new UserInput();
CheckUserInput checkError = new CheckUserInput();
int passedUserInput[] = input.getInput();
input.promptUser();
input.getInput();
System.out.println(passedUserInput[0]);
checkError.inputCheck();
String check = checkError.getError();
if (check == ("failEven")) {
System.out.println("You entered an odd number");
} else if (check == "failRange") {
System.out.println("Please enter a number between 2 and 20");
} else if (check == "checkpassed") {
System.out.println("All cleared");
}
}
}
检查用户输入类
public class CheckUserInput {
String errorMessage = "";
public void inputCheck() {
UserInput input = new UserInput();
input.promptUser();// unless I do this I cannot pass the value to this method but when I also need
// to do this in the MainClass class
// and this cause two jDialog prompts
int[] checkUserInput = input.getInput();
if (!(checkUserInput[1] <= 5 && checkUserInput[1] % 2 == 0)) {
errorMessage = "failEven";
} else if (checkUserInput[0] < 2 || checkUserInput[0] > 20) {
errorMessage = "failRange";
} else if ((checkUserInput[0] >= 2 || checkUserInput[0] <= 20)
&& (checkUserInput[1] <= 5 && checkUserInput[1] % 2 == 0)) {
errorMessage = "checkpassed";
}
}
public String getError() {
return errorMessage;
}
}
用户输入类
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class UserInput {
int[] userInput = new int[2];
String[] error = new String[2];
String s;
JPanel panel = new JPanel();
JTextField firstNumber = new JTextField(10);
JTextField secondNumber = new JTextField(10);
JLabel fnLabel = new JLabel("Enter first number: ");
JLabel snLabel = new JLabel("Enter second number: ");
public void promptUser() {
panel.add(fnLabel);
panel.add(firstNumber);
panel.add(snLabel);
panel.add(secondNumber);
int ok = JOptionPane.showConfirmDialog(null, panel, "Testing", JOptionPane.OK_CANCEL_OPTION);
if (ok == JOptionPane.CANCEL_OPTION || ok == JOptionPane.CLOSED_OPTION) {
} else {
s = "go";
}
}
public int[] getInput() {
if (s == "go") {
userInput[0] = Integer.parseInt(firstNumber.getText());
userInput[1] = Integer.parseInt(secondNumber.getText());
}
return userInput;
}
}
解决方案
推荐阅读
- laravel - 如何在laravel的命名路由中传递get参数
- php - Bootstrap:如何固定面板高度并使面板内的图像遵循该固定高度?
- swift - APNs 与 Firebase 分开工作正常,但无法在 FCM 中获得通知
- javascript - 如何在 Safari 扩展中实施内容安全策略
- java - 通过保持文本位置在 Java 中阅读电子邮件
- javascript - 如何根据 onChange 在 React 功能组件中重新渲染?
- html - 在 div 上方添加两列,但该列和 div 不应有间隙
- python - 在 pandas df 中填写缺失的日期
- python - 从 python-shell 返回值作为响应
- sql - 使用 group by 在 postgres 中进行慢速查询