【问题标题】:How to put an image into jpanel with GridBagLayout()?如何使用 GridBagLayout() 将图像放入 jpanel?
【发布时间】:2019-09-30 17:23:05
【问题描述】:

目前,代码为:

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 都正确放置在网格上的位置,除了出现在右上角而不是指定位置的图像。

【问题讨论】:

  • panelForm.add(label); 不应该是panelForm.add(label,c);
  • 好的,谢谢。我不敢相信我竟然半个多小时都没有注意到它。
  • frame.setSize(1200, 800);//Give it a size BTW - 最好等到组件添加完毕,然后frame.pack(); //Calculate size needed!
  • @AndrewThompson 完成。

标签: java swing jframe layout-manager gridbaglayout


【解决方案1】:

在这部分:

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

会解决的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    相关资源
    最近更新 更多