繁体   English   中英

摆动JProgressBar花费在方法上的时间

[英]Swing JProgressBar for time spent in method

我有一种将数据集导入数据库的方法,我想有一个进度条,通知用户单击按钮后正在导入。 我已经对进度条进行了编码,该进度条可以进行硬编码的持续时间,但是显然我希望它根据导入的持续时间是动态的。 我尝试了很多不同的尝试,但都没有成功,所以希望能对您有所帮助! :) 谢谢! 编辑:这是导入按钮的动作侦听器->

        btnImportADataset.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                progressBar(10);
                SystemAdminHome.testMethod();`enter code here`
                ExcelReadInReadOut.writeToDB();
            }
        });

以下是在动作侦听器中调用的方法->

    private final static int interval = 1000;
    private static int i;
    private static JLabel label;
    private static JProgressBar progBar;
    private static Timer timer;

    public static void progressBar(final long duration) {
        JFrame frame = new JFrame("Progress Bar");
        ProgressBar progBarInstance = new ProgressBar();

        progBar = new JProgressBar(0, (int) duration);
        progBar.setValue(0);
        progBar.setStringPainted(true);

        label = new JLabel("Import a dataset");

        JPanel panel = new JPanel();
        //panel.add(btnStart);
        panel.add(progBar);

        JPanel panel1 = new JPanel();
        panel1.setLayout(new BorderLayout());
        panel1.add(panel, BorderLayout.NORTH);
        panel1.add(label, BorderLayout.CENTER);
        panel1.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        frame.setContentPane(panel1);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Create a timer.
        timer = new Timer(interval, new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                if (i == duration) {
                    timer.stop();
                    btnImportADataset.setEnabled(true);
                    progBar.setValue(0);
                    String str = "<html>" + "<font color=\"#FF0000\">" + "<b>"
                            + "Import completed." + "</b>" + "</font>"
                            + "</html>";
                    label.setText(str);
                }
                i = i + 1;
                progBar.setValue(i);
            }
        });


    }

    public static void testMethod() {
        btnImportADataset.setEnabled(false);
        i = 0;
        String str = "<html>" + "<font color=\"#008000\">" + "<b>"
                + "Import is in process......." + "</b>" + "</font>"
                + "</html>";label.setText(str);timer.start();
    }

请参阅https://stackoverflow.com/a/10774277/66207,使用SwingWorker的doInBackground方法进行繁重的工作,并使用publish方法发布进度。

[编辑]链接到正确答案,而不是问题。

您可以尝试这样的东西(未经测试):

JProgressBar jp = new JProgressBar();
jp.setMinimum(System.currentTimeMillis());

while(import) {
    jp.setValue(System.currentTimeMillis());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM