Search code examples
javauser-interfacelayoutgridbaglayout

GridBagLayout in JAVA


I want to display image, JLabel, and JTextField using GridBagLayout.

The image should looked like this

enter image description here

This is what I have tried, but the JTextField display below images, not besides

   JPanel panel = new JPanel(new GridBagLayout());
   gbc = new GridBagConstraints();

   for (int i = 0; i < ELEMENTS; i++) {
        Image image = ImageIO.read(file[i]);
        Image imageScaled = image.getScaledInstance(80, 95, Image.SCALE_SMOOTH);
        ImageIcon imageIcon = new ImageIcon(imageScaled);
        foodLabel[i] = new JLabel(imageIcon);
        qtyField[i] = new JTextField(3);
    }

    gbc.gridx = 0;
    for (int i = 0; i < ELEMENTS; i++) {
        if (i % 3 == 0) {
            gbc.gridy += 2;
            gbc.gridx = 0;
        }
        panel.add(foodLabel[i], gbc);
        gbc.gridy++;
        panel.add(qtyField[i], gbc);
        gbc.gridx++;
        gbc.gridy--;
        tabbedPane.addTab(text, panel);
    }

Solution

  • The problem is that you are adding and subtracting the value of gridy wrong. To adjust the code to qtyField be on the right side of foodLabel, simply remove those gbc.gridy and add a gbc.gridx ++ after panel.add(foodLabel[i], gbc).

    Now, it won't be as your image (at least I think it wouldn't unless you properly setup the foodLabel, and even if you do, align properly will be a little to much work), to do so you can create a new array of JLabel (foodImage), the same size of foodLabel, where you can show only the images. Then your code will be almost right, only move some lines and add the foodImage. I wrote and here it is:

    JPanel panel = new JPanel(new GridBagLayout());
    gbc = new GridBagConstraints();
    // Just to give a space between the components
    gbc.insets = new Insets(5, 5, 5, 5);
    
    for (int i = 0; i < ELEMENTS; i++) {
        Image image = ImageIO.read(file[i]);
        Image imageScaled = image.getScaledInstance(80, 95, Image.SCALE_SMOOTH);
        ImageIcon imageIcon = new ImageIcon(imageScaled);
        foodImage[i] = new JLabel(imageIcon);
        foodLabel[i] = new JLabel("Label");
        qtyField[i] = new JTextField(3);
    }
    
    gbc.gridx = 0;
    for (int i = 0; i < ELEMENTS; i++) {
        if (i % 3 == 0) {
            gbc.gridy += 2;
            gbc.gridx = 0;
        }
    
        // Add the image
        panel.add(foodImage[i], gbc);
        // Below the image
        gbc.gridy++;
        // Add the label
        panel.add(foodLabel[i], gbc);
        // Go back up
        gbc.gridy--;
        // Next column
        gbc.gridx++;
        // Add the textfield
        panel.add(qtyField[i], gbc);
        // Next column
        gbc.gridx++;
        tabbedPane.addTab(text, panel);
    }
    

    I ran this code, and should be like this