【发布时间】:2012-12-28 22:21:29
【问题描述】:
这可能是一个基本问题。但是,我已经阅读了《Java 绝对初学者编程》的第 7 章,并进入了挑战部分。我不能完全让清除按钮来解决挑战问题。
问题问:
创建一个数字小键盘,它使用按钮来更新不可编辑的文本字段,方法是将点击的数字附加到当前数字的末尾。为 Frame 使用 BorderLayout。在 BorderLayout.NORTH,放置 TextField。在中心,创建一个面板,该面板使用 GridLayout 将按钮 1 到 9 布置在三乘三网格中。在 BorderLayout.SOUTH 处,创建另一个面板,该面板具有零键和一个“清除”键,用于删除 TextField 中的当前数字。”
我认为我的主要问题在于 TextArea 附加方法。我知道我应该使用 TextField,但是根据我所做的研究,似乎不可能在 TextField 中附加。
这个问题的答案可能有助于许多新的 Java 程序员理解基本的 GUI 和事件处理。
import java.awt.*;
import java.awt.event.*;
public class CalcFacade extends GUIFrame
implements ActionListener, TextListener {
TextField tf;
TextArea ta;
Panel p1, p2;
Label clear;
Button b1, b2, b3, b4, b5, b6, b7, b8, b9, c, b0;
public CalcFacade() {
super("Calculator Facade");
setLayout(new BorderLayout());
Button b1 = new Button("1");
b1.addActionListener(this);
Button b2 = new Button("2");
b2.addActionListener(this);
Button b3 = new Button("3");
b3.addActionListener(this);
Button b4 = new Button("4");
b4.addActionListener(this);
Button b5 = new Button("5");
b5.addActionListener(this);
Button b6 = new Button("6");
b6.addActionListener(this);
Button b7 = new Button("7");
b7.addActionListener(this);
Button b8 = new Button("8");
b8.addActionListener(this);
Button b9 = new Button("9");
b9.addActionListener(this);
Button b0 = new Button("0");
b0.addActionListener(this);
Button c = new Button("Clear");
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clear.setText("");
}
});
tf = new TextField(100);
add(tf);
tf.setEnabled(false);
tf.addActionListener(this);
tf.addTextListener(this);
setVisible(false);
ta = new TextArea("", 10, 30);
add(ta);
ta.setEnabled(true);
setVisible(true);
Panel p1 = new Panel();
p1.setLayout(new GridLayout(3, 3));
p1.setBackground(Color.gray);
p1.add(b1);
p1.add(b2);
p1.add(b3);
p1.add(b4);
p1.add(b5);
p1.add(b6);
p1.add(b7);
p1.add(b8);
p1.add(b9);
Panel p2 = new Panel();
p2.setBackground(Color.gray);
p2.add(b0);
p2.add(c);
add(ta, BorderLayout.NORTH);
add(p1, BorderLayout.CENTER);
add(p2, BorderLayout.SOUTH);
pack();
setSize(400, 300);
setVisible(true);
}
public static void main(String args[]) {
CalcFacade cf = new CalcFacade();
}
public void actionPerformed(ActionEvent e) {
tf.setText(""
+((Button)e.getSource()).getLabel());
}
public void textValueChanged(TextEvent e) {
ta.append(tf.getText());
}
}
非常感谢您提前提供的所有帮助。
【问题讨论】:
-
为了追加,将文本设置为之前的内容 + 按下按钮的标签:
tf.setText(tf.getText() + ((Button)e.getSource()).getLabel())。清除按钮只是将文本字段设置为空值tf.setText("") -
点击此链接。这可能会帮助您解决问题。 Click here
标签: java user-interface event-handling append textfield