【发布时间】:2020-06-02 04:23:29
【问题描述】:
我对 Java 还是很陌生,我想自己动手做一个 GUI,但我似乎无法让它按照我想要的方式工作。
我写了一些代码,认为如果我按下 GUI 上的“添加”按钮,那么一个新的 JTextField 将出现在所有其他文本字段所在的下方,但这不会发生。只有一个新的 JTextField 确实出现了,但它出现在我的添加按钮旁边,而不是在我拥有的所有其他文本字段的下方,如果我再次按下它,什么也不会发生。我尝试使用其他变量,但它似乎无法正常工作。我觉得我的 ActionListener 出了点问题,但我不知道是什么。
public class TheGUI extends JFrame{
List<JTextField> listOfTextFields = new ArrayList<JTextField>();
private JTextField desc1;
private JTextField instruct;
private JTextField desc2;
private JButton submit;
private JButton addNew;
public TheGUI() { //My GUI with the default fields & buttons that should be on there.
super("Chili");
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
instruct = new JTextField("Choose your words");
instruct.setEditable(false);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 0;
add(instruct, c);
addNew = new JButton("Add");
c.weightx = 0.0;
c.gridx = 1;
c.gridy = 0;
add(addNew, c);
submit = new JButton("Submit!");
c.weightx = 0.5;
c.gridwidth = 2;
c.gridx = 0;
c.gridy = GridBagConstraints.PAGE_END;
add(submit, c);
desc1 = new JTextField(10);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridwidth = 2;
c.gridx = 0;
c.gridy = 1;
add(desc1, c);
desc2 = new JTextField(10);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridwidth = 2;
c.gridx = 0;
c.gridy = 2;
add(desc2, c);
addNew.addActionListener(new Adder());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setVisible(true);
}
private class Adder implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
int i = 0;
listOfTextFields.add(new JTextField());
GridBagConstraints textFieldConstraints = new GridBagConstraints();
//Give it a max of 9 text fields that can be created.
while(i < 10) {
textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
textFieldConstraints.weightx = 0.5;
textFieldConstraints.gridx = 0;
textFieldConstraints.gridwidth = 2;
textFieldConstraints.gridy = 3 + i;
i++;
}
add(listOfTextFields.get(i), textFieldConstraints);
revalidate();
repaint();
}
}
}
【问题讨论】:
-
未验证,但
int i = 0;后跟while (i > 10) {}看起来很可疑。由于您将i初始化为零,因此 while 循环将永远不会执行(i永远不会大于 10) -
谢谢托马斯!我应该注意到这一点。我已经进行了更改,但在那之后,当我尝试按下添加按钮“IndexOutofBoundsException:索引 10 超出长度 1 的范围时出现错误。看起来我可以在正确的空间中添加一个框,但只有在按下添加之后10 次。我需要做更多的研究。
标签: java swing user-interface jframe jtextfield