在运行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);
}
}
答案 0 :(得分:1)
当您为按钮设置插入时,请确保将60设置为您在开头为每个组件设置的权利。
在添加按钮之前:gbc.insets = new Insets(50, 0, 0, 60);
用你想要的任何内容替换50.