2015-04-07 92 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); 
    }