How to change the dimension of a component in a JFrame

后端 未结 3 1852
一个人的身影
一个人的身影 2020-12-20 01:28

Suppose I have a JPanel in a JFrame. When I invoke a method that changes the preferred size of that JPanel, it does not change.

The code looks something like this:

3条回答
  •  自闭症患者
    2020-12-20 01:54

    You need to invalidate the container hierarchy to make it re-layout the components.

    Simply call invalidate followed by revalidate on the component you have changed.

    Here's a small example...

    public class TestComponentHierarcy {
    
        public static void main(String[] args) {
            new TestComponentHierarcy();
        }
    
        public TestComponentHierarcy() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException ex) {
                    } catch (InstantiationException ex) {
                    } catch (IllegalAccessException ex) {
                    } catch (UnsupportedLookAndFeelException ex) {
                    }
    
                    JFrame frame = new JFrame("Test");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new GridBagLayout());
                    frame.add(new Test());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class Test extends JPanel {
    
            private Dimension size = new Dimension(10, 10);
    
            public Test() {
    
                setLayout(new GridBagLayout());
                addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        size.width += 10;
                        size.height += 10;
                        invalidate();
                        revalidate();
                    }
                });
    
            }
    
            @Override
            public Dimension getPreferredSize() {
                return size;
            }
    
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setColor(Color.RED);
                g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
            }
    
        }
    
    }
    

提交回复
热议问题