如何用 Java 添加具有相对 X 和 Y 坐标的组件?
要使用相对的 X 和 Y 坐标添加组件,你需要设置 gridx 和 gridy 这两个组件 −
GridBagConstraints constraints = new GridBagConstraints(); constraints.gridy = GridBagConstraints.RELATIVE; constraints.gridx = GridBagConstraints.RELATIVE;
以下是一个使用相对 X 和 Y 坐标添加组件的示例 −
示例
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.gridx = 1; constraints.gridy = GridBagConstraints.RELATIVE; panel.add(new JButton("1st row 1st column"), constraints); panel.add(new JButton("2nd row"), constraints); panel.add(new JButton("3rd row"), constraints); constraints.gridx = GridBagConstraints.RELATIVE; panel.add(new JButton("1st row 2nd column"), constraints); panel.add(new JButton("1st row 3rd column"), constraints); frame.add(panel); frame.setSize(550, 300); frame.setVisible(true); } }
输出
广告