I am trying to display a filled oval on the screen using a subclass of JPanel when I try to add an object of this subclass to a JFrame with FlowLayout the oval is not displayed correctly I don't know what the problem is. Could you help me please?
here's my code
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillOval(0, 0, 50, 50);
}
in main
JFrame frame = new JFrame("Ball");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setLayout(new FlowLayout());
BallPanel ball = new BallPane();
frame.add(ball);
See the Javadoc of the FlowLayout
:
A flow layout lets each component assume its natural (preferred) size
Since you do some custom painting, the BallPanel
cannot compute its preferred size (which is based on the components you add the panel). So override in the BallPanel
class the getPreferredSize
method to return correct dimensions (correct means matching your custom painting). Consider doing the same for the getMinimumSize
and getMaximumSize
.
What I always use when I have to debug Swing layout problems is to add borders to my components in specific colors. That way you clearly see the size your components take in their parent container, which might be a good starting point for debugging. In your case, it would show a very tiny panel ;-)