我正在研究需要驗證Web地址的Java7 Swing「嚮導」類型的項目,然後才能繼續執行嚮導的下一步。驗證需要通過互聯網訪問URL以驗證預期資源是否可用。在某些情況下,這可能需要幾秒鐘時間,足以混淆用戶。如何在點擊時更新JButton的外觀?
作爲一個快速解決方案,我想禁用「下一步」按鈕,並在驗證運行時更改顯示文本,以便用戶知道嚮導正在工作,而不是掛在任何東西上。問題是,當我添加代碼來修改JButton時,直到驗證完成後纔會發生任何更改。即使我更改了按鈕,並在之前致電revalidate()
執行驗證方法,也是如此。
這裏是什麼,我已經試過的摘錄:
// create next button
next = new JButton("Next", new ImageIcon(getClass().getResource("/navigate_right.png")));
next.setActionCommand("MYACTION");
next.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("Is this the event dispatch thread? "
+ javax.swing.SwingUtilities.isEventDispatchThread());
System.out.println("Changing button");
next.setEnabled(false);
next.setText("Testing Connection");
next.getRootPane().revalidate();
System.out.println("Validating Service");
boolean isValidLocation = ServiceValidator.serviceExists(locationField.getText());
// ...etc...
當我運行這段代碼,行「更改按鈕」和「驗證服務」之前,在顯示的實際按鈕的變化都得到印刷。如何在打印System.out.println("Validating Service");
之前讓JButton更改?
閱讀本文後,它將回答您的所有問題以及如何解決該問題:http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html – Michael