在setText(“”)之后JTextField没有清除

时间:2014-05-29 01:25:33

标签: java swing jtextfield settext

在解释之前,这是代码:

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是否包含数学运算符(我已将其存储在String数组中)。如果是,请在继续之前“清除”文本字段。

问题是:我的程序告诉我代码已执行(“调用”打印出来),但我的结果显示,好像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 ""

为什么不清除? :■

1 个答案:

答案 0 :(得分:3)

有几个问题......

首先,您的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;
    }
}

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

我&#34;思考&#34;你想做的,首先计算字段的值,然后按下按钮...

根据修改进行了更新

// 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是不可变的,这意味着一旦创建String的内容就无法更改,只需重新分配即可...