W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
GridBagLayout在與GridLayout類似的行和列中布置的單元格網(wǎng)格中布置組件。
由GridBagLayout創(chuàng)建的網(wǎng)格的所有單元格不必具有相同的大小。
組件不必準確放置在一個單元格。
組件可以水平和垂直跨越多個單元格。
我們可以指定單元格內(nèi)的組件應如何對齊。
GridBagLayout和GridBagConstraints類一起使用。這兩個類都在java.awt包中。
GridBagLayout類定義了一個GridBagLayout布局管理器。GridBagConstraints類為GridBagLayout中的組件定義約束。
以下代碼創(chuàng)建GridBagLayout類的對象并將其設置為JPanel的布局管理器:
JPanel panel = new JPanel(); GridBagLayout gridBagLayout = new GridBagLayout(); panel.setLayout(gridBagLayout);
下面的代碼展示了如何使用一個簡單的GridBagLayout。
import java.awt.Container; import java.awt.GridBagLayout; /* w w w . ja v a2s. c om*/ import javax.swing.JButton; import javax.swing.JFrame; public class Main { public static void main(String[] args) { String title = "GridBagLayout"; JFrame frame = new JFrame(title); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = frame.getContentPane(); contentPane.setLayout(new GridBagLayout()); for (int i = 1; i <= 9; i++) { contentPane.add(new JButton("Button " + i)); } frame.pack(); frame.setVisible(true); } }
這是我們用來創(chuàng)建和使用GridBagConstraints的正常過程。
這是我們用來創(chuàng)建和使用GridBagConstraints的正常過程。...
GridBagConstraints gbc = new GridBagConstraints();
然后,在約束對象中設置gridx和gridy屬性
gbc.gridx = 0; gbc.gridy = 0;
之后,添加一個JButton并傳遞約束對象作為 add()方法的第二個參數(shù)。
container.add(new JButton("B1"), gbc);
我們可以將gridx屬性更改為1. gridy屬性保持為0,如先前設置的。
gbc.gridx = 1;
然后,向容器中添加另一個JButton
container.add(new JButton("B2"), gbc);
以下代碼演示了如何為組件設置gridx和gridy值。
import java.awt.Container; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; //from ww w .jav a 2 s. co m import javax.swing.JButton; import javax.swing.JFrame; public class Main { public static void main(String[] args) { String title = "GridBagLayout"; JFrame frame = new JFrame(title); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = frame.getContentPane(); contentPane.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); for (int y = 0; y < 3; y++) { for (int x = 0; x < 4; x++) { gbc.gridx = x; gbc.gridy = y; String text = "Button (" + x + ", " + y + ")"; contentPane.add(new JButton(text), gbc); } } frame.pack(); frame.setVisible(true); } }
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: