Java GridBagLayout和JFrame内容窗格
我目前正在尝试正确地连接框架内的一些组件。我正在使用GridBagLayout,但这条线似乎在制造麻烦:Java GridBagLayout和JFrame内容窗格,java,swing,jpanel,layout-manager,Java,Swing,Jpanel,Layout Manager,我目前正在尝试正确地连接框架内的一些组件。我正在使用GridBagLayout,但这条线似乎在制造麻烦: frame.setContentPane(new ImagePanel(myImage)); 我想把中间的按钮放在中间,但它不起作用。如果我评论它,一切都很好。还尝试创建另一个具有BorderLayout的面板并将其居中,但结果相同。我想要一个背景图像到我的JFrame。我该怎么办?还是我做错了什么 private Image image; public MainClass(Image
frame.setContentPane(new ImagePanel(myImage));
我想把中间的按钮放在中间,但它不起作用。如果我评论它,一切都很好。还尝试创建另一个具有BorderLayout的面板并将其居中,但结果相同。我想要一个背景图像到我的JFrame。我该怎么办?还是我做错了什么
private Image image;
public MainClass(Image image){
this.image = image;
GridBagConstraints c = new GridBagConstraints();
this.setOpaque(false);
this.setLayout(new GridBagLayout());
c.gridx = 0;
c.gridy = 0;
this.add(new JButton("1"), c);
c.gridx = 0;
c.gridy = 1;
this.add(new JButton("2"), c);
c.gridx = 0;
c.gridy = 2;
this.add(new JButton("3", c);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
public static void main(String[] args) throws IOException {
BufferedImage myImage = ImageIO.read(new File("images/city.png"));
JFrame frame = new JFrame();
frame.setContentPane(new MainClass(myImage));
frame.setSize(600, 375);
frame.setUndecorated(true);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
//编辑:我刚刚意识到我正在尝试将面板添加到我的框架中。。乍一看,它的效果相当不错。最直截了当、最残酷的答案是——不要使用Java Swigs的布局管理器,因为它在大多数情况下几乎不可用。试试第三方的 我强烈建议MIG布局从它是非常强大的,灵活的,易于使用的layour经理与体面的文档和例子
frame.setContentPane(new ImagePanel(myImage));
frame.add(new MainClass());
首先,将ImagePanel设置为内容窗格,这是正常的。然后将MainClass()添加到框架中,这可能是正常的。这意味着MainClass将被添加到ImagePanel
如果我评论一下,一切都很好
默认情况下,JPanel使用FlowLayout
,因此MainClass将居中于面板顶部
您需要将ImagePanel的布局设置为
边框布局
。然后,它的工作原理应该与将main类直接添加到框架中一样。JLabel background=newjlabel(newimageicon(ImageIO.read(…));
setContentPane(背景)
添加所有其他按钮当你说它不起作用时,你的确切意思是什么?