java绘制组件绘制两次
据我所知,Swing将决定何时需要重新绘制,这将解释paintComponent()
执行两次的原因。但我已经制作了一个应用程序,可以休眠16毫秒、重新绘制、休眠16毫秒、重新绘制、休眠16毫秒,等等:
while(true)
{
frame.repaint();
try{Thread.sleep(16)}catch(Exception e){}
}
它应该以每秒60帧的速度工作。但是,FPS测量程序(如FRAP)显示应用程序以120fps的速度运行。所以基本上,应用程序所做的是:画框,画框,睡眠,画框,画框,睡眠。。。如何让swing为每个repaint()
调用绘制一个帧?(哦,我试着用Timer
代替sleep()
,结果是一样的)
下面是在Oracle教程中找到的SwingPaintDemo示例。我添加了一个while循环,它将每16毫秒重新绘制一次。我还将undecorated设置为true(这是FRAPS显示每秒实际帧数的唯一方法)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
***************************************************************
* Silly Sample program which demonstrates the basic paint
* mechanism for Swing components.
***************************************************************
*/
public class SwingPaintDemo {
public static void main(String[] args) {
JFrame f = new JFrame("Aim For the Center");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Container panel = new BullsEyePanel();
panel.add(new JLabel("BullsEye!", SwingConstants.CENTER), BorderLayout.CENTER);
f.setUndecorated(true);
f.setSize(200, 200);
f.getContentPane().add(panel, BorderLayout.CENTER);
f.show();
while(true)
{
f.repaint();
try{Thread.sleep(16);}catch(Exception e){}
}
}
}
/**
* A Swing container that renders a bullseye background
* where the area around the bullseye is transparent.
*/
class BullsEyePanel extends JPanel {
public BullsEyePanel() {
super();
setOpaque(false); // we don't paint all our bits
setLayout(new BorderLayout());
setBorder(BorderFactory.createLineBorder(Color.black));
}
public Dimension getPreferredSize() {
// Figure out what the layout manager needs and
// then add 100 to the largest of the dimensions
// in order to enforce a 'round' bullseye
Dimension layoutSize = super.getPreferredSize();
int max = Math.max(layoutSize.width,layoutSize.height);
return new Dimension(max+100,max+100);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension size = getSize();
int x = 0;
int y = 0;
int i = 0;
while(x < size.width && y < size.height) {
g.setColor(i%2==0? Color.red : Color.white);
g.fillOval(x,y,size.width-(2*x),size.height-(2*y));
x+=10; y+=10; i++;
}
}
}
# 1 楼答案
1)基本上,
paintComponent()
内的方法不需要调用repaint()
2)当需要重新绘制时,Swing GUI会自动调用
paintComponent()
3)对于今天使用
Graphics(2D)
的Swing GUI,默认情况下使用Swing Timer
4)为
frame.repaint();
调用重复repaint
的代码,删除该5)
frame.repaint();
是一种有用的方法,如果您add
/remove
/modify
已经可见你是说
编辑,你上一个问题中链接的
@trashgod
代码有什么问题,关于JPanel's repaint
(this.repaint()
)