1

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.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
mireazma
  • 526
  • 1
  • 8
  • 20

2 Answers2

4

Best to use a JPanel as your contentPane or add it to the contentPane, and to override its getPreferredSize() method and then usepack()` 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(...).

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
2

Try

 setPreferredSize(new Dimension(840,400));

If you named your frame you can do

 name.setPreferredSize(new Dimension(840,400));
Chris
  • 246
  • 1
  • 5
  • 15