2

这大概是个初级问题。但是,我已经阅读了《Java 绝对初学者编程》的第 7 章,并进入了挑战部分。我不能完全让清除按钮来解决挑战问题。

问题问:

通过将单击的数字附加到其当前数字的末尾,创建一个使用 Buttons 更新不可编辑的 TextField 的数字小键盘。为 Frame 使用 BorderLayout。在 BorderLayout.NORTH,放置 TextField。在中心,创建一个面板,该面板使用 GridLayout 将按钮 1 到 9 布置在三乘三网格中。在 BorderLayout.SOUTH 处,创建另一个具有零键和“清除”键的面板,用于删除 TextField 中的当前数字。”

我认为我的主要问题在于 TextArea append 方法。我知道我应该使用 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());
}
}

我非常感谢您提前提供的所有帮助。

4

2 回答 2

1

TextField 不需要只监听按钮的事件。

要将数字添加到末尾,只需将文本设置为 TextField 中已有的内容加上按钮标签。

只有一个 ActionListener 和一个 actionPerformed 方法;识别按钮并适当设置 TextField 即 c.addActionListener(this);

public void actionPerformed(ActionEvent e)
{
    Button b = (Button) e.getSource();

    if (b.getLabel().equals("Clear"))
    {
        tf.setText("");
    }
    else
    {
        tf.setText(tf.getText() + b.getLabel());
    }
}
于 2012-12-29T02:06:36.137 回答
0

当我猜你想调用它时,看起来你ActionListener的“清除”按钮正在调用。setText("")Label clearTextField tf

于 2012-12-28T22:28:00.113 回答