在循环中使用 KeyListener

Use KeyListener in a loop

我对 KeyListeners 没有太多经验,但我在我的应用程序中使用了一个,它工作正常,除了我需要等待输入才能继续我的程序。为此,我做了一个 while 循环,循环直到 String temp 不为空(这意味着会有输入)。

问题是无法在 JTextField(称为输入)中键入。下面是我的两种方法的代码,它们应该一起工作,以便可以返回我的 JTextField(输入)中的文本(作为临时)。我不确定为什么这不起作用或如何解决它。

我的 KeyListener 的 keyPressed 方法:

 public void keyPressed(KeyEvent e)
{
    //only sends text if the enter key is pressed
    if (e.getKeyCode()==KeyEvent.VK_ENTER)
    {
        //if there really is text
        if (!input.getText().equals(""))
        {
            //String temp is changed from null to input
            temp=input.getText();
            //text sent to another JTextField
            output.append(temp+"\n");
            //input no longer has text
            input.setText("");
        }
    }
}

试图获取文本的方法,也在我的 KeyListener 中 class

public String getTemp()
{
    booleans isNull=temp==null; 
    //loops until temp is not null
    while (isNull)
    {
        //unnecessary line of code, only used so the loop not empty
        isNull=checkTemp();
    }   
    return temp;
}
public boolean checkTemp()
{
    return temp==null;
}

您的 while 循环是一个常见的控制台程序结构,但要明白您不是在此处创建控制台程序,而是创建一个 事件驱动 GUI,在这种情况下, while 循环与 Swing GUI 库作斗争,您需要摆脱它。您现在想要响应事件,而不是持续轮询的 while 循环,如果您正在侦听用户输入到 JTextField ,请不要使用 KeyListener,因为这个低级侦听器可以导致不必要的副作用。而是将 DocumentListener 添加到 JTextField 的文档中。

编辑:您正在监听 enter 键,因此解决方案更简单:向 JTextField 添加一个 ActionListener!

例如,

input.addActionListener(e -> {
    String text = input.getText().trim();
    if (text.isEmpty()) {
        return;
    }
    output.append(text + "\n");

    input.setText("");
});

更完整的示例:

import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import javax.swing.*;

public class ChatBox extends JPanel {
    private static final int COLS = 40;
    private JTextField input = new JTextField(COLS);
    private JTextArea output = new JTextArea(20, COLS);
    private JButton submitButton = new JButton("Submit");

    public ChatBox() {
        output.setFocusable(false); // user can't get into output
        JScrollPane scrollPane = new JScrollPane(output);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        ActionListener inputListener = e -> {
            String text = input.getText().trim();
            if (text.isEmpty()) {
                return;
            }
            output.append(text + "\n");

            input.setText("");
            input.requestFocusInWindow();
        };

        input.addActionListener(inputListener);
        submitButton.addActionListener(inputListener);

        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
        bottomPanel.add(input);
        bottomPanel.add(submitButton);

        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.PAGE_END);
    }

    private static void createAndShowGui() {
        ChatBox mainPanel = new ChatBox();

        JFrame frame = new JFrame("Chat Box");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}