【问题标题】:getActionCommand with .equal not equaling properlygetActionCommand 与 .equal 不正确相等
【发布时间】:2021-04-04 21:41:13
【问题描述】:

我正在尝试学习 Jtextfields 和动作侦听器。我正在关注本教程https://www.geeksforgeeks.org/java-swing-jtextfield/,但是我遇到了这个函数的错误。

public void actionPerformed(ActionEvent e) {
    String input = e.getActionCommand();
    if (input.equals("submit")) {
        displaysText.setText(textField.getText());
        textField.setText("");
        System.out.println("Entered if statement");
    }
}

无论我在文本字段中输入什么,它都会输入该 if 语句。当我输入“提交”时,它应该只输入那个 if 语句。这是一个错误还是我做错了什么?

如果有帮助,这里就是所有代码

package IncludesMain;

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

public class Main extends JFrame implements ActionListener {
    static JTextField textField;
    static JFrame frame;
    static JButton button;
    static JLabel displaysText;
    Main() {}

    public static void main(String[] args) {

        frame = new JFrame("textfield");
        displaysText = new JLabel("N/A");
        button = new JButton("submit");

        Main textObject = new Main();
        button.addActionListener(textObject);
        textField = new JTextField(16);
        JPanel panel = new JPanel();

        panel.add(textField);
        panel.add(button);
        panel.add(displaysText);

        frame.add(panel);
        frame.setSize(500, 400);
        frame.show();


    }

    public void actionPerformed(ActionEvent e) {
        String input = e.getActionCommand();
        if (input.equals("submit")) {
            displaysText.setText(textField.getText());
            textField.setText("");
            System.out.println("Entered if statement");
        }
    }
}

【问题讨论】:

  • getActionCommand 方法从 JButton 获取动作命令字符串。如果您需要测试 JTextField 文本输入,该文本将是 textField.getText();.

标签: java swing actionlistener


【解决方案1】:

e.getActionCommand() 正在获取按钮的 actionCommand,因为您将侦听器放在那里。您需要在文本字段上设置监听器

代替

Main textObject = new Main();
button.addActionListener(textObject);
textField = new JTextField(16);
JPanel panel = new JPanel();

应该是

Example textObject = new Example();
textField = new JTextField(16);
textField.addActionListener(textObject);
JPanel panel = new JPanel();

如果你这样做了,那么你必须按 Enter 来提交值,除非你重构 actionPerformed 方法中的逻辑,否则按钮将不起作用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 2010-09-24
    • 2018-05-07
    • 1970-01-01
    • 2016-11-12
    • 2021-03-21
    相关资源
    最近更新 更多