您是否可以在 keyPressed 事件中使用布尔值来触发 while 循环的中断?

问题描述 投票:0回答:0

这不是尝试解决这个问题的正确方法吗?

public class GUI {
    JFrame mainFrame;
    PrintStream standardOut = System.out;
    PrintStream standardErr = System.err;
    JTextField userInputLoc;
    String curInput = "";
    boolean enterKeyPressed = false;

    // should be the main method most likely
    // next week figure out how to use migLayout which seems the best
    public GUI(){
        mainFrame = new JFrame("Excel Quality Checks");
        MigLayout layout = new MigLayout();
        JPanel panel = new JPanel();
        panel.setLayout(layout);

        JTextArea textOutput = new JTextArea(10,10);
        PrintStream printStream = new PrintStream(new CustomOutputStream(textOutput));
        System.setOut(printStream);
        System.setErr(printStream);

        panel.add(textOutput, "wrap");

        JLabel jl = new JLabel("Input Here:");
        userInputLoc = new JTextField(20);
        panel.add(jl, "wrap");

        panel.add(userInputLoc);
        

        userInputLoc.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();

                if(keyCode == KeyEvent.VK_ENTER){
                    curInput = userInputLoc.getText();
                    userInputLoc.setText("");
                    enterKeyPressed = true;
                }
            }
        });

        mainFrame.add(panel);

        mainFrame.setSize(600, 1000);

        mainFrame.setVisible(true);
    }
}

在单独的课程中:

private String nextInput(){
        String input = "";

        // will have to check if enter key is pressed
        while(!enterKeyPressed){
            input = gui.curInput;
        }

        return input;
    }

我试图根据用户按下回车键的时间在单独的类中设置一个等于用户输入的字符串,这表示输入已完成并准备好进行解析和读取。我目前正在将布尔值“enterKeyPressed”设置为 true,以向“nextInput()”方法发出信号,指示应读取下一个输入。当我尝试运行它时,我将输入一个输入,当按下回车键时它将被清除,但程序不会继续运行(我假设它仍然停留在 while(!enterKeyPressed) 循环中.

java swing while-loop key user-input
© www.soinside.com 2019 - 2024. All rights reserved.