更改背景颜色时,JFrame会闪烁

时间:2014-04-29 01:51:14

标签: java multithreading swing jframe setbackground

我制作了一个窗口,每750毫秒更改一次背景颜色......但是JFrame会像这样闪烁......

error

我想要这样的东西......

enter image description here

我发现了一些像这样的解决方案:

1.-Frame.getContentPane()的setBackground(颜色);
2. - 制作一个新的线程
3.-Frame.getContentPane()重绘();

但它不起作用

我的代码......

  

Thread ciclo = new Thread(new Runnable(){

        float c=1f;
        @Override
        public void run() {
            while(true){
            Frame.getContentPane().setBackground(Color.getHSBColor((c/360), 1, 1));
            Frame.getContentPane().repaint();                
            c=(c>=360)?1:c+5;
            try{Thread.sleep(750);}catch(Exception e){}
            }
        }
    });
    ciclo.start();

我该如何解决这个问题? 谢谢你的建议

1 个答案:

答案 0 :(得分:3)

您试图在后台线程中更改Swing状态,从而违反了Swing Threading规则。使用Swing Timer可能会解决您的问题。

new Timer(750, new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    contentPane.setBackground((Color.getHSBColor((c/360), 1, 1));
    contentPane.repaint();
    c= (c >= 360) ? 1 : c + 5;
  }
}).start();

修改或更好:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

@SuppressWarnings("serial")
public class BackgroundColorChange extends JPanel {
   private static final int PREF_W = 400;
   private static final int PREF_H = PREF_W;
   private static final int TIMER_DELAY = 75;

   public BackgroundColorChange() {
      new Timer(TIMER_DELAY, new ActionListener() {
         private int c = 1;

         @Override
         public void actionPerformed(ActionEvent arg0) {
            setBackground(Color.getHSBColor((float) c / 360, 1f, 1f));
            repaint();
            c = (c >= 360) ? 1 : c + 5;
         }
      }).start();
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   private static void createAndShowGui() {
      BackgroundColorChange mainPanel = new BackgroundColorChange();

      JFrame frame = new JFrame("BackgroundColorChange");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}