user3630154
user3630154

Reputation: 23

How do I use GridBagLayout

I have have a JLabel, a JButton and a JTextField; I need to put the JLabel in cell (0,0) from the JFrame origin and then put a JTextField (1,0) and finally put a JButton (0,1) on the second line. But, all my components are put in the same row and they start from left to right.

My code:

public static  void initializeFrame(){
  GridBagLayout layout  = new GridBagLayout();
  // set frame layout      
  JFrame frame = new JFrame("JFrame Source Demo");
  frame.setSize(new Dimension(400,200));
  frame.setLayout(new GridBagLayout());
  GridBagConstraints c = new GridBagConstraints();
  c.fill = GridBagConstraints.HORIZONTAL;
  JPanel    topPanel = new JPanel();
  JLabel jlbempty = new JLabel("MacAddress");
  c.gridx = 0;
  c.gridy = 0;
  c.ipadx = 30;
  c.ipady = 10;
  topPanel.add(jlbempty,c);
  JTextField field1 = new JTextField();
  c.gridx = 1;   
  c.gridy = 0;
  c.ipadx = 30;
  c.ipady = 10;
  topPanel.add(field1,c);
  field1.setPreferredSize(new Dimension(150, 20));
  JButton jb = new JButton("Generation Mac");
  c.gridx = 0;
  c.gridy = 1;
  c.ipadx = 30;
  c.ipady = 10; 
  layout.setConstraints( jb, c ); // set constraints
  topPanel.add(field1,c); 
  topPanel.add(jb,c);
  frame.add(topPanel);
  frame.pack();
  frame.setVisible(true);
}

Upvotes: 1

Views: 54

Answers (1)

Braj
Braj

Reputation: 46891

Some of the things that I observed in your code.

  • Set layout of the topPanel to GridBagLayout.

  • You are calling topPanel.add(field1, c); two times.

  • Don't use preferred size instead use relative size. Just hand over it to Layout manger to size the component.


Read more about How to Use GridBagLayout for more clarity and find the sample code as well.

Please read more about the other properties of GridBagLayout.


Here is the simplified code with inline comments.

GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
// c.insets=new Insets(5,5,5,5);   // margin outside the panel

JPanel topPanel = new JPanel(new GridBagLayout());

JLabel jlbempty = new JLabel("MacAddress");
c.gridx = 0;
c.gridy = 0;
// c.weightx=0.25;     // width 25% for 1st column
topPanel.add(jlbempty, c);

JTextField field1 = new JTextField();
c.gridx = 1;
c.gridy = 0;
// c.weightx=0.75;     // width 75% for 2nd column
topPanel.add(field1, c);

JButton jb = new JButton("Generation Mac");
c.gridx = 0;
c.gridy = 1;
//c.gridwidth = 2;    //SPAN to 2 columns if needed
// c.weightx=1.0;     // back to width 100%
topPanel.add(jb, c);

Upvotes: 1

Related Questions