倒计时器添加按钮点击事件问题

发布网友 发布时间:2022-04-20 03:44

我来回答

1个回答

热心网友 时间:2022-04-22 23:44

public class TTT {

Timer timer;

TTT() {
JButton button;
button = new JButton();
button.setText("1");
button.setBackground(Color.gray);
button.setPreferredSize(new Dimension(300, 300));
JMenu mnTimer = new JMenu("Timer");
timer = new Timer(1000, new ButtonAction(10, button));
timer.setRepeats(true);
JFrame jf = new JFrame();
jf.setBounds(20, 20, 300, 320);
JMenuBar menuBar = new JMenuBar();
jf.setJMenuBar(menuBar);
menuBar.add(mnTimer);
JMenuItem mntmKaishi = new JMenuItem("Start");
mnTimer.add(mntmKaishi);
mntmKaishi.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
timer.start();
}
});
JMenuItem mntmExit = new JMenuItem("Exit");
mnTimer.add(mntmExit);
mntmExit.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
timer.stop();
}
});
JPanel jp = new JPanel();
jf.setContentPane(jp);
jf.setDefaultCloseOperation(3);
jf.setVisible(true);
jp.add(button);
jp.setPreferredSize(new Dimension(300, 300));
}

class ButtonAction implements ActionListener {

int i = 10;
JButton button;

ButtonAction(int i, JButton button) {
this.i = i;
this.button = button;
}

public void actionPerformed(ActionEvent e) {
i--;
button.setText("倒计时:" + "\n" + i + "秒");
button.setText(i + "秒");
Font f = new Font("倒计时:" + '\n' + i + "秒", 10, 50);
button.setFont(f);
if (i == 0) {
timer.stop();
JOptionPane.showMessageDialog(button, "时间到!!!");
}
}
}

public static void main(String[] args) {
new TTT();
}
}
声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。
E-MAIL:11247931@qq.com