shurrok
shurrok

Reputation: 831

How to make grids different in GridBagLayout in Java?

what I want to achieve is something like this:

enter image description here

This is my code:

JDialog messageDialog = new JDialog();
messageDialog.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
messageDialog.setBounds(0, 0, 350, 250);
messageDialog.setLocationRelativeTo(null);
messageDialog.setVisible(true);

JPanel btnPanel = new JPanel();
JPanel clearPanel = new JPanel();
JPanel labelsPanel = new JPanel();
JPanel txtPanel = new JPanel();
JButton newMessage = new JButton("New");
JButton recievedMessages = new JButton("Recieved");
JButton sendMessages = new JButton("Sent");
JButton refreshMessages = new JButton("Refresh");
JLabel recievedMessLab = new JLabel("Messages get:");
JTextPane txtToSend = new JTextPane();

btnPanel.setLayout(new GridLayout(4, 1));
btnPanel.add(newMessage);
btnPanel.add(recievedMessages);
btnPanel.add(sendMessages);
btnPanel.add(refreshMessages);

c.gridx = 0;
c.gridy = 0;
messageDialog.add(clearPanel, c);

c.gridx = 1;
c.gridy = 0;
messageDialog.add(labelsPanel, c);

c.gridx = 0;
c.gridy = 1;
messageDialog.add(btnPanel, c);

c.gridx = 1;
c.gridy = 1;
messageDialog.add(txtPanel, c);

labelsPanel.add(recievedMessLab);

I don't know why I get some free space around all the panels and I can't figure out how to resize the grids. Oracle tutorial doesn't help too. What is the easiest way to resize this? How to rid of that free space?

Upvotes: 0

Views: 22

Answers (1)

Quota
Quota

Reputation: 583

You need to add weight and fill information to your GridBagConstraints so the layout manager knows which components to strech over the available space.

Try the following:

c.gridx = 0;
c.gridy = 0;
c.fill = c.NONE;  // dont fill (strech)
messageDialog.add(clearPanel, c);

c.gridx = 1;
c.gridy = 0;
c.weightx = 1; // horizontal weight: 1
c.fill = c.HORIZONTAL; // fill (strech) horizontally
messageDialog.add(labelsPanel, c);

c.gridx = 0;
c.gridy = 1;
c.weightx = 0; // horizontal weight: back to 0
c.weighty = 1; // vertical weight: 1
c.fill = c.VERTICAL; // fill (strech) vertically
messageDialog.add(btnPanel, c);

c.gridx = 1;
c.gridy = 1;
c.weightx = 1; // both weights: 1
c.weighty = 1; // both weights: 1
c.fill = c.BOTH; // and fill both ways, vertically and horizontally
messageDialog.add(txtPanel, c);

Revisit the part about weightx, weighty and fill in the tutorial to get a clue how they work.

PS: txtPanel is empty and txtToSend is never used?

Upvotes: 1

Related Questions