简体   繁体   中英

Adding JPanel to JFrame with FlowLayout

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);

When you create any custom component and do custom painting you need to override the getPreferredSize() method to return the size of the custom component. Ideally you would also overrid the minimum/maximum sizes as well.

Then the layout manager can do its job.

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 ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM