简体   繁体   中英

Java: How can I prevent Canvas from being resized when it is added to a JFrame?

When running this in my main:

    Canvas can = new Canvas();

    can.setSize(400, 400);

    System.out.print(can.getWidth() + ", " + can.getHeight() + " ");

    JFrame frame = new JFrame();

    frame.add(can);
    frame.pack();
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    System.out.println(can.getWidth() + ", " + can.getHeight());

The console reads: 400, 400 410, 410

It seems like when I add my Canvas to my JFrame and pack the JFrame it adds an extra 10 pixels to the width and height of my Canvas. Is there any way I can prevent this from happening and get exactly a 400 by 400 Canvas?

Don't use a Canvas, that is an AWT component.

When using Swing you should use a JPanel and then override the getPreferredSize() of the panel to return the desired size.

Also, setSize() does nothing. The layout manager will determined the size of each component based on the rules of the layout manager.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM