【发布时间】: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