簡體   English   中英

Java:如何在GridLayout中嵌套JPanel?

[英]Java: How to nest JPanel in a GridLayout?

我想知道如何使用GridLayout嵌套JPanel 它應該是這樣的。

在此輸入圖像描述

到目前為止,我通過兩種方式解決了這個問題,

  • 使用JPanel
  • 使用JLabel

並且它們都沒有工作(僅顯示創建的第一個面板)。

以下是JPanel方法的代碼:

    int x=20, y=20;
    JPanel [] panels = new JPanel[3];
    JLabel animal = new JLabel(new ImageIcon(getClass().getResource("Pictures/animal.gif")));
    JLabel map = new JLabel(new ImageIcon(getClass().getResource("Pictures/map.gif")));
    JLabel mountain = new JLabel(new ImageIcon(getClass().getResource("Pictures/mountain.gif")));

    for(int i=0;i<panels.length;i++)
    {
        if(i>0)
        {
            x+=x;
            y+=y;
        }
        panels[i] = new JPanel(new GridLayout(2,2));
        panels[i].setPreferredSize(new Dimension(x,y));

        if(i==0)
            panels[i].add(new JPanel());

        else
            panels[i].add(panels[i-1]);

        panels[i].add(mountain);
        panels[i].add(map);
        panels[i].add(animal);
    }       
    add(panels[2]);

一種選擇是創建一個類,該類將表示將圖像划分為網格的面板。 唯一的問題是左上象限,它通常包含嵌套面板,在某些時候你希望它只包含一個空白面板。 所以也許這樣的事情(除了各種優化):

 class GridPanel extends JPanel{

    JLabel mountain, map, animal;

    public GridPanel(JPanel panel){
        super();
        setLayout(new GridLayout(2, 2));
        animal = new JLabel(new ImageIcon(getClass().getResource("pictures/animal.gif")));
        map = new JLabel(new ImageIcon(getClass().getResource("pictures/map.gif")));
        mountain = new JLabel(new ImageIcon(getClass().getResource("pictures/mountain.gif")));
        add(panel);
        add(mountain);
        add(map);
        add(animal);
    }

}

請注意,它接受要在網格左上角顯示的面板。 然后使用指定的面板調用此coud。 所以在你想要創建主面板的時候:

   JPanel grid = new GridPanel(new JPanel()); //initial
    for(int i = 1; i <= 5; i++){
        grid = new GridPanel(grid);
    }
    add(grid);

使用空白JPanel創建初始網格。 並且每個后續網格都將包含前一個網格作為左上方面板。 您必須調整圖像等大小,甚至可能避免多次加載圖像等。但這是另一個問題。 此示例顯示了5個嵌套面板。

為了清楚起見,您應該使用ImageIO加載圖像一次並重復使用圖像。 例如,您可以在主類中創建這樣的BufferedImage:

  BufferedImage mointainImg = ImageIO.read(new File("pictures/mountain.gif"));

當你想創建JLabel時,你可以這樣做:

  mountain = new JLabel(new ImageIcon(mountainImg));

而且優點是你可以根據需要稍微操控圖像。

您遇到的一個問題是圖像沒有縮放。 要縮放圖像,請使用Image.getScaledInstance() 適當的縮放至少可以解決可見圖像被切斷的問題。 它也可能導致其他圖像顯示,因為它們可能只是隱藏在可見圖像后面,因為它們太大了。

暫無
暫無

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

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