I have the following problem. I have a JPanel
with GridBagLayout()
set. I add another JPanel
to it with the same layout manager. I have several different objects in it. The problem is that I can not set them so that the objects marked with No. 2 are in front of the object number 1. That is, objects number 2 should be first from the left side.
Below the code:
public MainPanel() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
SecondPanel secondPanel = new SecondPanel();
gbc.insets = new Insets(10, 20, 10, 20);
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.LINE_END;
gbc.weightx = 0.1;
add(secondPanel , gbc);
}
class SecondPanel extends JPanel {
public SecondPanel () {
setLayout(new GridBagLayout());
JPanel main = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.LINE_START;
main.add(ope, gbc);
gbc.anchor = GridBagConstraints.LINE_END;
main.add(opeV, gbc);
gbc.anchor = GridBagConstraints.LINE_START;
main.add(am, gbc);
gbc.anchor = GridBagConstraints.LINE_END;
main.add(amV, gbc);
gbc.anchor = GridBagConstraints.LINE_START;
main.add(cry, gbc);
gbc.anchor = GridBagConstraints.LINE_END;
main.add(cryV, gbc);
gbc.anchor = GridBagConstraints.BOTH;
main.add(addButton);
BufferedImage img = new BufferedImage(320, 240, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setColor(Color.RED);
g2d.drawLine(0, 0, 320, 240);
g2d.drawLine(320, 0, 0, 240);
g2d.dispose();
mainL.setIcon(new ImageIcon(img));
mainL.setBorder(new LineBorder(Color.RED));
gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.gridwidth = 1;
gbc.anchor = GridBagConstraints.WEST;
add(mainL, gbc);
add(main);
setVisible(true);
}
}
Screenshot :
EDIT : I solved problem, for first in this code was mistake add(mainL, gbc);
should be main.add(mainL,gbc);
. Secondly, I make two different panels from SecondPanel
and to MainPanel
separatly.
Stop, go read How to Use GridBagLayout and make sure you keep the JavaDocs for
GridBagLayout
andGridBagConstraints
on hand.GridBagLayout
is a, surprisingly, "grid" based layout, with flexibility.If you want to place one component on top of another, then you're going to have to tell the layout that both components share the same cell. This is where
gridx
andgridy
are importantSo when you do something like...
You're allowing the layout manager to make decisions about how best
main
should laid out, which isn't what you want, instead, you need to provide both components with the samegridx
/gridy
constraint, for example...I've left
main
opaque
and added a border so you can see it. Also beware, that components are displaying in FILO (reverse) orderGridBagLayout
is an art form, one you just have to muck about with to come to grips withYou mean something like...