我在这里的应用程序是拼接由六个独立部分组成的整个图像。我将它们声明为JLabels并使用GridLayout设置布局。但是,JLabels不在给定的行和列之后,并且两者之间存在间隙。

您认为我在某处的编码有误吗?
谢谢!

import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.awt.Color;

class MyGridLayout extends JPanel {

public static void main(String [] args)
{
    JFrame pictureFrame = new JFrame("Picture Frame");
    GridLayout myGrid = new GridLayout(2, 3, 0, 0);
    pictureFrame.setLayout(myGrid);

    MyGridLayout thePanel = new MyGridLayout();
    pictureFrame.add(thePanel);

    ImageIcon i = new ImageIcon("IMAGES/chunkE.gif");
    ImageIcon j = new ImageIcon("IMAGES/chunkC.gif");
    ImageIcon k = new ImageIcon("IMAGES/chunkB.gif");
    ImageIcon l = new ImageIcon("IMAGES/chunkI.gif");

    JLabel label1 = new JLabel(i);
    JLabel label2 = new JLabel(j);
    JLabel label3 = new JLabel(k);
    JLabel label4 = new JLabel(l);

    thePanel.add(label1);
    thePanel.add(label2);
    thePanel.add(label3);
    thePanel.add(label4);

    pictureFrame.add(thePanel);
    pictureFrame.pack();
    pictureFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pictureFrame.setVisible(true);
}
}

最佳答案

设置JPanel而不是JFrame的布局

GridLayout myGrid = new GridLayout(2, 3, 0, 0);
thePanel.setLayout(myGrid);


JPanel默认使用FlowLayout

09-30 12:41