简体   繁体   中英

Link array of buttons and textfields in Java

I have a list of textfields, and a list of buttons. These are laid out on a form with the buttons next to the textfields. Let's say there are 5 of each, they are 1 through 5. In reality, the number will be created at runtime.

When the user clicks a button, a new form is opened, which guides the user through creating a string. When they finish on that form, a text string is written in to the text field next to the button.

I'd like to create a relationship between each button and text field so that I know which text field to write in based on which button was clicked.

Is there a Java standard here? If not, any suggestions appreciated.

Thanks

Well either wrap or extend JButton to add a JTextfield field. Upon creation of the Button, pass the associated textfield to it and then you can pass along that info.

I'd like to create a relationship between each button and text field

Create an ActionListener class that takes the text field as a parameter. Something like:

JTextField textField = new JTextField();
JButton button = new JButton(...);
button.addActionListener( new FormPopupListener( textField ) );

Then you can save the text field as a variable in your listener class and when the dialog closes you can update the text field.

You have two lists, why not use the index in the list? Button at index 0 relates to textfield at index 0 and so on. Another alternative would be wrap them in an object that contains the button and the textfield and run a single list.

I would use the second route but there is nothing wrong with just using the index of the list.

Basically you can subclass JButton with additional attribute index. You can populate the index when creating the buttons and it will refer to index of text field in array of text fields. If you want you can even have a name given to each text field and add them to a map and then give the name to button to lookup the required text field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM