2016-11-13 74 views
0

我有一個動態設置Jtogglebutton的背景顏色的問題。我想讓Jtoggle按鈕像指示燈一樣閃爍,並在特定時間開啓和關閉,如500毫秒。我試圖重寫paint和paintComponent方法。但也不能成功。我卡住了。這是我的代碼,感謝您的幫助。Jtogglebutton動態設置背景

領導類:

public class Led extends JToggleButton { 
private Color okColor = Color.GREEN; 
private Color notOkColor = Color.RED; 
private static int BLINK_FREQUENCY=500; 

public Led() { 
    this.setPreferredSize(new Dimension(50, 50)); 
    timer.start(); 
} 

Timer timer=new Timer(BLINK_FREQUENCY, new ActionListener() { 

    @Override 
    public void actionPerformed(ActionEvent e) { 
      setBackground(okColor); 
      System.out.println("ok"); 
      try { 
       Thread.sleep(BLINK_FREQUENCY); 
      } catch (InterruptedException e1) { 
       e1.printStackTrace(); 
      } 
      setBackground(notOkColor); 
      System.out.println("notok"); 
    } 
}); 

}

大型機級:

public class MainFrame { 

private JFrame frame; 
private Led led; 
private JPanel panel; 

public MainFrame() { 
    initializeComponents(); 
} 

private void initializeComponents() { 
    frame = new JFrame("Blinking Led"); 
    frame.setSize(400, 400); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setLocationRelativeTo(null); 
    { 
     panel = new JPanel(); 
     led = new Led(); 
     panel.add(led); 
     frame.add(panel); 
    } 

} 

public void setVisible(boolean visible) { 
    frame.setVisible(visible); 
} 

}

+0

1)爲了更好地幫助更快,發佈[MCVE]或[短的,獨立的,正確的示例](http://www.sscce.org/)。 2)請參閱[檢測/修復代碼塊的懸掛緊密支架](http://meta.stackexchange.com/q/251795/155831),以解決問題,我不再擔心修復問題。 –

+0

我不確定我是否理解,您希望顏色每隔500毫秒切換一次,或者您希望按鈕的狀態切換,然後觸發顏色切換? –

+0

我想每隔500ms切換一次按鈕的顏色。國家並不重要。 –

回答

-1

我沒有看到這一點,使用Timer類,而只是一個簡單的線程應該工作

public Led() { 
    this.setPreferredSize(new Dimension(50, 50)); 
    thread.start(); 
} 

Thread thread = new Thread(() -> { 
        while (true) { 
         if (getBackground().equals(notOkColor)) { 
          setBackground(okColor); 
         } else { 
          setBackground(notOkColor); 
         } 
         try { 
          Thread.sleep(BLINK_FREQUENCY); 
         } catch (InterruptedException e) { 
          e.printStackTrace(); 
         } 
        } 
       }); 
+0

:)謝謝。這對我幫助很大。你有任何想法使用塗料方法嗎? –

+0

關鍵是要在EDT上運行與GUI相關的代碼.... – Antoniossss

+0

@Antoniossss否使用爲您提供ActionListener和ActionEvent的類絕對沒有任何意義,您將永遠無法在代碼中使用它。正確的方法是使用SwingUtils.invokeLater()在EDT上手動調用revalidate()和repaint(),但在這種情況下甚至不需要這樣做。 –

1

它幾乎完成:

Timer timer=new Timer(BLINK_FREQUENCY, new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent e) { 
      setBackgroundColor(getBackgroundColor()==okColor ? noOkColor:okColor); 
    } 
    }); 

timer.start();