W3Cschool
恭喜您成為首批注冊(cè)用戶(hù)
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
GridBagLayout在與GridLayout類(lèi)似的行和列中布置的單元格網(wǎng)格中布置組件。
由GridBagLayout創(chuàng)建的網(wǎng)格的所有單元格不必具有相同的大小。
組件不必準(zhǔn)確放置在一個(gè)單元格。
組件可以水平和垂直跨越多個(gè)單元格。
我們可以指定單元格內(nèi)的組件應(yīng)如何對(duì)齊。
GridBagLayout和GridBagConstraints類(lèi)一起使用。這兩個(gè)類(lèi)都在java.awt包中。
GridBagLayout類(lèi)定義了一個(gè)GridBagLayout布局管理器。GridBagConstraints類(lèi)為GridBagLayout中的組件定義約束。
以下代碼創(chuàng)建GridBagLayout類(lèi)的對(duì)象并將其設(shè)置為JPanel的布局管理器:
JPanel panel = new JPanel(); GridBagLayout gridBagLayout = new GridBagLayout(); panel.setLayout(gridBagLayout);
下面的代碼展示了如何使用一個(gè)簡(jiǎn)單的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); } }
這是我們用來(lái)創(chuàng)建和使用GridBagConstraints的正常過(guò)程。
這是我們用來(lái)創(chuàng)建和使用GridBagConstraints的正常過(guò)程。...
GridBagConstraints gbc = new GridBagConstraints();
然后,在約束對(duì)象中設(shè)置gridx和gridy屬性
gbc.gridx = 0; gbc.gridy = 0;
之后,添加一個(gè)JButton并傳遞約束對(duì)象作為 add()方法的第二個(gè)參數(shù)。
container.add(new JButton("B1"), gbc);
我們可以將gridx屬性更改為1. gridy屬性保持為0,如先前設(shè)置的。
gbc.gridx = 1;
然后,向容器中添加另一個(gè)JButton
container.add(new JButton("B2"), gbc);
以下代碼演示了如何為組件設(shè)置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號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話(huà):173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: