2 回答
TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超8個(gè)贊
首先,不要改變JFrame繪制的方式(換句話說(shuō),不要覆蓋paintComponent()a JFrame)。創(chuàng)建一個(gè)擴(kuò)展類(lèi)JPanel并繪制它JPanel。其次,不要覆蓋paint()方法。覆蓋paintComponent()。第三,始終運(yùn)行 Swing 應(yīng)用程序,SwingUtilities.invokeLater()因?yàn)樗鼈儜?yīng)該在自己的名為 EDT(事件調(diào)度線程)的線程中運(yùn)行。最后,javax.swing.Timer就是你要找的。
看看這個(gè)例子。它每 1500 毫秒在隨機(jī) X、Y 上繪制一個(gè)橢圓形。
預(yù)習(xí):
https://i.stack.imgur.com/KGLff.gif
源代碼:
import java.awt.BorderLayout;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class DrawShapes extends JFrame {
private ShapePanel shape;
public DrawShapes() {
super("Random shapes");
getContentPane().setLayout(new BorderLayout());
getContentPane().add(shape = new ShapePanel(), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setLocationRelativeTo(null);
initTimer();
}
private void initTimer() {
Timer t = new Timer(1500, e -> {
shape.randomizeXY();
shape.repaint();
});
t.start();
}
public static class ShapePanel extends JPanel {
private int x, y;
public ShapePanel() {
randomizeXY();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillOval(x, y, 10, 10);
}
public void randomizeXY() {
x = (int) (Math.random() * 500);
y = (int) (Math.random() * 500);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new DrawShapes().setVisible(true));
}
}
TA貢獻(xiàn)1868條經(jīng)驗(yàn) 獲得超4個(gè)贊
首先,不要繼承 JFrame;而是將 JPanel 子類(lèi)化,并將該面板放在 JFrame 中。其次,不要覆蓋paint() - 而是覆蓋paintComponent()。第三,創(chuàng)建一個(gè) Swing Timer,并在其 actionPerformed() 方法中進(jìn)行您想要的更改,然后調(diào)用 yourPanel.repaint()
添加回答
舉報(bào)
