Java GUI Creating Components
-
21-08-2019 - |
Question
I hope it is correct term-wise to say that components in a GUI is like JButton, JPanel, JTextField, all that good stuff.
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. I mean if I have a for loop and do something like:
print("JTextField num1 = new JTextField()");
then in a for loop it will only create 1 text field when I want many. How do I generically create variables of JTextFields?
Thanks for your help...
Solution
Use an appropriate LayoutManager (e.g. GridLayout) to create and add your textfields.
for (i = 0; i < numberOfTextFields; i++) {
JTextField textField = new JTextField();
container.add(textField);
/* also store textField somewhere else. */
}
OTHER TIPS
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)
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 );