【问题标题】:JTextField not clearing after setText("")JTextField 在 setText("") 后未清除
【发布时间】:2014-05-29 01:25:32
【问题描述】:

在解释之前,代码如下:

public class Calculator extends JFrame implements ActionListener {
    private String[] ops = { "+", "-", "*", "/", "=" };
    private JButton[] buttons = new JButton[16];
    private JTextField field;

    private int currentAnswer;

    public Calculator() {
        super("Calculator");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new GridBagLayout());
        addComponents();
        pack();
        setLocationRelativeTo(null);
    }

    private void addComponents() {
        GridBagConstraints gbc = new GridBagConstraints();

        field = new JTextField(10);
        add(field, gbc);

        gbc.gridy++;

        add(buttons[0] = newButton("0"), gbc);
        add(buttons[10] = newButton("+"), gbc);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String text = field.getText();

        /* Checks for operation chars */
        for(int i = 0; i < ops.length; i++) {
            if(text.endsWith(ops[i])) {
                field.setText("");
                System.out.println("called");
                break;
            }
        }

        /* Checks if number was pressed */
        for (int i = 0; i <= 9; i++) 
            if (e.getSource() == buttons[i]) {
                field.setText(text + buttons[i].getText());
                return;
            }

        switch (e.getActionCommand()) {
            case "+":
                currentAnswer += Integer.parseInt(text);
                field.setText(text + e.getActionCommand());
                return;
        }
    }

    public JButton newButton(String name) {
        JButton newButton = new JButton(name);
        newButton.addActionListener(this);
        return newButton;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                Calculator calculator = new Calculator();
                calculator.setVisible(true);
            }
        });
    }
}

我的目标是检查我的JTextField field 是否包含数学运算符(我已将其存储在字符串数组中)。如果是,请在继续之前“清除”文本字段。

问题是:我的程序告诉我代码已被执行(“调用”打印出来),但我的结果显示好像从未调用过 setText("")

我确实在 EDT 上初始化了我的所有组件(和我的框架)。如果您需要查看其余代码,请告诉我(数量不多)。我的一个朋友给我发了这个,我正试图清理它(消除错误)。我不确定这是否只是我没有看到的一件小事,但我知道 Swing 有很多“规则”,要全部跟上真的很难/:


编辑:

按下“+”按钮后,当我按下数字按钮时会发生这种情况

String text = field.getText(); 
System.out.println(text); // prints "0+" like expected (after pressing number)

/* Checks for operation chars */
for(int i = 0; i < ops.length; i++) {
    if(text.endsWith(ops[i])) {
        field.setText("");
        System.out.println("called"); //gets printed
        break;
    }
}

System.out.println(text); //even when "called" prints, text is not ""

为什么不清除? :s

【问题讨论】:

  • 发帖SSCCE
  • 考虑提供一个实际的runnable example that demonstrates your problem 将涉及更少的猜测工作和更好的响应
  • 由于太常见了,您对您的问题的描述不够充分,“好像从未调用过 setText("")”并没有告诉我们会发生什么。还有其他文字吗?不同的文字?您是否试图在其他东西出现之前清除它,即使应该在该方法稍后的 setText() 调用之一中出现什么?什么?
  • text.endsWith(ops[i]):确保你的文本不以空格或类似的东西结尾。考虑使用 indexOf
  • @MadProgrammer 更新了我的答案。对此感到抱歉

标签: java swing jtextfield settext


【解决方案1】:

有几个问题...

首先,您的 actionPerformed 方法完全按照您的指示进行操作

for (int i = 0; i < ops.length; i++) {
    if (text.endsWith(ops[i])) {
        field.setText("");
        System.out.println("called");
        break;
    }
}

/* Checks if number was pressed */
for (int i = 0; i <= 9; i++) {
    if (e.getSource() == buttons[i]) {
        // Here, the field text is been rest to text + button.text...
        field.setText(text + buttons[i].getText());
        // And nothing will be executed after it...
        return;
    }
}

因此,即使该字段被清除,它也将始终设置回现有值加上按钮文本的值...

我“认为”你想要做的是先计算字段的值,然后处理按钮按下...

根据修改更新

// You assign the reference to the `String` maintained by the text field...
String text = field.getText(); 
System.out.println(text); // prints "0+" like expected (after pressing number)

/* Checks for operation chars */
for(int i = 0; i < ops.length; i++) {
    if(text.endsWith(ops[i])) {
        // You assign a NEW reference to the text field, this
        // won't change the contents of text as they are different
        // references...
        field.setText("");
        System.out.println("called"); //gets printed
        break;
    }
}

// text has not changed, this variable and the field contents are not
// magically linked
System.out.println(text); //even when "called" prints, text is not ""

另外,请记住,Java 中的String 是不可变的,这意味着一旦创建,Strings 的内容就无法更改,它可以简单地重新分配...

【讨论】:

  • 这是我的一个问题(通过最小化代码)。 “+”按钮使用buttons[11],因此在我的原始代码中它不会触发循环if(e.getSource() == buttons[i]) 中的条件。让我解决这个问题
  • 你的switch语句field.setText(text + e.getActionCommand());....还是有同样的问题。
  • 但是 switch 语句的情况只有在我按“+”时才会触发。每次按下按钮时,它首先检查操作员。如果有,请清除该字段,然后开始添加数字。但它好像跳过了清理阶段。如果当前文本与操作员一起发送,则该字段应立即清除(然后设置为“0”或任何数字)。 switch 语句案例是在按下操作员按钮时在我的字段文本的末尾添加操作员。它不会在与"called" 打印时相同的方法调用中触发
  • 但是,您已经在文本字段中保留了 WAS 的引用,然后您将其添加回...
  • 欢迎来到森林,小心树木;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-02
  • 2012-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
相关资源
最近更新 更多