2011-08-16 79 views
4

我试图在JPanel内使用BoxLayout,使用GridBagLayout来处理10(3x3 + 1)JButtonsGridBagLayout多个按钮+边框

但是,如果我使用胶水盒或类似的GridBagLayoutJPanel占用BoxLayout中的所有额外空间。我可能错过了一些东西,或者这是不可能做到的?

我用过的一个解决方案是用gridbaglayout里面的扩展元素向上推按钮。这将按钮放在正确的位置,但边框显得很大。

这里紧跟我的示例代码:

import java.awt.Container; 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 

import javax.swing.BorderFactory; 
import javax.swing.Box; 
import javax.swing.BoxLayout; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 

public class GridBagLayoutTest extends JFrame { 

    public GridBagLayoutTest(){ 
     super(); 
     this.setTitle("JVectorView"); 
     this.setSize(300,300); 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     Container content = this.getContentPane(); 
     content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); 
     content.add(new JLabel("Hello!")); 
     content.add(new Controls()); 
     content.add(Box.createGlue()); 
     this.setVisible(true); 
    } 


    private class Controls extends JPanel{ 
     private static final int WIDTH = 3, HEIGHT = 3; 

     public Controls(){ 
      GridBagConstraints constraints = new GridBagConstraints(); 

      //this.setBorder(BorderFactory.createLineBorder(Color.red)); 
      this.setBorder(BorderFactory.createTitledBorder("Some stuff")); 
      constraints.fill = GridBagConstraints.NONE; 
      this.setLayout(new GridBagLayout()); 
      for(int row = 0; row < HEIGHT; row++){ 
       for(int col = 0; col < WIDTH; col++){ 
        constraints.gridx = col; 
        constraints.gridy = row; 
        this.add(new JButton("B"+(col+row*WIDTH)), constraints); 

       } 
      } 
      constraints.gridx = 1; 
      constraints.gridy = 3; 
      this.add(new JButton("B"+(10)), constraints); 
     } 
    } 

    public static void main(String[] args) { 
     new GridBagLayoutTest(); 
    } 

} 

我想边境被周围的按钮紧。是否有可能让gridbaglayout在其内容中崩溃或是否始终强制填充面板?

+0

也许试着调整你放入网格的组件的最小和最大尺寸? – Marvo

+0

你想填补可用'JPanel's'区10'JButtons'? – mKorbel

+0

+1对你的问题编译,简单的解释 –

回答

1
JPanel p=new JPanel(new FlowLayout()); 
p.add(new Controls()); 
content.add(p); 
+0

感谢您的回复,但flowLayout的问题是我无法控制我想要组件的方向。在这种情况下,我希望它们垂直放置。 – larlin