gpt4 book ai didi

java - Java 中的元素间距

转载 作者:行者123 更新时间:2023-12-01 11:20:17 24 4
gpt4 key购买 nike

当我运行 java 代码时,我在 GUI 上的字段和按钮间距方面遇到问题。我正在寻找一些帮助和解释,或者一个制作精良的网站的方向,解释如何轻松地分隔元素。下面是我的很长的代码,希望它能很好地显示,这样我就不会疲劳你的眼睛。

我试图在第一个文本框之后和第二个文本框之后获得间距,以便按钮可以位于相同的 x 位置,但只是在 y 轴上向下移动。我尝试添加新的插图并按下按钮,但它们被向下推到右侧,并且没有任何东西看起来再居中。

public class theater_proceeds extends JFrame    
{

//winow dimentions

private final int wh = 300;
private final int ww = 500;

//20% gross keep
private final double percent_rev = 0.20;

//Labels
private JLabel adult_price;
private JLabel adult_num;
private JLabel child_price;
private JLabel child_num;

//Fields
private JTextField a_price;
private JTextField a_num;
private JTextField c_price;
private JTextField c_num;

//Buttons
private JButton calculate;
private JButton exit;

//panel
private JPanel theater;

private GridBagConstraints gbc;

theater_proceeds()
{
//set the size
setSize(ww, wh);

//set the title
setTitle("Theater Proceeds Calculator");

//set exit default action
setDefaultCloseOperation(EXIT_ON_CLOSE);

//constraints
gbc = new GridBagConstraints();

//set the insets
gbc.insets = new Insets(0,0,0,60);


//create the panel
theater = new JPanel();

//set the layout manager
theater.setLayout(new GridBagLayout());

//initialize each pair of field and label and add them to the panel
//starting with first 2
adult_num = new JLabel("Number of Adults");
gbc.gridx = 0;
gbc.gridy = 0;
theater.add(adult_num, gbc);

a_num = new JTextField(10);
gbc.gridx = 0;
gbc.gridy = 1;
theater.add(a_num, gbc);

//second pair
adult_price = new JLabel("Price per Adult");
gbc.gridx = 1;
gbc.gridy = 0;
theater.add(adult_price,gbc);

a_price = new JTextField(10);
gbc.gridx = 1;
gbc.gridy = 1;
theater.add(a_price, gbc);


//third pair
child_num = new JLabel("Number of Children");
gbc.gridx = 0;
gbc.gridy = 2;
theater.add(child_num, gbc);


c_num = new JTextField(10);
gbc.gridx = 0;
gbc.gridy = 3;
theater.add(c_num, gbc);


//forth pair
child_price = new JLabel("Price per Child");
gbc.gridx = 1;
gbc.gridy = 2;
theater.add(child_price, gbc);


c_price = new JTextField(10);
gbc.gridx = 1;
gbc.gridy = 3;
theater.add(c_price, gbc);


calculate = new JButton("Calculate");
gbc.gridx = 0;
gbc.gridy = 7;
theater.add(calculate, gbc);

exit = new JButton("Exit");
gbc.gridx = 1;
gbc.gridy = 7;
theater.add(exit, gbc);

add(theater);

setVisible(true);

}

}

最佳答案

当您为按钮设置 Inset 时,请确保将您在开始时为每个组件设置的 60 保持正确。

添加按钮之前:gbc.insets = new Insets(50, 0, 0, 60);

将 50 替换为您想要的任何插图。

关于java - Java 中的元素间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31320572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com