對於我所瞭解的內容,Swing將決定什麼時候需要重新繪製,這可以解釋爲什麼paintComponent()
執行兩次。但是我做了睡16ms的,重新繪製的應用程序,睡16毫秒,重新繪製,睡16毫秒,等等:paintComponent paint兩次
while(true)
{
frame.repaint();
try{Thread.sleep(16)}catch(Exception e){}
}
應該在60fps工作。但是,FPS測量程序(如FRAPS)顯示應用程序運行速度爲120fps。所以基本上,應用程序正在做的是:並條機,並條機,睡眠,並條機,並條機,睡眠......我怎樣才能告訴擺動畫每個repaint()
電話一幀? (哦,我試過用Timer
而不是sleep()
,結果是一樣的)。
下面是例如在Oracle教程中找到的SwingPaintDemo。我添加了一個while循環,每16ms重新繪製一次。我還將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++;
}
}
}
爲了更好地幫助越早,請包括[SSCCE(http://www.sscce.org)證實說問題。 – user1329572
[將程序設置爲60FPS,但以120FPS運行?]的完全重複(http://stackoverflow.com/questions/10473637/set-program-to-60fps-but-runs-at-120fps)。 ***不要問同樣的問題兩次!*** –
哈哈我知道它是有點相同,但在這個問題中,我使用計時器,因爲你說設置FPS在60,但它看起來好像它是30 ,因爲它繪製每個幀兩次。所以問題仍然存在,定時器不是解決方案。現在我想知道如何設置paintComponent來繪製一次而不是兩次。 – user1319734