简体   繁体   中英

JFrame color change

I have a JFrame that appears at the end of a timer. The code below pops up the frame and a sound. The color of the frame is set from a menu and then it's given to the frame. I need the frame to alternate between default color and the color i select in the menu. Thanks in advance

new Thread(new Runnable()
      {
        public void run()
        {
            JFrame frame= new JFrame(); 
    frame.setVisible(true);
            frame.setSize(600, 400);
            frame.setLocation(200, 200);
            frame.setTitle("ALARM");
            frame.getContentPane().setBackground(GUI.this.timerPanel.colorButton.getBackground());  // *This is the source for the color i select in the menu* 
            JLabel welcome = new JLabel("",SwingConstants.CENTER);
            welcome.setFont(new Font("Serif", Font.PLAIN, 48));
            welcome.setText("ALARM ALARM ALARM");
            frame.add(welcome);
            new SoundEngine().playSound();





        }
      })

        .start();

Swing isn't Thread friendly, try learning about SwingUtility.InvokeLater .

To change Color use JFrame.setBackGround(color) .

Now how will you toggle?

For me the best way is to create a Class , named Util .

public class Util{
     private static int ser=0;
     private static Color[] backColor=new Color[]{Color.red,Color.green,Color.white};
     public static void setBC(JFrame frame){
         frame.setBackGround(backColor[ser++%backColor.lenght]);
}

Now on your extended JFrame class or section just call Util.setBC(frame) .

It changes between these three color, you can add more or even remove soem as you wish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM