2 回答

TA貢獻1772條經驗 獲得超8個贊
首先,不要改變JFrame
繪制的方式(換句話說,不要覆蓋paintComponent()
a JFrame
)。創建一個擴展類JPanel
并繪制它JPanel
。其次,不要覆蓋paint()
方法。覆蓋paintComponent()
。第三,始終運行 Swing 應用程序,SwingUtilities.invokeLater()
因為它們應該在自己的名為 EDT(事件調度線程)的線程中運行。最后,javax.swing.Timer
就是你要找的。
看看這個例子。它每 1500 毫秒在隨機 X、Y 上繪制一個橢圓形。
預習:
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貢獻1868條經驗 獲得超4個贊
首先,不要繼承 JFrame;而是將 JPanel 子類化,并將該面板放在 JFrame 中。其次,不要覆蓋paint() - 而是覆蓋paintComponent()。第三,創建一個 Swing Timer,并在其 actionPerformed() 方法中進行您想要的更改,然后調用 yourPanel.repaint()
添加回答
舉報