如何在Swings中实现ActionListener的延迟?

时间:2014-04-17 19:58:58

标签: java swing

我有一个Swing应用程序,我想添加一些延迟。我有一个关闭按钮,在点击时应显示JTextArea,显示"关闭数据库连接...."然后执行Database.databaseClose()方法和System.exit()。我已经尝试使用Thread.sleep()方法,如下面的代码中的延迟。当我执行程序时,屏幕冻结2秒钟然后关闭而不显示JTextArea。关闭按钮和JTextArea直接添加到JFrame。

我想要的是,单击关闭按钮时,应立即显示JTextArea,然后应用程序应延迟2秒,最后实现Database.databaseClose()方法并退出程序。 Database.databaseClose()方法工作得很好。

我是Swings的初学者,如果有人可以修改代码来实现上述要求,我将非常感激。谢谢!

以下是代码段:

    JButton btnClose = new JButton("Close");
    btnClose.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {
            JTextArea txtrClosingDatabaseConnections = new JTextArea();

            txtrClosingDatabaseConnections.setText("\r\n\tClosing database connections....");

            getContentPane().add(txtrClosingDatabaseConnections);
            validate();
            repaint();

            /*
             try 
             {
                Thread.sleep(2000);
             }
             catch (InterruptedException e2)
             {
                e2.printStackTrace();
             }
            */

            try 
            {
                Database.databaseClose();
            }
            catch (Exception e1) 
            {
                e1.printStackTrace();
            }

            System.exit(0);

        }
    });

    getContentPane().add(btnClose);

3 个答案:

答案 0 :(得分:3)

您的代码正在Event Dispatch Thread上执行,因此您无法使用Thread.sleep(),因为这会阻止EDT并阻止它重新绘制GUI。

您需要为数据库处理使用单独的Thread。阅读Concurrency上Swing教程中的部分以获取更多信息,以及使用SwingWorker为您管理此主题的解决方案。

答案 1 :(得分:3)

  

Timer是解决方案。 Swing计时器的任务在事件派发线程中执行。这意味着任务可以安全地操作组件,但这也意味着任务应该快速执行。

您可以通过两种方式使用Swing计时器:

  1. To perform a task once, after a delay.
    例如,工具提示管理器使用Swing计时器来确定何时显示工具提示以及何时隐藏它。
  2. To perform a task repeatedly.
    例如,您可以执行动画或更新显示目标进度的组件。
  3. 请详细了解http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html

答案 2 :(得分:3)

Hej,这是一个在Swing中的JFrame上初始化JMenuBar的示例方法。

private JMenuBar initMenuBar() {
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");

        exitApp = new JMenuItem("Exit App");
        exitApp.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Timer t = new Timer(2000, new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        System.exit(0);
                    }
                });

                JOptionPane.showMessageDialog(getParent(), "Closing App in 2 Seconds");
                t.start();
            }

        });

        fileMenu.add(exitApp);
        menuBar.add(fileMenu);
        return menuBar;
    }

愿它能帮到你。它会创建一个JOptionPane,必须通过单击“确定”关闭,然后JFrame将在2秒后关闭。