Search code examples
javaswingjframelayout-managergridbaglayout

How to put an image into jpanel with GridBagLayout()?


Currently, the code is:

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

Which results in:

enter image description here

Every Jlabel is put properly in its place on the grid, except the image which appears in top right corner instead of assigned place.


Solution

  • In this part:

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

    you add the component to the container without the GridBagConstratints. That's why the component is not being added in the proper location. So, changing it to:

    panelForm.add(label,c); //Add with constraints
    

    will fix it.