簡體   English   中英

為什么JLabel不遵循GridLayout?如何消除兩者之間的差距?

[英]Why is the JLabel not following the GridLayout and how to remove the gap in between?

我在這里的應用程序是拼接由六個獨立部分組成的整個圖像。 我將它們聲明為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

嘗試這個:

public class Main extends JFrame
{
    public Main()
    {
        super("Title");
        setLayout(new BorderLayout());
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(2,3);

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

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

        add(panel, BorderLayout.NORTH);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    public static void main(String[] args)
    {
        Main m = new Main();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM