Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Layout problem (GridBagLayout)

843805Dec 2 2006 — edited Dec 2 2006
hi,

i'm quite new to swing, so please forgive me most of my stupid questions.

How can i achieve following behavior:

both buttons (b1 and b2) should "span over" the whole upperPanel? It is not nessecary to realize this with GridBagLayout. Any appropiate solution is welcome.

tnx in advance

mamurdian

here is my attempt:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;

public class GridLayoutExample extends JFrame
{
  
  public GridLayoutExample ()
  {
    super ("just an example");
    
    setLayout (new GridBagLayout ());
    
    GridBagConstraints frameConstraints = new GridBagConstraints ();
    
    JPanel upperPanel = new JPanel ();
    
    upperPanel.setLayout (new GridBagLayout ());
    
    GridBagConstraints upperPanelConstraints = new GridBagConstraints ();
    upperPanelConstraints = new GridBagConstraints ();
    
    JButton b1 = new JButton ("b1");
    JButton b2 = new JButton ("b2");
    
    upperPanelConstraints.gridx = 0;
    upperPanelConstraints.gridy = 0;
    upperPanelConstraints.fill = GridBagConstraints.HORIZONTAL;
    upperPanel.add (b1, upperPanelConstraints);
    
    upperPanelConstraints.gridx = 0;
    upperPanelConstraints.gridy = 1;
    upperPanelConstraints.fill = GridBagConstraints.HORIZONTAL;
    upperPanel.add (b2, upperPanelConstraints);
    
    
    frameConstraints.gridx = 0;
    frameConstraints.gridy = 0;
    frameConstraints.fill = GridBagConstraints.HORIZONTAL;
    upperPanel.setBorder (new TitledBorder ("upper panel"));
    add (upperPanel, frameConstraints);
    
    JPanel lowerPanel = new JPanel ();
    JLabel lowerLabel = new JLabel ("lower label");
    lowerLabel.setPreferredSize (new Dimension (320, 240));
    lowerPanel.add (lowerLabel);
    
    frameConstraints.gridx = 0;
    frameConstraints.gridy = 1;
    frameConstraints.fill = GridBagConstraints.HORIZONTAL;
    lowerPanel.setBorder (new TitledBorder ("lower panel"));
    getContentPane ().add (lowerPanel, frameConstraints);
  }
  
  public static void main (String [] args)
  {
    GridLayoutExample gle = new GridLayoutExample ();
    gle.setPreferredSize (new Dimension (640, 480));
    gle.pack ();
    gle.setVisible (true);
  }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 30 2006
Added on Dec 2 2006
3 comments
141 views