我试图使用线程“淡化”JPanel。实际上并没有褪色,但他通过改变rgb值逐渐将颜色变为黑色。
public class MostraPainel {
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setSize(500, 500);
// Centraliza
jf.setLocationRelativeTo(null);
Painel painel = new Painel();
jf.setContentPane(painel);
jf.setVisible(true);
new Thread(painel).start();
}
}
所以我想按照我设置的间隔重新绘制面板,查看面板类
public class Painel extends JPanel implements Runnable {
// alt+s
/**
* Create the panel.
*/
int cont = 0;
public Painel() {
setBackground(Color.BLACK);
}
@Override
protected void paintComponent(Graphics g) {
if (cont == 1)
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// System.out.println(cont);
g2.setColor(new Color(cont, cont, cont));
int w = getWidth() - 1;
int h = getHeight() - 1;
int widthQ = w / 8;
int heightQ = h / 8;
int size = 0;
int cont = 0;
for (int j = heightQ; j < getHeight(); j += (2 * heightQ)) {
for (int i = size; i < getWidth(); i += (2 * widthQ)) {
if (cont == 0)
g2.fillRect(i + widthQ, 0, widthQ, heightQ);
g2.fillRect(i + widthQ, j + heightQ, widthQ, heightQ);
g2.fillRect(i, j, widthQ, heightQ);
}
cont++;
}
}
@Override
public void run() {
// TODO Auto-generated method stub
this.cont++;
for (cont = 0; cont < 255; cont++) {
if (this.cont < 255) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.repaint();
}
}
}
}
因此paintComponent()方法在面板上绘制图像,方法run()重绘并将sum 1加到cont变量中。这实际上有效,但每次执行repaint()时屏幕都不会更新,因此淡入淡出的FPS较低。如果我继续调整屏幕大小,那么淡入淡出效果很好,那么问题是什么?
答案 0 :(得分:0)
我通过添加此行来解决问题
Toolkit.getDefaultToolkit().sync();
感谢您的帮助