Okay. I was writing my Ball class and the ball is not displayed. I tried adding other components to my container and they are displayed, so I think it is safe to assume that the problem is my ball. The class code:

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JComponent;


public class Ball extends JComponent {

public Ball() {
    ballX  = (Window.WINDOW_WIDTH - BALL_DIAMETER) / 2;
    ballY  = (Window.WINDOW_HEIGHT - BALL_DIAMETER) / 2;
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawRect(5, 5, 50, 50);
    g.setColor(Color.GREEN);
    g.fillOval(ballX, ballY, BALL_DIAMETER, BALL_DIAMETER);
    g.dispose();

}
public void setX(int x) {
    ballX = x;
}
public void setY(int y) {
    ballY = y;
}

private int ballX;
private int ballY;
public static final int BALL_DIAMETER = 30;
}

The first rect was used for testing. It doesn't appear neither....

有帮助吗?

解决方案

Make sure your component has a preferred size larger than (0, 0):

@Override
public Dimension getPreferredSize() {
    return new Dimension(500, 500);
}

其他提示

Not seeing the code that adds the ball to a container, it's a little hard to answer your question.

However, there are a few problems with your code:

  1. You're setting the location of the ball in the constructor, using some constants - Assuming you want to paint the ball in the middle of the component, you should calculate the location in the paintComponent method by calling getSize and doing the math on the spot
  2. You dispose of the Graphics object at the end of the paintComponent method even though you didn't create it, don't do that, remove that method call (that's probably the culprit)
  3. You're not keeping the state of the Graphics object. Either create a copy (using the create method of the Graphics object) and disposing of it at the end, or by restoring the state you changed at the end of the method (the Color that was set before you changed it to Color.GREEN)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top