使用添加按钮在文本字段中添加数字 java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14207994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
adding numbers in textfield with add button java
提问by user1956858
I am trying to write a textfield
and a button using applet. The main problem is that I cannot seem to figure out how to add multiple numbers such as one number then hit the add button then the number then add button and display the total as well in the same textfield like the basic calculator program. Here is what I've got so far:
我正在尝试textfield
使用小程序编写一个和一个按钮。主要问题是我似乎无法弄清楚如何添加多个数字,例如一个数字然后点击添加按钮然后点击数字然后添加按钮并在与基本计算器程序相同的文本字段中显示总数。这是我到目前为止所得到的:
import java.applet.Applet;
import java.awt.Button;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class addition extends Applet implements ActionListener {
TextField tf;
Button btnAdd;
Button btnEqual;
Button btnExit;
public addition() {
tf = new TextField(15);
btnAdd = new Button(" + ");
btnEqual = new Button(" = ");
btnExit = new Button("exit");
}
public void init() {
add(tf);
add(btnAdd);
add(btnEqual);
add(btnExit);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnAdd.getFocusListeners()) {
tf.setText("text goes here");
}
}
}
回答by THarms
try
尝试
tf.repaint();
to tell the Component to layout again with the new value.
告诉组件使用新值重新布局。
This is a classic failure in programming. This is only automatic with a valid data binding e.g. when a table is setup with data binding.
这是编程中的典型失败。这仅在具有有效数据绑定的情况下才会自动进行,例如,当使用数据绑定设置表时。
EDIT:Your code looks fine so far, the source of the action is the button itself not a FocusListener :
编辑:到目前为止,您的代码看起来不错,操作的来源是按钮本身而不是 FocusListener :
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnAdd) {
tf.setText("text goes here");
// create sum here (class variable, should be 0 at start)
// update TF with new value
// tell TF or Panel underneath to layout newly
}
if (e.getSource() == btnEqual){
// update value
// layout newly
}
}