問題: 將多個球加入 Java應用程式會產生初始球被第二個覆蓋,導致只有一個可見
要解決此問題並在螢幕上繪製多個彈跳球,請考慮以下方法:
< ;h4>4。使用球的容器類:
public class Balls extends JPanel { private List<Ball> ballsUp; // ... (Constructor and other methods) @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); for (Ball ball : ballsUp) { ball.paint(g2d); } g2d.dispose(); } public List<Ball> getBalls() { return ballsUp; } } public class Ball { private Color color; private Point location; private Dimension size; private Point speed; // ... (Constructor and other methods) protected void paint(Graphics2D g2d) { Point p = getLocation(); if (p != null) { g2d.setColor(getColor()); Dimension size = getSize(); g2d.fillOval(p.x, p.y, size.width, size.height); } } } public class BounceEngine implements Runnable { private Balls parent; // ... (Constructor and other methods) public void run() { // Randomize ball properties and starting positions for (Ball ball : getParent().getBalls()) { // ... (Randomization logic) } while (getParent().isVisible()) { // Repaint the balls SwingUtilities.invokeLater(new Runnable() { @Override public void run() { getParent().repaint(); } }); // Move each ball for (Ball ball : getParent().getBalls()) { move(ball); } // Delay between updates try { Thread.sleep(100); } catch (InterruptedException ex) { } } } // ... (Remaining code) }
這種使用容器類別和單獨執行緒進行球運動的方法可以更好地控制球的行為,並允許更複雜的球動畫。
以上是如何在 Java 應用程式中顯示多個彈跳球而不互相覆蓋?的詳細內容。更多資訊請關注PHP中文網其他相關文章!