Set size of JPanel, when there are no components in it

陌路散爱 提交于 2019-12-24 21:22:24

问题


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


来源:https://stackoverflow.com/questions/22166549/set-size-of-jpanel-when-there-are-no-components-in-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!