我試圖回答與moving a ball across the screen while changing its color over time有關的問題,但是我遇到了一個奇怪的錯誤(最可能是在我的代碼中),並且在詢問此問題時我來到related question但是這個問題是使用客戶端 - 服務器架構,而我的是一個簡單的Swing應用程序。Swing自定義繪畫動畫在到達框架的半寬處後停止
發生了什麼事情是,當圓/球,但是你想命名它,達到JPanel
或JFrame
的半寬度,它變得不可見或停止。
起初我以爲這可能是我的JPanel
被定位不好,但我添加了一個Border
到它,所以我可以看到它的尺寸,但它顯示了JFrame
的整個空間周圍的整個邊框。
接下來,我認爲這可能是一些算術問題,所以我決定讓球大於和小於我最初繪製它,給我相同的結果,當我放大或縮小窗口尺寸。
爲了得到下面的輸出,我需要通過9
,而不是10
我最初加入改變增量,因爲如果我將其更改爲10
它變得不可見:
下面的代碼產生上面的輸出:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class ChangingColorBall {
private JFrame frame;
private Timer timer;
private BallPane ballPane;
public static void main(String[] args) {
SwingUtilities.invokeLater(new ChangingColorBall()::createAndShowGui);
}
private void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
ballPane = new BallPane();
timer = new Timer(100, e -> {
ballPane.increaseX();
});
ballPane.setBorder(BorderFactory.createLineBorder(Color.RED));
frame.add(ballPane);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
timer.start();
}
@SuppressWarnings("serial")
class BallPane extends JPanel {
private int x;
private static final int Y = 50;
private static final int SIZE = 20;
private Color color;
private Random r;
public void increaseX() {
x += 9;
r = new Random();
color = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
revalidate();
repaint();
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(color);
// g2d.fill(new Ellipse2D.Double(x, Y, SIZE, SIZE));
g2d.fillOval(x, Y, SIZE, SIZE);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 100);
}
}
}
我還以爲這可能是一些涉及到Shapes
API,並決定茶將它改爲fillOval
以及相同的結果,我無法發佈GIF,但是如果需要,稍後將添加它。
我在MacOS塞拉利昂10.12.6(16G29)在MacBook Pro上工作(13 '' 的Retina顯示屏,2015年初)編制和Java 1.8下運行它
我稍後會測試該代碼以及在我自己的PC上,而不是在我工作的Mac上,但是,這可能是與Swing API有關的錯誤還是我自己代碼中的錯誤?如果是這樣,我做錯了什麼?由於它對我而言並不明顯
創建一個「形狀」對象,它具有位置(和顏色)的概念,並可以自己繪製,更新並使面板畫上它 – MadProgrammer