java - 在循环中使用 KeyListener

标签 java swing while-loop keylistener

我对 KeyListener 没有太多经验,但我在我的应用程序中使用了一个,它工作得很好,只是我需要等待输入才能继续我的程序。为此,我做了一个 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 类中

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 键,因此解决方案更加简单:将 ActionListener 添加到 JTextField!

例如,

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());
    }
}

关于java - 在循环中使用 KeyListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43415416/

相关文章:

java - 使用 JComboBox 计算 JTable 中的运行总计

java - android values-v21 和 values-ldrtl 在一起

java - 永久更改 JComboBox 所选项目的颜色

java - 递归求解 A^4 + B^4 + C^4 + D^4 = E^4

java - Groovy 不执行 Java-Method(签名包括泛型)

java - 我可以修改现有对象的 JComboBox 弹出窗口背景颜色吗?

java - 具有动态生成的 HTML 的 JEditorPane.scrollToReference()

Javascript 比较不​​适用于提示、while 循环和 !==

C++ 如何检查多输入语句的第一个输入?

python - 返回 True 后继续 while 循环