如何使用 GridBagLayout() 将图像放入 jpanel?
How to put an image into jpanel with 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(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();
}
您将组件添加到没有 GridBagConstratints
的容器中。这就是组件未添加到正确位置的原因。因此,将其更改为:
panelForm.add(label,c); //Add with constraints
会修复它。
目前代码为:
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();
}
您将组件添加到没有 GridBagConstratints
的容器中。这就是组件未添加到正确位置的原因。因此,将其更改为:
panelForm.add(label,c); //Add with constraints
会修复它。