【发布时间】:2019-05-12 04:25:15
【问题描述】:
编写程序以在按下 +1 按钮时递增计数器,然后当计数器达到某个数字时,移除 +1 按钮并用 +2 按钮替换它,依此类推。我首先创建了两个按钮,但只是将 btnCount1 设置为 setVisible(false)。当某个数字通过时,我使 btnCount 不可见并且 btnCount1 可见,并从那里增加 2。当达到 10 次点击时,btnCount 消失,但 btnCount1 不出现。
我尝试过创建一个 if(arg0.equals(btnCount1)),然后从那里增加 2。我尝试将 add(btnCount1) 放在 else if 语句中,以便在 elseif 条件为真后创建它。
public class AWTCounter extends Frame implements ActionListener
private Label lblCount;
private TextField tfCount;
private Button btnCount;
private Button btnCount1;
private int count = 0;
public AWTCounter() {
setLayout(new FlowLayout());
lblCount = new Label("Counter");
add(lblCount);
tfCount = new TextField(count + "",10);
tfCount.setEditable(false);
add(tfCount);
btnCount = new Button("Add 1");
btnCount1 = new Button("Add 2");
add(btnCount);
add(btnCount1);
btnCount1.setVisible(false);
btnCount.addActionListener(this);
btnCount1.addActionListener(this);
setTitle("AWT Counter");
setSize(500,500);
}
public static void main(String[]args) {
AWTCounter app = new AWTCounter();
}
public void actionPerformed(ActionEvent arg0) {
if(count <= 10) {
++count; //Increase the counter value
tfCount.setText(count + "");
}else if(count > 10) {
btnCount.setVisible(false);
btnCount1.setVisible(true);
count += 2;
tfCount.setText(count + "");
}
}
【问题讨论】:
-
为什么要使用 AWT?请参阅 this answer 了解放弃 AWT 组件以支持 Swing 的许多充分理由。