0
   import javax.swing.*;
   import java.awt.*;
   class MainGui{
         JFrame frame = new JFrame();
         JPanel mainPanel = new JPanel();
         JButton newBut = new JButton("New Game");
         JButton continueBut = new JButton("Continue");
         JButton exitBut = new JButton("Exit");
         JLabel backImage = new JLabel(new ImageIcon("C:\\Users\\BSK\\Desktop\\game5.jpg"));
         public MainGui(){
             frame.setSize(600,800);
             frame.setVisible(true);
             frame.setResizable(false);
             setButtonSize();
             frame.setLayout(new BorderLayout());
             frame.setContentPane(backImage);
             frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
             insertBlankArea(frame);
             frame.getContentPane().add(newBut);
             insertBlankArea(frame);
             frame.getContentPane().add(continueBut);
             insertBlankArea(frame);
             frame.getContentPane().add(exitBut);
             frame.setSize(799,800);

      }
      public void insertBlankArea(JFrame frame){
            frame.getContentPane().add(Box.createRigidArea(new Dimension(280,155)));
      }
      public void setButtonSize(){
            Dimension dim = new Dimension(100,100);//here is the problem,i am not getting the desired dimension and the size of buttons remains the default.
            newBut.setPreferredSize(dim);
            continueBut.setPreferredSize(dim);
            exitBut.setPreferredSize(dim);
      }

      public static void main(String[] args) {
            MainGui mainGui = new MainGui();
      }
  }

So iam not getting the defined size for the buttons but when i set frame.setResizable(false); then when i stretch the screen the button's height increases but its width still remains the same.
So please tell me what is going wrong? this is the output

OldSchool
  • 2,123
  • 4
  • 23
  • 45
  • http://stackoverflow.com/questions/14226622/boxlayout-refuses-to-honor-preferred-size-of-jbutton – schlagi123 Jul 06 '14 at 10:38
  • Not related, Hard coding a system path, might will give trouble at the time of deployment of the application, consider how to [add images to Java Project](http://stackoverflow.com/a/9866659/1057230), for a way to organize the project structure. Moreover, try to write `frame.setVisible(true)` as the last line, preceeded by `frame.pack()` once you have added all components to the `JFrame`. Do not call it before that, not a good practice, and a reason why you have to set size again, instead call `frame.pack()` – nIcE cOw Jul 06 '14 at 10:43

2 Answers2

4

You should take a look at A Visual Guide to Layout Managers and choose the most appropriate one for your situation. You should also avoid explicitly setting sizes (ie: setSize, setMinimumSize, setMaximumSize, and setPreferredSize) because those methods are the responsibility of the layout manager. You may also be interested in reading this question on whether or not the use of the different set size methods should be avoided or not.

Finally, you should not be calling your MainGUI class outside of the Event Dispatch Thread (EDT). Most Swing GUI-related methods are not thread safe and therefore require being executed in the EDT. Below is a corrected version of your main method:

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            MainGui mainGui = new MainGui();
        }
    });
}
Community
  • 1
  • 1
David Yee
  • 3,515
  • 25
  • 45
3

Just reading your short descrption, I have no idea what your problem is. But based solely on the question title

"How to give a preffered size to the JButton?"

Don't. Let the the layout manager handle this for you. If you want a bigger button, you can use JButton.setMargins(Insets) and/or JButton.setFont(Font) where you specify a bigger font.

If you want you button stretched or not to stretch, You need to select an appropriate layout manager, that will or won't respect the buttons preferred size. For instance, BorderLayout and GridLayout won't respect preferred sizes and will stretch the button the fit, and FlowLayout, BoxLayout, and GridBagLayout will respect the preferred size. As you can see here

enter image description here


See example with GridBagLayout

enter image description here

import javax.swing.*;
import java.awt.*;

class MainGui {
    JFrame frame = new JFrame();
    JPanel mainPanel = new JPanel();
    JButton newBut = new JButton("New Game");
    JButton continueBut = new JButton("Continue");
    JButton exitBut = new JButton("Exit");
    JLabel backImage = new JLabel(new ImageIcon(
            getClass().getResource("images.jpg")));

    public MainGui() {
        backImage.setLayout(new BorderLayout());
        frame.setContentPane(backImage);
        JPanel mainPanel = new JPanel(new GridBagLayout());
        mainPanel.setOpaque(false);
        GridBagConstraints gbc = new GridBagConstraints();

        gbc.gridy = 0;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        mainPanel.add(newBut, gbc);

        gbc.gridy = 1;
        mainPanel.add(continueBut, gbc);

        gbc.gridy = 2;
        mainPanel.add(exitBut, gbc);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(mainPanel);
        frame.setSize(250, 275);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                MainGui mainGui = new MainGui();
            }
        });
    }
}

And here's with nesting panels which will give the same result

import java.awt.GridBagLayout;
import java.awt.GridLayout;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

class MainGui {
    JFrame frame = new JFrame();
    JPanel mainPanel = new JPanel();
    JButton newBut = new JButton("New Game");
    JButton continueBut = new JButton("Continue");
    JButton exitBut = new JButton("Exit");
    JLabel backImage = new JLabel(new ImageIcon(
            getClass().getResource("images.jpg")));

    public MainGui() {
        backImage.setLayout(new GridLayout(3,1));
        frame.setContentPane(backImage);
        JPanel p1= new JPanel(new GridBagLayout());
        p1.setOpaque(false);
        p1.add(newBut);
        JPanel p2 = new JPanel(new GridBagLayout());
        p2.setOpaque(false);
        p2.add(continueBut);
        JPanel p3 = new JPanel(new GridBagLayout());
        p3.setOpaque(false);
        p3.add(exitBut);

        frame.add(p1);
        frame.add(p2);
        frame.add(p3);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(250, 275);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                MainGui mainGui = new MainGui();
            }
        });
    }
}
Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • please tell me one more thing,in your first case why we need `backImage.setLayout(new BorderLayout());`.I have noticed that without it image is displaying but not buttons on it,what is the reason for this,please reply.Thanx. – OldSchool Jul 06 '14 at 13:43
  • Because JLabel has default null layout. In order to add to a null layout, you need to specify the bounds for the components you add to it. Like `panel.setBounds(0, 0, 300, 300); label.add(panel);`. With a layout manager, setting the bounds is unnecessary as the layout manager takes care of sizing and positioning for you – Paul Samsotha Jul 06 '14 at 13:50
  • it means without setting bounds you cannot add components to a null layout container – OldSchool Jul 06 '14 at 13:52
  • Yes that's correct. Test it out. You should always use a layout manager though. The to main containers come already with default layout manager. JFrame=BorderLayout, JPanel=FlowLayout – Paul Samsotha Jul 06 '14 at 13:54