Java setBounds() method (JFrame)

Pablo Ajo picture Pablo Ajo · May 11, 2015 · Viewed 7.8k times · Source

Hi Im using the setBounds method to open a window whith a certain size. But the size that I pass in the argument is the size of the window including the bars of the frame. How can I set the dimensions only for the content?

Answer

Kevin Workman picture Kevin Workman · May 11, 2015

Set the size of the content, then call pack() on the JFrame.

Edit: Because Guillaume Polet will not stop griefing me, here is a complete working example. Notice how you don't need to (mis)use inheritance at all, and it gets the job done in much fewer lines:

import java.awt.Dimension;
import javax.swing.JFrame;

public class Main  {

    public static void main(String... args) {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setPreferredSize(new Dimension(500, 500));
        frame.pack();
        frame.setVisible(true);
    }
}