簡體   English   中英

在網格樣式的布局中為JButton設置固定大小

[英]Setting a fixed size for JButtons in a grid-style layout

我想讓16個按鈕顯示為4x4網格。 每個按鈕應具有相同的大小,並具有相等的間隙。

我已經能夠設置間隙大小,但是我不能減小按鈕的大小。 我基本上只是將其用於組布局...

layout.setHorizontalGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(LEADING)
                    .addComponent(button1)
                    .addComponent(button5)
                    .addComponent(button9)
                    .addComponent(button13))
               .addGroup(layout.createParallelGroup(LEADING)
                    .addComponent(button2)
                    .addComponent(button6)
                    .addComponent(button10)
                    .addComponent(button14))
               .addGroup(layout.createParallelGroup(LEADING)
                    .addComponent(button3)
                    .addComponent(button7)
                    .addComponent(button11)
                    .addComponent(button15))
               .addGroup(layout.createParallelGroup(LEADING)
                    .addComponent(button4)
                    .addComponent(button8)
                    .addComponent(button12)
                    .addComponent(button16))
            );

            layout.setVerticalGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(BASELINE)
                    .addComponent(button1)
                    .addComponent(button2)
                    .addComponent(button3)
                    .addComponent(button4))
               .addGroup(layout.createParallelGroup(BASELINE)
                    .addComponent(button5)
                    .addComponent(button6)
                    .addComponent(button7)
                    .addComponent(button8))
               .addGroup(layout.createParallelGroup(BASELINE)
                    .addComponent(button9)
                    .addComponent(button10)
                    .addComponent(button11)
                    .addComponent(button12))
               .addGroup(layout.createParallelGroup(BASELINE)
                    .addComponent(button13)
                    .addComponent(button14)
                    .addComponent(button15)
                    .addComponent(button16))

有人可以幫我更好的方法。

您也可以嘗試使用GridLayout()。 這將所有組件排列在一個網格中,行和列由參數定義。 您使用以下行創建它

GridLayout g = new GridLayout(rows, columns)

您需要導入AWT,以便您的代碼如下所示:

GridLayout g = new GridLayout(4,4);
//Add it to your JPanel
myJpanel.setLayout(g);
//then
myJpanel.add(button1);
//the rest of your code

GroupLayout中每個組件的大小受三個值約束; 最小尺寸,首選尺寸和最大尺寸

嘗試:

button.setPreferredSize(new Dimension(50, 10));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM