3

Hi I am trying to add 2 JPanel's to a JFrame that take the full width and height of the JFrame.I managed to add them with GridBagLayout() but I can't seem to set the size of the JPanels using the setsize().I have also tryied to used ipady and ipadx while that seemed to work at first after I aded some buttons the whole layout became a mess.Here is my code:

           JFrame tradeframe = new JFrame("Trade");
           JPanel P1panel = new JPanel();         
           P1panel.setBackground(Color.red);
           JPanel P2panel = new JPanel();
           P2panel.setBackground(Color.BLACK);


           tradeframe.setVisible(true);
           tradeframe.setSize(600, 400);
           tradeframe.setResizable(false);
           tradeframe.setLocationRelativeTo(null);
           tradeframe.setLayout(new GridBagLayout());

           P1panel.add(new JButton ("P1 Agree"));

           P2panel.add(new JButton ("P2 Agree"));


           GridBagConstraints a = new GridBagConstraints();
           a.gridx = 0;
           a.gridy = 0;
           a.weightx = 360;
           a.weighty = 300;
           //a.fill = GridBagConstraints.HORIZONTAL;
           tradeframe.add(P1panel , a);

           GridBagConstraints b = new GridBagConstraints();
           b.gridx = 1;
           b.gridy = 0;
           b.weightx = 360;
           b.weighty = 300;
          // b.fill = GridBagConstraints.HORIZONTAL;
           tradeframe.add(P2panel , b);

How can I make that each JPanel is 300px width and 400px in height?

user1146440
  • 363
  • 1
  • 9
  • 19
  • 1
    When you use LayoutManager you don't use setXXXSize(), it's the job of the LayoutManager to worry about that. Moreover read the GridBagLayout Tutorials again, and see what values they told you for weightx and weighty :-) – nIcE cOw Mar 12 '12 at 13:33

5 Answers5

4

for GridBaglayout you have to set

  • fill

  • anchor

  • weightx and weighty

  • gridx / gridy (depend of orientations)

then is possible for example

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

public class BorderPanels extends JFrame {

    private static final long serialVersionUID = 1L;

    public BorderPanels() {
        setLayout(new GridBagLayout());// set LayoutManager
        GridBagConstraints gbc = new GridBagConstraints();
        JPanel panel1 = new JPanel();
        Border eBorder = BorderFactory.createEtchedBorder();

        panel1.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
        gbc.gridx = gbc.gridy = 0;
        gbc.gridwidth = gbc.gridheight = 1;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.anchor = GridBagConstraints.NORTHWEST;
        gbc.weightx = gbc.weighty = 20;
        add(panel1, gbc); // add compoenet to the COntentPane

        JPanel panel2 = new JPanel();
        panel2.setBorder(BorderFactory.createTitledBorder(eBorder, "60pct"));
        gbc.gridy = 1;
        gbc.weightx = gbc.weighty = 60;
        //gbc.insets = new Insets(2, 2, 2, 2);
        add(panel2, gbc); // add component to the COntentPane

        JPanel panel3 = new JPanel();
        panel3.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
        gbc.gridy = 2;
        gbc.weightx = gbc.weighty = 20;
        gbc.insets = new Insets(2, 2, 2, 2);
        add(panel3, gbc);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // important
        pack();
        setVisible(true); // important
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() { // important

            public void run() {
                BorderPanels borderPanels = new BorderPanels();
            }
        });
    }
}

on most cases will be better use another LayoutManager

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • +1, for actually interpreting what is to be done, instead of using `setXXXSize(...)`. But please do read what GridBagLayout has to say for weightx and weighty, "Generally weights are specified with 0.0 and 1.0 as the extremes: the numbers in between are used as necessary." – nIcE cOw Mar 12 '12 at 13:36
  • @Gagandeep Bali just simple hack, otherwise resize isn't continously and proportional, my curiosity do you have another way how to do it (in GridBagLayout) – mKorbel Mar 12 '12 at 13:39
  • I had just added a small Program, do check that out :-) – nIcE cOw Mar 12 '12 at 13:58
  • @Gagandeep Bali +1 true is that for GridBagLayout I always creating matrix before, by using small JLabels on the 1st row (required forcing by setXxxSize), then you can place JComponents on both directions without any faults, this is idea similair with how MigLayout to works – mKorbel Mar 12 '12 at 14:04
3
    JFrame tradeframe = new JFrame("Trade");
    JPanel P1panel = new JPanel();         
    P1panel.setBackground(Color.red);
    JPanel P2panel = new JPanel();
    P2panel.setBackground(Color.BLACK);
    tradeframe.setSize(600, 400);
    tradeframe.setResizable(false);
    tradeframe.setLocationRelativeTo(null);

    Box content = new Box(BoxLayout.X_AXIS);

    P1panel.add(new JButton ("P1 Agree"));

    P2panel.add(new JButton ("P2 Agree"));

    content.add(P1panel);
    content.add(P2panel);

    tradeframe.setContentPane(content);
    tradeframe.setVisible(true);
Jakub Zaverka
  • 8,816
  • 3
  • 32
  • 48
  • You seems to me a big fan of BoxLayout :-) , but the idea you had given will no doubt work, +1 for that :-) – nIcE cOw Mar 12 '12 at 13:38
  • Everyone seems to be using GridBag, which is awfully painful to use. I just enlighten them :-) I also like BorderLayout. You can create all possible layouts using just Box and Border layouts and nesting panels. – Jakub Zaverka Mar 12 '12 at 13:41
2

Invoke setPreferredSize(new Dimension(int width, int height)); method on your panel objects.

Juvanis
  • 25,802
  • 5
  • 69
  • 87
  • 1
    -1, for specifying `setXXXSize(...)`, when you are using a Layout, what's the need of this wonderful method. Layout is used to overcome these things :-) – nIcE cOw Mar 12 '12 at 13:34
  • read here first http://stackoverflow.com/q/1783793/544983 it says setsize is used when there is no layout manager. remove downvote please. my answer is correct. – Juvanis Mar 12 '12 at 13:38
  • @deporter +1 I agree. There seems to be some difference in opinion on using preferredSize vs weights. It is never that clear cut and depends on layout manager. e.g. for a text label why wouldn't you let the component decide the size - it knows its own font etc., same for inherently pixel based widgets, like video playback, image viewers. etc. – Adam Mar 12 '12 at 13:45
  • @deporter : He is using GridBagLayout, so how come that post is helpfull in anyway. Hardly in dreams such situation comes, when you cann't use any Layout. What you suggested might will look good on his computer, but depending on different `LnFs` that might won't look nice. That's where Layouts come in picture, to make the content response in the same way on any `Platform` and `LnF`. – nIcE cOw Mar 12 '12 at 13:46
2

Here is the way to do that :

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

public class GridBagLayoutTest
{
    public GridBagLayoutTest()
    {
        JFrame frame = new JFrame("GridBag Layout Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);

        Container container = frame.getContentPane();
        container.setLayout(new GridBagLayout());

        JPanel leftPanel = new JPanel();
        leftPanel.setBackground(Color.WHITE);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 0.5;
        gbc.weighty = 1.0;
        gbc.anchor = GridBagConstraints.FIRST_LINE_START;
        gbc.fill = GridBagConstraints.BOTH;

        container.add(leftPanel, gbc);

        JPanel rightPanel = new JPanel();
        rightPanel.setBackground(Color.BLUE);
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.weightx = 0.5;
        gbc.weighty = 1.0;
        gbc.anchor = GridBagConstraints.FIRST_LINE_END;
        gbc.fill = GridBagConstraints.BOTH;

        container.add(rightPanel, gbc);

        frame.setSize(600, 400);
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        Runnable runnable = new Runnable()
        {
            public void run()
            {
                new GridBagLayoutTest();
            }
        };
        SwingUtilities.invokeLater(runnable);
    }
}

OUTPUT :

GRIDBAG LAYOUT TEST

nIcE cOw
  • 24,468
  • 7
  • 50
  • 143
0

You are using setSize() instead of setPreferredSize(). The difference is somewhat misleading and I would consider it a gotcha in java. Some more information about what the difference between the two can be found here.

The article I link has some other pitfalls/gotchas and a useful read if you are new to Java.

Halfwarr
  • 7,853
  • 6
  • 33
  • 51