[英]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.