[英]Java GUI Creating Components
I hope it is correct term-wise to say that components in a GUI is like JButton, JPanel, JTextField, all that good stuff. 我希望用正确的术语说GUI中的组件就像JButton,JPanel,JTextField之类的好东西。
I want to create a text field that takes in an integer. 我想创建一个接受整数的文本字段。 Then a submit button can be pressed and based on the integer that was inputted, create that many textfields in a popup window or whatever. 然后可以按下提交按钮,并根据输入的整数在弹出窗口中创建这么多的文本字段。
I have no clue, could someone get me started in the right direction? 我不知道,有人可以引导我朝正确的方向发展吗?
The trouble I'm having is that I have no clue how to create a for loop to create the GUI components. 我遇到的麻烦是我不知道如何创建for循环来创建GUI组件。 I mean if I have a for loop and do something like: 我的意思是,如果我有一个for循环并执行以下操作:
print("JTextField num1 = new JTextField()");
then in a for loop it will only create 1 text field when I want many. 然后在for循环中,当我需要很多时,它只会创建1个文本字段。 How do I generically create variables of JTextFields? 我一般如何创建JTextFields的变量?
Thanks for your help... 谢谢你的帮助...
Use an appropriate LayoutManager (eg GridLayout) to create and add your textfields. 使用适当的LayoutManager(例如GridLayout)来创建和添加文本字段。
for (i = 0; i < numberOfTextFields; i++) {
JTextField textField = new JTextField();
container.add(textField);
/* also store textField somewhere else. */
}
Try something like this: 尝试这样的事情:
List<JTextField> nums = new ArrayList<JTextField>();
JTextField tempField;
for (int i = 0; i < 10; i++) {
tempField = new JTextField();
jPanel1.add(tempField); // Assuming all JTextFields are on a JPanel
nums.add(tempField);
}
Don't forget to set a proper layout manager for the container. 不要忘记为容器设置适当的布局管理器。 (jPanel1 in this case) (在这种情况下为jPanel1)
I would create a List to store the text fields, and then you can get them back by index. 我将创建一个列表来存储文本字段,然后可以通过索引将它们取回。 Then you can have as many fields as you need. 然后,您可以根据需要拥有任意多个字段。
List fields = new ArrayList();
// Create as many elements as you need
for (int i = 0; i < numberOfElements; i++){
JTextField field = new JTextField();
// Add the fields to some panel so they are shown in the screen.
// I assume that the component is called parent panel
parentPanel.add(field);
// Store the component in the list so you can retrieve it later
fields.add(field);
}
// ...
// When you want to retrieve a particular one:
JTextField field = (JTextField)fields.get( indexToRetrieve );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.