10

I get a JFrame and i want to display a JLabel with a border in it with a padding of maybe 50px. When i set the size of the JFrame to 750, 750, and the size of the JLabel to 650, 650 and the location to 50, 50, it display it strange... Here's my code:

public class GUI {

    /**
     * Declarate all 
     */
    public int height = 750;
    public int width = 750;

    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (screen.width / 2) - (width / 2); // Center horizontally.
    int y = (screen.height / 2) - (height / 2); // Center vertically.

    /**
     * Create the GUI
     */
    JFrame frame = new JFrame();
    Border border = LineBorder.createBlackLineBorder();
    JLabel label = new JLabel();    

    public GUI(){
        label.setBorder(border);
        label.setSize(700, 700);
        label.setLocation(0, 0);

        frame.getContentPane().setLayout(null);
        frame.add(label);
    }

    public void createGUI() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(x,y,width,height);
        frame.setVisible(true);
    }

}

So I think the title-bar at the top is also include in the size. In Graphics you can use getInsets(). Now is there anything like that for Swing / JFrame?

Sri Harsha Chilakapati
  • 11,744
  • 6
  • 50
  • 91
Michael Schmidt
  • 9,090
  • 13
  • 56
  • 80
  • please your question is about, for why reason(s) (not joking now) is important to set a final size on the screen – mKorbel Nov 20 '12 at 14:01
  • get the dimensions of the `JFrame` contentpane - http://stackoverflow.com/questions/5097301/jframe-get-size-without-borders?rq=1 – mre Nov 20 '12 at 14:04
  • yes TitleBar is also included while calculating JFrame size !! but I didn't get your problem !! – Pratik Nov 20 '12 at 14:06
  • @dTDesign : You might have to override `JFrame` Class's `getInset()` method to return something valid for your case, like e.g. as shown here on [this link](http://stackoverflow.com/a/10125472/1057230). – nIcE cOw Nov 20 '12 at 14:14
  • @mKorbel: Hm? Sorry, don't understand your question... – Michael Schmidt Nov 20 '12 at 14:24
  • @mre: I don't want to get it, i want to set it. – Michael Schmidt Nov 20 '12 at 14:24
  • @Pratik: I want a Label just with a padding of 50 in the JFrame. With my method, it looks strange... – Michael Schmidt Nov 20 '12 at 14:24
  • @GagandeepBali: I think JFrame haven't this method... – Michael Schmidt Nov 20 '12 at 14:25
  • Oh! So you want whole label must fit into the JFrame. is it? If that so then you need to set labels height width too. – Pratik Nov 20 '12 at 14:34
  • Yes. I want a label in JFrame. And i set the size: label.setSize(700, 700);. My Problem is, the padding between frame and label is different at the bottom and the right border. – Michael Schmidt Nov 20 '12 at 14:38
  • @dTDesign : `JFrame` gets [**getInset()**](http://docs.oracle.com/javase/7/docs/api/java/awt/Container.html#getInsets()), method from the **Container** Class, so as shown in that example, you have to override this method, to do something related to your case. – nIcE cOw Nov 20 '12 at 14:40
  • ya when you use setLocation on Label it moves the label co-ordinates to point (50,50) from (0,0). and size of label remains same. so you need to set size of label again to display it into frame. – Pratik Nov 20 '12 at 14:40
  • @Pratik: In 30 minutes, the school is over. But tomorrow i will create you the the displayed GUI, if i haven't found a resolution for my problem. PS: I want to create a GUI for a snake game... – Michael Schmidt Nov 20 '12 at 14:48
  • @GagandeepBali: Sorry, i'm a amateur with swing. This is now the Container class. So i must extends the JFrame with Container? – Michael Schmidt Nov 20 '12 at 14:51
  • No no, just watch [this link](http://stackoverflow.com/a/10125472/1057230) I gave you before, extend `JFrame` and override `getInsets()`, since **Window extends Container - Frame extends Window - JFrame extends Frame**, so you can override that in your given class by just extending `JFrame`. – nIcE cOw Nov 20 '12 at 15:02

2 Answers2

16

First get the pixels trimmed out by the frame.

int reqWidth = reqHeight = 750;

// first set the size
frame.setSize(reqWidth, reqHeight);

// This is not the actual-sized frame. get the actual size
Dimension actualSize = frame.getContentPane().getSize();

int extraW = reqWidth - actualSize.width;
int extraH = reqHeight - actualSize.height;

// Now set the size.
frame.setSize(reqWidth + extraW, reqHeight + extraH);

An alternate simpler way. The previous works but this is recommended.

frame.getContentPane().setPreferredSize(750, 750);
frame.pack();

Hope this helps.

EDIT:

Add this in your constructor before adding components to the frame. and to set it in the middle, use

frame.setLocationRelativeTo(null);

This will center the window on the screen.

Sri Harsha Chilakapati
  • 11,744
  • 6
  • 50
  • 91
  • Thanks for your answer. But sorry for this stupid question: Where must i insert this? I want to have the window in the middle of the screen, so i need the setBounds() method... Sorry, i don't work a lot with swing... – Michael Schmidt Nov 20 '12 at 14:27
  • @dTDesign : To put the window in the middle of the screen you simply have to use `frameObject.setLocationRelativeTo(null);`, that's it, before calling `setVisible(true)` on the `JFrame`. – nIcE cOw Nov 20 '12 at 14:41
  • Eclipse gives me a error to "setPrefferedSize"... It will cast it with 'Object'... – Michael Schmidt Nov 20 '12 at 14:46
  • May have to change that to `frame.getContentPane().setPreferredSize(new Dimension(750, 750));` and add this import: `import java.awt.Dimension;` – hello_friend Dec 01 '20 at 19:14
3

Using setPreferredSize() is problematic, as it always overrules the component's calculation with an arbitrary choice. Instead, pack() the enclosing Window to accommodate the preferred sized of the components, as shown below.

image

import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;

/**
 * @see https://stackoverflow.com/a/13481075/230513
 */
public class NewGUI extends JPanel {

    private static final int S1 = 10;
    private static final int S2 = 50;
    private JLabel label = new JLabel("Hello, world!");

    public NewGUI() {
        label.setHorizontalAlignment(JLabel.CENTER);
        Border inner = BorderFactory.createEmptyBorder(S1, S1, S1, S1);
        Border outer = BorderFactory.createLineBorder(Color.black);
        label.setBorder(new CompoundBorder(outer, inner));
        this.setBorder(BorderFactory.createEmptyBorder(S2, S2, S2, S2));
        this.add(label);
    }

    private void display() {
        JFrame f = new JFrame("NewGUI");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new NewGUI().display();
            }
        });
    }
}
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045