如何在 Java 中创建一个具有行和列的 GridLayout?
在创建 GridLayout 时,你需要将行和列设为括号。GridLayout 用于创建具有指定行数和列数的布局。
假设我们有一个 GridLayout,有 1 行和 4 列 −
GridLayout layout = new GridLayout(1,4);
以下是一个用行和列创建 GridLayout 的示例 −
示例
package my; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.WindowConstants; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame("Sections"); JPanel panel = new JPanel(); panel.setBackground(Color.orange); GridLayout layout = new GridLayout(1,4); layout.setHgap(40); panel.setLayout(layout); panel.add(new JButton("Overview")); panel.add(new JButton("Samples")); panel.add(new JButton("Tutorials")); panel.add(new JButton("Support")); frame.add(panel); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setSize(500, 300); frame.setVisible(true); } }
输出
广告