I use the GridBagLayout
for creating a panel.
I would like the delete icon on the right corner of the panel. However, if the JTextArea
is not added to the panel, the delete icon will shift to the left.
How to do it properly?
There is my code for GridBagLayout panel setting
public void setting() {
try {
this.setLayout(new GridBagLayout());
c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0; // **** comment this line out to see effect ****
c.weighty = 1.0; // **** comment this line out to see effect ****
this.setBorder(BorderFactory.createLineBorder(Color.black));
addMouseListener(this);
buildTopJPane();
setVisible(true);
} catch (Exception err) {
Utility.DisplayErrorMsg(pageErrorPrefix + err.getMessage().toString());
}
}
There is the code for adding components into the panel
private void buildTopJPane() {
try {
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.NONE;
this.add(setAttonIconCreator(), c);
c.gridx = 5;
c.gridy = 0;
c.gridwidth = 4;
this.add(setDeleteIcon(), c);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 4;
this.add(setPageDateLabel(), c);
if (thisComment.content != null) {
if (thisComment.content.length() > 0)
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 4;
this.add(setContent(), c);
}
} catch (Exception err) {
Utility.DisplayErrorMsg(pageErrorPrefix + err.getMessage().toString());
}
}
Use a combination of weightx
and anchor
on the delete icon.
For example, try using weightx = 1
and anchor = GridBagConstraints.WEST
. Note, this will also push the other content to the left.
You could also try using weightx = 1
on the comment panel instead.
You may also find better use of gridwidth
and cell placement allows you to overlap components across columns which will give you a better result.
Don't forget to reset the constraints before you use them on the next component.