Search code examples
javaswingpaintcomponent

JComponent subclass not appearing


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....


Solution

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

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