Set size of JPanel, when there are no components i

2019-09-01 01:49发布

问题:

I have a custom JPanel. The only thing that is in it, is a drawing of a rectangle, using the drawRect method of the Graphics object. The JPanel is always in a very specific square size, refuses to get any bigger or smaller. Tried overriding the getPreferredSize() method, didn't work.

Tried setting different layout managers for this custom JPanel, and also tried every layout manager for the JPanel that hosts this JPanel. Still, the size of the custom JPanel stays the same.

As I said, the custom JPanel has no components in it, only a drawing of a rectangle.

Any ideas?

回答1:

Without knowing more about what you're trying to achieve:

  • As far as your containing panel, you need to know which layout managers respect preferred sizes and which ones don't

                              Grid     Flow     Border    Box   GridBag
    Respect PreferredSize      NO       YES      NO       YES     YES
    
  • That being said, if you wrap the painted JPanel in a JPanel with one of the "NOs", the painted JPanel shoud stretch with the resizing of the frame.

  • Also if you want the drawn rectangle to stretch along with its JPanel, then you need to remember to draw the rectangle with getWidth() and getHeight() of the JPanel and not use hard coded values.

Here is an example using BorderLayout as the containing panel's layout, and making use of getWidth() and getHeight() when performing the painting.

import java.awt.*;
import javax.swing.*;

public class StretchRect {

    public StretchRect() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(new RectanglePanel());

        JFrame frame = new JFrame();
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public class RectanglePanel extends JPanel {

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.fillRect( (int)(getWidth() * 0.1), (int)(getHeight() * 0.1), 
                        (int)(getWidth() * 0.8), (int)(getHeight() * 0.8) );
        }

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

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new StretchRect();
            }
        });
    }
}