2011-08-16 51 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