我有一個小Rect的遊戲,它正在移動,我需要通過在我的onUpdate
方法中執行this.update(MyGraphics)
來更新Graphics
,該方法每50毫秒調用一次。但是,當我這樣做this.update(MyGraphics)
我所有的buttons
和textfields
都會出現問題。JFrame(Swing)更新(圖形)錯誤
有人知道如何解決它嗎?
我有一個小Rect的遊戲,它正在移動,我需要通過在我的onUpdate
方法中執行this.update(MyGraphics)
來更新Graphics
,該方法每50毫秒調用一次。但是,當我這樣做this.update(MyGraphics)
我所有的buttons
和textfields
都會出現問題。JFrame(Swing)更新(圖形)錯誤
有人知道如何解決它嗎?
以下是如何通過定時器更新JPanel
的示例之一。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class MainClass extends JPanel {
static JFrame frame = new JFrame("Oval Sample");
static MainClass panel = new MainClass(Color.CYAN);
static Color colors[] = {Color.RED, Color.BLUE, Color.GREEN, Color.YELLOW};
static Color color;
static int step = 0;
public MainClass(Color color) {
this.color = color;
}
final static Timer tiempo = new Timer(500, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// paintComponent();
System.out.println("Step: " + step++);
if (step % 2 == 0) {
color = Color.DARK_GRAY;
} else {
color = Color.BLUE;
}
panel.repaint();
}
});
@Override
public void paintComponent(Graphics g) {
int width = getWidth();
int height = getHeight();
g.setColor(color);
g.drawOval(0, 0, width, height);
}
public static void main(String args[]) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(2, 2));
panel = new MainClass(colors[2]);
frame.add(panel);
frame.setSize(300, 200);
frame.setVisible(true);
tiempo.start();
}
}
當我做這個this.update(MyGraphics)我所有的按鈕和文本框的glitched。
請勿直接調用update(...)
。這不是定製繪畫完成的方式。
相反,當你的風俗畫,你重寫JPanel的paintComponent(...)
方法:
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
// add your custom painting here
}
我有一個小矩形,一個小遊戲。如果你想要的動畫被移動
那麼你應該使用Swing Timer
安排動畫。然後,當Timer觸發時,調用自定義類的方法來更改矩形的位置,然後調用repaint()
。這將導致面板被重新粉刷。
閱讀Swing Tutorial。上有幾個部分:
讓你的開始基本的例子。
你應該重載'paintComponent(...)'。 – camickr
這是行不通的,因爲只有當我點擊下一個圓形按鈕時,Paint方法纔會更新//我與Jpanel交互,但是我希望它在沒有我做任何事情的情況下更新 –
它沒有解決我的問題,所以我會說不 –