如何用GridLayout在Java中创建垂直按钮列?
要创建垂直按钮列,我们首先创建一些按钮并将布局也设置为 −
JPanel btnPanel = new JPanel(new GridLayout(10, 1, 10, 5)); btnPanel.add(new JButton("First Button")); btnPanel.add(new JButton("Second Button")); btnPanel.add(new JButton("Third Button")); btnPanel.add(new JButton("Fourth Button")); btnPanel.add(new JButton("Fifth Button")); btnPanel.add(new JButton("Sixth Button")); btnPanel.add(new JButton("Seventh Button")); btnPanel.add(new JButton("Eighth Button"));
在上面,我们已经设置了GridLayout,以便使用垂直和水平间距创建行和列。
以下是使用GridLayout创建垂直按钮列的一个示例 −
示例
package my; import java.awt.BorderLayout; import java.awt.GridBagLayout; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; public class SwingDemo { public static void main(String[] args) { JPanel panel = new JPanel(new BorderLayout()); panel.setBorder(new EmptyBorder(2, 3, 2, 3)); JPanel layout = new JPanel(new GridBagLayout()); layout.setBorder(new EmptyBorder(5, 5, 5, 5)); JPanel btnPanel = new JPanel(new GridLayout(10, 1, 10, 5)); btnPanel.add(new JButton("First Button")); btnPanel.add(new JButton("Second Button")); btnPanel.add(new JButton("Third Button")); btnPanel.add(new JButton("Fourth Button")); btnPanel.add(new JButton("Fifth Button")); btnPanel.add(new JButton("Sixth Button")); btnPanel.add(new JButton("Seventh Button")); btnPanel.add(new JButton("Eighth Button")); layout.add(btnPanel); panel.add(layout, BorderLayout.CENTER); JFrame frame = new JFrame("Demo"); frame.add(panel); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setLocationByPlatform(true); frame.setSize(500, 400); frame.setVisible(true); } }
输出
广告