Java JFrame.setSize (x, y) not working?

When I execute this bit of code, a tiny window appears, and inside it is about 116x63 and the whole size includes a ~ 140x100 border. How do I customize the interior for what I need?

public static void graphics() {
    JFrame frame = new JFrame();

    String title = "test window";
    frame.setTitle(title);

    frame.setSize(gridRow, gridCol); //101 x 101
    frame.setResizable(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

      

+1


source to share


1 answer


  • Create a custom component extending from JPanel

    , override its method getPreferredSize

    to return the window size you would like.
  • Either add this to your frame or set it as the frame's content pane.
  • Call pack

    in frame

Updated with example

enter image description here



On my pc Frame size = java.awt.Dimension[width=216,height=238]

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestFrameSize01 {

    public static void main(String[] args) {
        new TestFrameSize01();
    }

    public TestFrameSize01() {
        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());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

                System.out.println("Frame size = " + frame.getSize());
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
        }

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

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            String text = getWidth() + "x" + getHeight();
            FontMetrics fm = g2d.getFontMetrics();
            int x = (getWidth() - fm.stringWidth(text)) / 2;
            int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
            g2d.drawString(text, x, y);
            g2d.dispose();
        }
    }    
}

      

+3


source







All Articles