复习定时器 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class p1 extends JFrame { private JButton openButton; public p1() { openButton = new JButton("打开新窗口"); openButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Timer timer = new Timer(5000, new ActionListener() { // 5000毫秒后触发 @Override public void actionPerformed(ActionEvent e) { JFrame newWindow = new JFrame("新窗口"); newWindow.setSize(300, 200); newWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 当新窗口关闭时结束程序 newWindow.setVisible(true); dispose(); // 关闭当前窗口 } }); timer.setRepeats(false); // 只执行一次 timer.start(); // 开始定时器 } }); this.setLayout(new FlowLayout()); this.add(openButton); this.setSize(300, 200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 当主窗口关闭时结束程序 this.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { // 在事件调度线程中运行窗口的代码 @Override public void run() { new p1(); // 创建窗口 } }); } }
实训作业 day1
最新推荐文章于 2024-08-18 23:25:39 发布