簡體   English   中英

當我的JButton忙時,是否可以顯示正在加載的JLabel?

[英]Is there a way to display a loading JLabel when my JButton is busy?

我已經上傳了代碼的特定部分,希望這足以理解我的問題。 我在具有多個按鈕的框架中使用p6面板,其中一個按鈕顯示此面板。

該面板p6具有兩個按鈕。 一次單擊check_api ,該程序需要一些時間來執行,並且對於用戶來說,似乎應用程序已掛起。 因此,我嘗試添加一種在按鈕繁忙時顯示等待消息的方法。 但是這樣做時,我的面板丟失了用戶定義的尺寸。

有沒有辦法顯示等待消息而不影響面板尺寸?

public static void prepare_url(JPanel p6, JPanel content, int count) {
    InnerOperations.removeexcept(6, content);
    if (count != 1) {
        p6.removeAll();
        p6.revalidate();
        System.out.println("Count is greater than 1");
    }
    JPanel p_back = new JPanel();
    JTextField field = new JTextField(" Enter url(s) with delimiter ';'");
    JButton check_list = new JButton(" CHECK URL LIST STATUS");
    JButton check_api = new JButton(" CHECK  PREDEFINED API LIST");
    p_back.add(check_list);
    p_back.add(field);
    p_back.add(l_check);
    p_back.add(check_api);
    check_api.setBounds(200, 130, 400, 30);
    l_check.setBounds(50, 300, 600, 20);
    field.setBounds(200, 50, 400, 30);
    check_list.setBounds(200, 90, 400, 30);
    p6.add(p_back);
    p_back.setBounds(0, 0, 800, 600);
    check_list.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            String url_pref 
            String list[] = url_pref.split(";");
            int i = 0;
            while (i < list.length) {
                try {
                    // thread1.start();
                    prepareurl(p6, p_back, list, list.length);
                    // thread1.stop();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                i++;

            }
        }
    });
    check_api.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // thread2.start();
            // p_back.removeAll();
            //check_api.setText("Will load in a while");
            prepare_api(p6, content, p_back);
            // thread2.stop();

        }
    });

}
public static void userwait(JPanel ppanel)
{
    JLabel waiting = new JLabel();
    ppanel.add(waiting);
    waiting.setText("Please Wait......");
    waiting.setBounds(200, 200, 400, 30);
}   

在EDT中執行長時間運行的任務通常不是一個好主意-改用SwingWorker ,請參閱示例“使用SwingWorker 提高應用程序性能” 您可以只在啟動工作線程之前顯示一些文本,並禁用按鈕以防止用戶再次單擊:

public class SwingworkerExample extends JFrame {

    private JButton startBtn = new JButton("Start");
    private JProgressBar progressBar = new JProgressBar(0, 100);
    private JLabel progressLbl = new JLabel("");
    private JLabel statusLbl = new JLabel("");

    public static void main(String... args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                SwingworkerExample swe = new SwingworkerExample("SwingWorker: progress");
                swe.setVisible(true);
            }
        });
    }

    public SwingworkerExample(String title) {
        super(title);
        setupUI();
        startBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                startWorkerThread();
            }
        });
    }

    private void startWorkerThread() {
        // Disable JButton:
        startBtn.setEnabled(false);
        // Show info
        statusLbl.setText("running...");
        progressLbl.setText("...");

        /*
         * Create SwingWorker<Boolean, Integer> where
         * Boolean : type for thread result, use "Void" if no return value
         * Integer : type for published values
         */
        SwingWorker<Boolean, Integer> swingWorker = new SwingWorker<Boolean, Integer>() {

            @Override
            protected Boolean doInBackground() throws Exception {
                // WARN: do not update the GUI from within doInBackground(), use process() / done()!

                // Do something ... 
                // prepareurl(p6, p_back, list, list.length);
                // 
                for (int i = 0; i <= 100; i++) {
                    Thread.sleep((int) (Math.random() * 60));
                    // Use publish to send progress information to this.process() [optional]
                    publish(i);
                }
                return true;
            }

            @Override
            protected void process(List<Integer> chunks) {
                // handle published progress informations / update UI
                StringBuilder sb = new StringBuilder();
                chunks.forEach(val -> sb.append(" ").append(val));
                progressLbl.setText(String.format("processing: %s%n", sb));
                int progress = chunks.get(chunks.size() - 1);
                progressBar.setValue(progress);
            }

            @Override
            protected void done() {
                // Swingworker finished - update UI / handle result
                try {
                    Boolean result = get();
                    statusLbl.setText("DONE. Result= " + result);
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                    statusLbl.setText("Error: " + e.getMessage());
                }
                // Enable JButton
                startBtn.setEnabled(true);
            }
        };
        swingWorker.execute();
    } // end: startWorkerThread

    private void setupUI() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(240, 160);
        setLayout(new GridBagLayout());
        GridBagConstraints gc = new GridBagConstraints();
        gc.fill = GridBagConstraints.BOTH;
        gc.weightx = 1;
        gc.weighty = 1;
        gc.gridx = 0;
        gc.weighty = 1;

        gc.gridy = 0;
        add(startBtn, gc);

        gc.gridy = 1;
        add(progressBar, gc);

        gc.gridy = 2;
        add(statusLbl, gc);

        gc.gridy = 3;
        add(progressLbl, gc);
    }
}

有兩個選擇:

  1. 您可以使用不確定的JProgressBar 有關更多信息和工作示例,請參見Swing教程中有關如何使用進度條的部分。

  2. 您可以使用GlassPane在面板頂部顯示消息。 有關此方法的示例,請參見禁用玻璃窗格

暫無
暫無

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

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