Java 如何使用GridBagLayout()将图像放入jpanel?
目前,代码为:Java 如何使用GridBagLayout()将图像放入jpanel?,java,swing,jframe,layout-manager,gridbaglayout,Java,Swing,Jframe,Layout Manager,Gridbaglayout,目前,代码为: JFrame frame = new JFrame("App"); frame.setSize(1200, 800);//Give it a size frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//Make it go away on close JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT)); //TU ZMIENIAC frame.add
JFrame frame = new JFrame("App");
frame.setSize(1200, 800);//Give it a size
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//Make it go away on close
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT)); //TU ZMIENIAC
frame.add(panel);//Add it to your frame
(...)
JPanel panelForm = new JPanel(new GridBagLayout());
panel.add(panelForm);
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10,10,10,10);
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.LINE_END;
(...)
panelForm.add(label_pageCount, c);
c.gridy++;
try {
URL url = new URL(JSONLists.thumbnail.get(page));
BufferedImage image = ImageIO.read(url);
JLabel label = new JLabel(new ImageIcon(image));
panelForm.add(label);
} catch (Exception exp) {
exp.printStackTrace();
}
其结果是:
每个Jlabel都正确地放置在网格上的相应位置,但出现在右上角而不是指定位置的图像除外。在本部分中:
try {
URL url = new URL(JSONLists.thumbnail.get(page));
BufferedImage image = ImageIO.read(url);
JLabel label = new JLabel(new ImageIcon(image));
panelForm.add(label); //here
} catch (Exception exp) {
exp.printStackTrace();
}
将组件添加到容器中时,不使用gridbagcontstants
。这就是为什么没有将组件添加到正确的位置。因此,将其更改为:
panelForm.add(label,c); //Add with constraints
将修复它。在本部分中:
try {
URL url = new URL(JSONLists.thumbnail.get(page));
BufferedImage image = ImageIO.read(url);
JLabel label = new JLabel(new ImageIcon(image));
panelForm.add(label); //here
} catch (Exception exp) {
exp.printStackTrace();
}
将组件添加到容器中时,不使用gridbagcontstants
。这就是为什么没有将组件添加到正确的位置。因此,将其更改为:
panelForm.add(label,c); //Add with constraints
将修复它。
panelForm.add(标签)代码>不应为panelForm.add(标签,c)代码>?是的,谢谢。我简直不敢相信我有半个多小时没有注意到它。frame.setSize(1200800)//给它一个大小
BTW-更好的方法是等待组件添加完毕,然后frame.pack()//计算所需尺寸代码>@AndrewThompson完成。panelForm.add(标签)代码>不应为panelForm.add(标签,c)代码>?是的,谢谢。我简直不敢相信我有半个多小时没有注意到它。frame.setSize(1200800)//给它一个大小
BTW-更好的方法是等待组件添加完毕,然后frame.pack()//计算所需尺寸代码>@AndrewThompson已完成。