2016-11-13 72 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();