Reputation: 4240
I'm trying to open a window with a specific WINDOW_WIDTH
and WINDOW_HEIGHT
.
/**
* Program to calculate a tip based on a restaurant bill
* @author Nick Gilbert
*/
import javax.swing.*;
import java.awt.*;
public class TipCalculator extends JFrame {
private JFrame frame1;
private JLabel label1;
private JPanel panel1;
private JTextField askBill;
private final int WINDOW_WIDTH = 400; // Window width
private final int WINDOW_HEIGHT = 300; // Window height
/**
* Constructor
*/
public TipCalculator(){
setTitle("Tip Calculator!");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
panel1 = new JPanel();
label1 = new JLabel("Enter bill:");
askBill = new JTextField(10);
panel1.add(label1);
panel1.add(askBill);
add(panel1, BorderLayout.NORTH);
pack();
setVisible(true);
}
public static void main(String[] args) {
new TipCalculator();
}
}
Yet when I run this the width and height I specify with the setSize
method has no effect and I have no idea why
Upvotes: 1
Views: 414
Reputation: 347204
You're calling pack
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
//...
pack();
From the JavaDocs...
public void pack()
Causes this Window to be sized to fit the preferred size and layouts of its subcomponents. The resulting width and height of the window are automatically enlarged if either of dimensions is less than the minimum size as specified by the previous call to the setMinimumSize method.
If the window and/or its owner are not displayable yet, both of them are made displayable before calculating the preferred size. The Window is validated after its size is being calculated.
This is actually the preferred method for sizing a window as it takes into account the variations between platforms. It also means that the window's viewable space (the area within the window's borders) matches the preferred size of it's content.
Calling setSize
makes the widow that size, meaning that the content will be the specified size - the windows borders, which will be different for different look and feels and platforms.
Upvotes: 1