【发布时间】:2014-07-19 17:11:20
【问题描述】:
在我的代码中,我试图通过JFrame 进行绘制,但绘制不正确。我告诉框架在我创建它的开始处绘制,但是一旦创建它它就是正常的灰色。我认为这可能与我正在重新粉刷它有关,如果是这样,我如何确保它被重新粉刷成黄色?有人可以尝试弄清楚为什么我的代码没有绘制JFrame Yellow 吗?谢谢!
public class EvolutionColor {
public static void main(String args[]) {
JFrame frame = new JFrame("Bouncing Ball");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BallPanel bp = new BallPanel();
frame.add(bp);
frame.setSize(600, 600); // set frame size
frame.setVisible(true); // display frame
frame.setBackground(Color.YELLOW);
}
class BallPanel extends JPanel implements ActionListener {
private int delay = 10;
protected Timer timer;
private int x = 0; // x position
private int y = 0; // y position
private int radius = 15; // ball radius
private int dx = 2; // increment amount (x coord)
private int dy = 2; // increment amount (y coord)
public BallPanel() {
timer = new Timer(delay, this);
timer.start(); // start the timer
}
public void actionPerformed(ActionEvent e) {
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g); // call superclass's paintComponent
g.setColor(Color.red);
// check for boundaries
if (x < radius) {
dx = Math.abs(dx);
}
if (x > getWidth() - radius) {
dx = -Math.abs(dx);
}
if (y < radius) {
dy = Math.abs(dy);
}
if (y > getHeight() - radius) {
dy = -Math.abs(dy);
}
// adjust ball position
x += dx;
y += dy;
g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
}
【问题讨论】:
-
旁白:我将创建一个
Ball类来保存球对象的状态,并在Ball类中拥有一个操作和绘制它的方法。如果您想要的不仅仅是一个球,这使得它更易于维护。请参阅示例here。也看看Initial Threads。 Swing 应用程序应该在 EDT 上运行
标签: java swing colors jpanel paintcomponent