2017-09-06 39 views
0

這是我目前的形式是什麼樣子:爪哇 - 如何對齊一個網格佈局內JPanels

enter image description here

我試圖創建一個單選按鈕的4列的形式,但是當我嘗試添加面板,拿着按鈕,到他們似乎錯誤對齊的另一個面板的網格佈局。我沒有在網格佈局上設置任何高度的邊界所以我不確定是什麼導致它轉移。

我的代碼:

public class Window extends JFrame{ 
public void paint(Graphics g) { 
    super.paint(g); // ?? 
    getContentPane().setBackground(Color.WHITE); // background color 
} 

public static void main(String[] args) { 
    Window w = new Window(); 
    w.setSize(1500,1000); 
    w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    JLabel title = new JLabel("Menu", SwingConstants.CENTER); 
    title.setFont(title.getFont().deriveFont(32f)); 

    Container titlePanel = new JPanel(); // used as a container 
    titlePanel.setBackground(Color.WHITE); 
    FlowLayout flow = new FlowLayout(); // Create a layout manager 
    titlePanel.setLayout(flow);// assign flow layout to panel 
    titlePanel.add(title); // add label to panel 
    w.getContentPane().add(BorderLayout.NORTH,titlePanel); 

    Container mains = new JPanel(new GridLayout(7, 0)); 
    mains.setBackground(Color.RED); 
    JLabel mainsHeader = new JLabel("Mains"); 
    mainsHeader.setFont(mainsHeader.getFont().deriveFont(24f)); 
    mains.add(mainsHeader); 

    Container noodles = new JPanel(new GridLayout(4, 0)); 
    noodles.setBackground(Color.GREEN); 
    JLabel noodlesHeader = new JLabel("Noodles"); 
    noodlesHeader.setFont(noodlesHeader.getFont().deriveFont(24f)); 
    noodles.add(noodlesHeader); 

    Container sauces = new JPanel(new GridLayout(3, 0)); 
    sauces.setBackground(Color.BLUE); 
    JLabel saucesHeader = new JLabel("Sauce"); 
    saucesHeader.setFont(saucesHeader.getFont().deriveFont(24f)); 
    sauces.add(saucesHeader); 


    Container extras = new JPanel(new GridLayout(6, 0)); 
    extras.setBackground(Color.YELLOW); 
    JLabel extrasHeader = new JLabel("Extra"); 
    extrasHeader.setFont(extrasHeader.getFont().deriveFont(24f)); 
    extras.add(extrasHeader) 

    Container menuSelection = new JPanel(new GridLayout(0,4)); 
    menuSelection.add(mains); 
    menuSelection.add(noodles); 
    menuSelection.add(sauces); 
    menuSelection.add(extras); 

    w.getContentPane().add(menuSelection); 

    w.setVisible(true); 
} 
} 
+0

每個GridLayout中的行數是不同的。這就是標籤出現在不同位置的原因。您是否需要每個佈局中的那些行? –

+0

1)以最小尺寸提供ASCII圖形或簡單的GUI圖形*圖形,如果可調整大小,更多寬度和高度 - 則顯示應該如何使用額外空間。 2)請參閱[檢測/修復代碼塊的懸掛緊密支架](http://meta.stackexchange.com/q/251795/155831),以解決問題,我不再擔心修復問題。 3)最好不要在像JFrame這樣的頂層容器中進行自定義繪畫,而應該在它上面添加一個面板並重寫'paintComponent(Graphics)'而不是'paint(Graphics)'4)。儘管如此,不要調用從.. –

+0

.. paint方法更改GUI的方法,因爲它可能會創建無限循環。而是在構造函數中設置BG顏色。 5)在添加所有組件後,但在調用setVisible(true)之前,總是'裝載()'頂層容器。 –

回答

0

你並不需要設置一個GridLayout的每個子板上。您只應將其設置爲mains,可能具有正確數量的行和列。

如果您只需要標籤,您可以將它們直接添加到主電源,並且它應該爲您準備好。