如何使用GridBagLayout()将图像放入jpanel?

问题描述 投票:0回答:1

当前,代码是:

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();
}

将导致:

enter image description here

每个Jlabel都正确放置在网格上的位置,除了图像显示在右上角而不是分配的位置。

java swing jframe layout-manager gridbaglayout
1个回答
2
投票

在此部分:

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

将修复它。

© www.soinside.com 2019 - 2024. All rights reserved.