I made a 840 by 400 frame and added a text field. By default, the java app shrinked only to the size of the text field. I want it fixed to the respective size.
I tried setResizable(false)
, setExtendedState()
, setBounds()
with no avail.
I made a 840 by 400 frame and added a text field. By default, the java app shrinked only to the size of the text field. I want it fixed to the respective size.
I tried setResizable(false)
, setExtendedState()
, setBounds()
with no avail.
Best to use a JPanel as your contentPane or add it to the contentPane, and to override its getPreferredSize() method and then use
pack()` on the JFrame. For example:
import java.awt.Dimension;
import javax.swing.*;
@SuppressWarnings("serial")
public class MyPanel extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = 300;
public MyPanel() {
//...
}
@Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
MyPanel myPanel = new MyPanel();
JFrame frame = new JFrame("My GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(myPanel);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
One advantage of this is that other classes cannot change MyPanel's size via setSize(...)
or setPreferredSize(...)
.
Try
setPreferredSize(new Dimension(840,400));
If you named your frame you can do
name.setPreferredSize(new Dimension(840,400));