我们可以在 Java 中组合 GridLayout 和 BorderLayout 吗?
是的,正如下面所示,我们可以使用 Java Swings 来实现。这里,我们有一个已设置 GridLayout 的面板,还有一个已设置 BorderLayout 的面板 −
JPanel panelGrid = new JPanel(new GridLayout(10, 5, 10, 10)); panelGrid.add(new JCheckBox("Demo CheckBox1")); panelGrid.add(new JCheckBox("Demo CheckBox2")); panelGrid.add(btnAPanel); panelGrid.add(btnBPanel); panelGrid.add(btnCPanel); panelGrid.add(btnDPanel); JPanel panelBrdLayout = new JPanel(new BorderLayout()); panelBrdLayout.add(panelGrid, BorderLayout.NORTH);
以下展示了组合 GridLayout 和 BorderLayout 的示例 −
package my; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JPanel; public class SwingDemo { public static void main(String[] args) { JButton btnA = new JButton("Button1"); JButton btnB = new JButton("Button2"); JButton btnC = new JButton("Button3"); JButton btnD = new JButton("Button4"); btnA.setPreferredSize(new Dimension(150, 20)); btnB.setPreferredSize(new Dimension(150, 20)); btnC.setPreferredSize(new Dimension(150, 20)); btnD.setPreferredSize(new Dimension(150, 20)); JPanel btnAPanel = new JPanel(); JPanel btnBPanel = new JPanel(); JPanel btnCPanel = new JPanel(); JPanel btnDPanel = new JPanel(); btnAPanel.add(btnA); btnBPanel.add(btnB); btnCPanel.add(btnC); btnDPanel.add(btnD); JPanel panelGrid = new JPanel(new GridLayout(10, 5, 10, 10)); panelGrid.add(new JCheckBox("Demo CheckBox1")); panelGrid.add(new JCheckBox("Demo CheckBox2")); panelGrid.add(btnAPanel); panelGrid.add(btnBPanel); panelGrid.add(btnCPanel); panelGrid.add(btnDPanel); JPanel panelBrdLayout = new JPanel(new BorderLayout()); panelBrdLayout.add(panelGrid, BorderLayout.NORTH); panelBrdLayout.setPreferredSize(new Dimension(550, 300)); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(panelBrdLayout); frame.setSize(550, 300); frame.setVisible(true); } }
输出
广告