2014-09-21 65 views
0

我有一個JButton,我希望當我點擊這個按鈕,它顯示一個圖標,然後在3秒後隱藏的圖標,並顯示在按鈕文本。顯示一個JButton的圖標,隱藏

在動作監聽

我試過這段代碼:

JButton clickedButton = (JButton) e.getSource(); 
clickedButton.setIcon(new ImageIcon(images.get(clickedButton.getName()))); 
try { 
    Thread.sleep(3000);     
} catch(InterruptedException ex) { 
    Thread.currentThread().interrupt(); 
} 
clickedButton.setText("x"); 
clickedButton.setIcon(null); 

的問題是,當我點擊按鈕,3分鐘的程序塊然後在按鈕上顯示的文字「×」。

我該如何解決這個問題?

回答

2

不要Swing事件線程調用Thread.sleep(...)自認爲凍結線程,並與它的GUI。請使用Swing Timer。例如:

final JButton clickedButton = (JButton) e.getSource(); 
clickedButton.setIcon(new ImageIcon(images.get(clickedButton.getName()))); 

new Timer(3000, new ActionListener(){ 
    public void actionPerformed(ActionEvent evt) { 
    clickedButton.setText("x"); 
    clickedButton.setIcon(null); 
    ((Timer) evt.getSource()).stop(); 
    } 
}).start(); 
1

至於建議你不需要使用的Thread.Sleep使用Swing Timer執行此任務。單擊該按鈕時

// Declare button and assign an Icon. 
Icon icon = new ImageIcon("search.jpg"); 
JButton button = new JButton(icon);  
ChangeImageAction listener = new ChangeImageAction(button); 
button.addActionListener(listener); 

下面ChangeImageAction類將做必要的行動。 當你點擊按鈕時,一個動作被觸發,在這個動作中,我們將調用定時器的動作偵聽器,我們將按鈕的圖標設置爲空,並給按鈕一個標題。

class ChangeImageAction implements ActionListener { 

    private JButton button; 

    public ChangeImageAction(JButton button) { 
     this.button = button; 
    } 

    ActionListener taskPerformer = new ActionListener() { 
     public void actionPerformed(ActionEvent evt) { 
      button.setIcon(null); 
      button.setText("Button"); 
     } 
    }; 

    @Override 
    public void actionPerformed(ActionEvent arg0) { 
     Timer timer = new Timer(3000 , taskPerformer); 
     timer.setRepeats(false); 
     timer.start(); 
    } 

} 

P.S:我試圖定時器在第一時間感謝@Hovercraft全面的建議鰻魚爲。