我正在尝试使用基于命令提示符的 GUI 制作一个简单的程序(即输入命令并单击输入按钮)。每当用户单击 Enter 按钮时,他们在 JTextArea 中输入的所有信息都会被处理,然后根据他们的输入给出输出(例如输入/exit 来关闭程序)。
每当用户输入/exit 时,都会出现提示,询问用户是否确定要退出。但是,一旦弹出,如果用户输入了无法识别的内容,它就会被我输入的无效输入消息所取代。我对发生这种情况的唯一原因是 ActionListener 类仍然将/exit 存储在 inputHolder 字符串中,这是我用来存储用户输入并处理它们的字符串。
package msai;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainFrame extends JFrame implements ActionListener {
JTextArea output;
JButton inputButton;
JTextArea commandLine;
String inputHolder;
String invalid = "Invalid input!";
public MainFrame() {
super("MSAI");
setLookAndFeel();
setSize(650, 350);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flo = new FlowLayout();
setLayout(flo);
output = new JTextArea("Hi! I'm MSAI. Type any command to get started, or type /help for a list of commands and syntax!", 8, 40);
inputButton = new JButton("ENTER");
inputButton.addActionListener(this);
commandLine = new JTextArea(8, 40);
commandLine.setLineWrap(true);
commandLine.setWrapStyleWord(true);
JScrollPane scroll = new JScrollPane(commandLine, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
add(output);
add(inputButton);
add(scroll);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
inputHolder = commandLine.getText();
switch(inputHolder) {
"/exit":
output.setText("Are you sure you want to terminate this session?");
inputHolder = commandLine.getText();
switch(inputHolder.toUpperCase()) {
case "YES":
System.exit(0);
break;
case "NO":
output.setText("Your session has not been terminated.");
break;
default:
output.setText(invalid);
break;
}
}
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"javax.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
//ignore error
}
}
public static void main(String[] args) {
MainFrame frame = new MainFrame();
}
}
目前,我关于如何解决此问题的唯一思考过程是将另一个 actionPerformed 放入/exit switch 语句中,但我不确定如何做到这一点,或者这是否是最好的解决方案。我欢迎任何答案和反馈,只是请不要有毒!
最佳答案
当你这样做时
output.setText("Are you sure you want to terminate this session?");
inputHolder = commandLine.getText();
用户尚未更新命令行
并按下按钮,因此没有任何变化。您需要“等待”直到用户再次响应。
您需要将请求的“状态”传递到下次调用 ActionPerformed
时,例如...
private boolean wantsToExit = false
public void actionPerformed(ActionEvent event) {
inputHolder = commandLine.getText();
if (wantsToExit) {
if (wantsToExit && inputHolder.equals("YES")) {
// Better to close the frame and let the system deal with it
} else if (wantsToExit && inputHolder.equals("NO")) {
output.setText("Your session has not been terminated.");
}
wantsToExit = false;
} else {
switch(inputHolder) {
"/exit":
wantsToExit = true;
output.setText("Are you sure you want to terminate this session?");
break;
}
}
}
如果您想在单个流程中执行此操作,那么您应该考虑使用 JOptionPane
来提示用户
关于java - 如何在 switch 语句中执行 actionPerformed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58424244/