2015-04-07 88 views
1

我想添加一個CellPanel,它在JPanel內部延伸JPanel。我這樣做,因爲我有按鈕,從這些JPanels刪除內容並添加其他組件。問題是JPanelFlowLayout s不能從左上角定位我的CellPanel。我能做什麼?JPanel內的JPanel添加頂部填充

這裏就是我有這個問題的代碼:

JFrame mazeFrame = new JFrame("Create and Play"); 
    mazeFrame.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);   
    mazeFrame.setSize(640, 480); 
    mazeFrame.setResizable(false); 
    mazeFrame.setLocationRelativeTo(null); 
    mazeFrame.setLayout(new GridLayout(rows,columns));//max(7,10) 

    JPanel[] cellr = new JPanel[rows*columns]; 
    for(int i=0;i<rows*columns; i++){ 
     cellr[i] = new JPanel(); 
     cellr[i].setPreferredSize(new Dimension(mazeFrame.getWidth()/columns,mazeFrame.getHeight()/rows)); 
     mazeFrame.getContentPane().add(cellr[i]); 
    } 

    for(int i=0;i<rows*columns; i++){ 
     CellPanel cell = new CellPanel(wall.getImage()); 
     cell.setPreferredSize(new Dimension(mazeFrame.getWidth()/columns,mazeFrame.getHeight()/rows)); 
     cellr[i].add(cell); 
    } 

它所顯示: enter image description here

+0

您可以嘗試先將CellPanel添加到您的JPanel中,然後將JPanel添加到JFrame中。您也可以擺脫setPrefferedSize調用,因爲GridLayout應該能夠自動確定大小。 –

+1

有兩件事,你可以給'GridLayout'提供一個'hgap'和'vgap'屬性,並且不要使用框架大小去嘗試和計算你的組件的大小,它包括框架裝飾 – MadProgrammer

+0

問題是當我將CellPanel添加到JPanel。如果我直接將CellPanel添加到mazeFrame,它可以正常工作。我認爲問題在於JPanel的FlowLayout沒有將我的CellPanel與左上角對齊。 – Andrew

回答

0

我做了一些研究,我發現了一個解決方案。

JPanel[] cellr = new JPanel[rows*columns]; 
    for(int i=0;i<rows*columns; i++){ 
     cellr[i] = new JPanel(); 
     cellr[i].setLayout(new GridBagLayout()); 
     mazeFrame.getContentPane().add(cellr[i]); 
    } 

    GridBagConstraints g = new GridBagConstraints(); 
    for(int i=0;i<rows*columns; i++){ 
     CellPanel cell = new CellPanel(wall.getImage()); 
     cell.setPreferredSize(new Dimension(mazeFrame.getWidth()/columns,mazeFrame.getHeight()/rows)); 
     g.fill = GridBagConstraints.BOTH; 
     g.weightx = 1; 
     g.weighty = 1; 
     cellr[i].add(cell,g); 
    }