我在Java中创建了一个简单的程序,我希望在单击“restart”numClick
时将JMenuItem
变量值设置为0。我现在所拥有的并没有改变任何事情。
代码:
public class Tests {
JButton b1 = new JButton("Click Me");
public int numClick = 0;
JLabel l1 = new JLabel("You have clicked the button 0 times");
public Tests() {
frame();
}
public void frame() {
JFrame f = new JFrame();
f.setVisible(true);
f.setSize(500,500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel();
JMenuBar mb = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem exit = new JMenuItem("Exit");
JMenuItem restart = new JMenuItem("Restart");
p.add(b1);
p.add(l1);
mb.add(file);
file.add(exit);
file.add(restart);
f.add(p);
f.setJMenuBar(mb);
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
restart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
numClick = 0;
}
});
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
numClick++;
l1.setText("You have clicked the button " + numClick + " times");
}
});
}
public static void main(String[] args) {
new Tests();
}
}
答案 0 :(得分:3)
只需更新重启动作监听器中的文本
restart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
numClick = 0;
l1.setText("You have clicked the button " + numClick + " times");
}
});
答案 1 :(得分:2)
看来你已经快到了。在将numClick设置为0之后,只需在重启的ActionListener actionPerformed方法中添加行l1.setText("You have clicked the button " + numClick + " times");
。就是这样。
restart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
numClick = 0;
// simply add this line, that's it.
l1.setText("You have clicked the button " + numClick + " times");
}
});