JFrame isResizable(false) sizing issue

前端 未结 1 818
渐次进展
渐次进展 2020-12-20 20:54

I intended to make a JFrame with a ContentPanel of 600x600 and I wanted the JFrame to be not re-sizable. Inside this box, I Drew a 600x600 red-outlined rectangle to make sur

相关标签:
1条回答
  • 2020-12-20 21:44

    You are right, setting a frame to un-resiable does seem to add 10 pixels to it's height and width, as to why, I can't say, this seems to be side effect of updating the native peer, however...

    You can reset it by call JFrame#pack after the calling JFrame#setResizable

    public class TestResizableFrame {
    
        public static void main(String[] args) {
            new TestResizableFrame();
        }
    
        public TestResizableFrame() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    JFrame frame = new JFrame();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(new FixedPane());
                    frame.setResizable(false);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class FixedPane extends JPanel {
    
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(200, 200);
            }
    
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Dimension size = getSize();
                String text = size.width + "x" + size.height;
                FontMetrics fm = g.getFontMetrics();
                int x = (getWidth()- fm.stringWidth(text)) / 2;
                int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
                g.drawString(text, x, y);
                g.setColor(Color.RED);
                g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
            }
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题