如何使用 Java 中的相对 X 位置添加组件
若要添加具有相对 X 位置的组件,请使用 GridBagConstraints.RELATIVE 常量。将此值设置为 gridx 字段 −
GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = GridBagConstraints.RELATIVE;
以下是在 Java 中添加带有相对 X 位置的组件的示例 −
示例
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); } }
输出
广告