Frame and Canvas grow larger than specified

后端 未结 1 430
轻奢々
轻奢々 2020-12-21 12:57

I have no idea why I am getting an extra-large window, this is making me run hoops to fit my sprites in the game-window. The constructor should make it so all the subcompone

相关标签:
1条回答
  • 2020-12-21 13:42

    Swap the pack and setResizable calls, so that pack is the second call.

    In the following example, it will write 200x200 on the panel, if you swap the calls it will write 210x210

    This is a known "issue"

    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    
    public class TestResizeFrame {
    
        public static void main(String[] args) {
            new TestResizeFrame();
        }
    
        public TestResizeFrame() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(new TestPane());
                    // Will appear as 200x200, swap them and it will appear as 210x210
                    frame.setResizable(false);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class TestPane extends JPanel {
    
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(200, 200);
            }
    
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g); 
                FontMetrics fm = g.getFontMetrics();
                g.drawString(getWidth() + "x" + getHeight(), 0, fm.getAscent());
            }
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题