在 Java 中设置组件并将其放在先前添加的组件旁边,使用 GridBagLayout


我们首先设置一个组件 –

GridBagConstraints constraints = new GridBagConstraints();
constraints.gridy = 0;
panel.add(new JButton("First row"), constraints);

现在,我们将其放在先前添加的组件旁边 –

constraints.gridx = GridBagConstraints.RELATIVE;
constraints.gridy = 1;
panel.add(new JButton("2nd row 1st column"), constraints);
panel.add(new JButton("2nd row 2nd column"), constraints);

示例

package my;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JPanel panel = new JPanel();
      panel.setLayout(new GridBagLayout());
      GridBagConstraints constraints = new GridBagConstraints();
      constraints.gridy = 0;
      panel.add(new JButton("First row"), constraints);
      constraints.gridx = GridBagConstraints.RELATIVE;
      constraints.gridy = 1;
      panel.add(new JButton("2nd row 1st column"), constraints);
      panel.add(new JButton("2nd row 2nd column"), constraints);
      frame.add(panel);
      frame.setSize(550, 300);
      frame.setVisible(true);
   }
}

输出


更新于:30-Jul-2019

103 浏览

启动你的 事业

完成课程获得认证

立即开始
广告