网格包布局
令人惊讶的是,基于网格的布局具有灵活性。
如果要将一个组件放置在另一个组件之上,则必须告诉布局这两个组件共享同一单元格。这里就是
gridx
和
gridy
很重要
所以当你做一些像…
add(mainL, gbc);
add(main);
您允许布局管理器决定
main
应该布局,这不是您想要的,相反,您需要为两个组件提供相同的
网格
/
格里迪
约束,例如…
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SecondPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
class SecondPanel extends JPanel {
public SecondPanel() {
setLayout(new GridBagLayout());
JPanel main = new JPanel(new GridBagLayout());
main.setBorder(new LineBorder(Color.GRAY));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.LINE_START;
main.add(new JLabel("Ope"), gbc);
gbc.anchor = GridBagConstraints.LINE_END;
main.add(new JLabel("opeV"), gbc);
gbc.anchor = GridBagConstraints.LINE_START;
main.add(new JLabel("am"), gbc);
gbc.anchor = GridBagConstraints.LINE_END;
main.add(new JLabel("amV"), gbc);
gbc.anchor = GridBagConstraints.LINE_START;
main.add(new JLabel("cry"), gbc);
gbc.anchor = GridBagConstraints.LINE_END;
main.add(new JLabel("cryV"), gbc);
gbc.anchor = GridBagConstraints.CENTER;
main.add(new JButton("Add"), gbc);
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();
JLabel mainL = new JLabel();
mainL.setIcon(new ImageIcon(img));
mainL.setBorder(new LineBorder(Color.RED));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(main, gbc);
add(mainL, gbc);
}
}
}
我走了
主要的
opaque
并添加了边框以便您可以看到它。还要注意的是,组件是以filo(相反)顺序显示的
网格包布局
是一种艺术形式,一种你只需在其中混来混去就能掌握的艺术形式
但这不能解决我的问题
你的意思是…
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(main, gbc);
gbc.gridx++;
add(mainL, gbc);