我想使用GridBagLayout显示图像,JLabel和JTextField。

图像应如下所示

java - JAVA中的GridBagLayout-LMLPHP

这是我尝试过的,但是JTextField显示在图像下方,除了

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

最佳答案

问题是您添加和减去gridy的值是错误的。要将代码调整为qtyField位于foodLabel的右侧,只需删除这些gbc.gridy并在gbc.gridx ++之后添加panel.add(foodLabel[i], gbc)

现在,它不会像您的图像一样(至少我认为除非您正确设置foodLabel,否则它就不会如此,即使您这样做,正确对齐也将需要花费很多工作),因此您可以创建一个新数组JLabelfoodImage),其大小与foodLabel相同,在其中只能显示图像。然后,您的代码几乎正确,只需移动几行并添加foodImage。我写的是:

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

10-05 22:12