如何用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);
   }
}

输出


更新于:30-Jul-2019

1K + 次浏览

开启你的职业生涯

完成学习即可获得认证

开始学习
广告