簡體   English   中英

單擊“開始”按鈕后如何運行進度欄?

[英]How do I make my progress bar run when the “START” button is clicked?

我目前正在嘗試在Java gui中插入進度條。 但是,當我單擊“開始”按鈕時,進度條無法運行。 在cmd中運行的所有不同批處理文件都必須完成,然后進度條才能運行。 但是有什么意義呢? 我希望它在按下“開始”按鈕時運行,並且當cmd中運行的所有不同批處理文件結束時,進度欄也將停止。

這是我的代碼:

JLabel ProgressBar = new JLabel("Progress Bar: ");
ProgressBar.setFont(new Font("Arial", Font.BOLD, 12));
ProgressBar.setBounds(100, 285, 180, 53);
contentPane.add(ProgressBar);
final JProgressBar aJProgressBar = new JProgressBar(JProgressBar.HORIZONTAL);
aJProgressBar.setBounds(185,305,184,15);
contentPane.add(aJProgressBar);

//when start button is selected
btnStart.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent args)
    {
        //the process starts
        JStartTimeTextField.setText(dateFormat.format(date));

        //the progress bar should show it running (by right)
        aJProgressBar.setIndeterminate(true);

        try 
        {
            //create new process    
            String command = "cmd /c start /wait" +DetectDrive+"\\starting.bat";

            //run process
            Process p = Runtime.getRuntime().exec(command);

            //cause this process to stop until process p is terminated
            p.waitFor();
        } 
        catch (IOException | InterruptedException e1)
        {
            e1.printStackTrace();
        }

        ......

        Date newDate = new Date();
        JStartTimeTextField.setText(dateFormat.format(newDate));

        //the progress bar should stop running (by right)
        //aJProgressBar.setIndeterminate(false);
    }
});

因此,右擊...單擊“ START”按鈕時,應該顯示startTime並且進度條應該正在運行。 但是,僅當cmd中的所有批處理文件完成運行時,才會顯示startTime。

但就目前而言,進度欄是我的首要任務。 如何確保單擊“開始”按鈕時進度條運行,並且全部完成后進度條停止?

給予的任何幫助將不勝感激!

您正在使用同一線程來更新JProgressBar和運行腳本。 問題是您等待Process終止( p.waitFor() ),因此線程將等待而不更新JProgressBar 正確的解決方案是使用SwingWorker 但是我認為您可以通過啟動一個新的Thread來運行您的腳本來使事情運行。

就像是:

public void actionPerformed(ActionEvent args)
{
    //the process starts
    JStartTimeTextField.setText(dateFormat.format(date));

    //the progress bar should show it running (by right)
    aJProgressBar.setIndeterminate(true);
    new Thread()
    {
    public void run()
    {
    try 
    {
        //create new process    
        String command = "cmd /c start /wait" +DetectDrive+"\\starting.bat";

        //run process
        Process p = Runtime.getRuntime().exec(command);

        //cause this process to stop until process p is terminated
        p.waitFor();
    } 
    catch (IOException | InterruptedException e1)
    {
        e1.printStackTrace();
    }
    }
    }.start();   

    ......

    Date newDate = new Date();
    JStartTimeTextField.setText(dateFormat.format(newDate));

    //the progress bar should stop running (by right)
    //aJProgressBar.setIndeterminate(false);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM