Java: change a variable depending on dynamically generated text field name? - java

I have an ArrayList of TrainingClass objects with a variable "priority".
I am making a settings frame, where for each element currently in the ArrayList I make a TextField where the user sets priority.
This is how it is generated
for (TrainingClass tclass : mTrainingClasses) {
//Loop the ArrayList
JTextField txtPriority = new JTextField(3);
txtPriority.setBounds(10,10,100,20);
txtPriority.setText("" + tclass.getPriority());
getContentPane().add(txtPriority);
}
Now I would add a change listener, but...
Once I know which field has been changed, how can I access the proper element of the ArrayList mTrainingClasses?
In php, for example, I would simply make something like:
$mTrainingClasses->$changed_field->setPriority($new_value);
But, as far as I understand, I can’t do this in Java. So, how should I proceed?
Do I need to manually set the field name and listener for each element? I’m sure there is some other solution, but I have no idea at this point.
(I know I could use an ArrayList for the fields as well, such as
txtPriority.add(new JTextField(3));
But in this case, how do I know which index corresponds to the field that has been changed?
)

Have a list of Text Fields
List<JTextField> textFields = new ArrayList<JTextField>();
Change the loop like the following where you add all text fields to above list
for (TrainingClass tclass : mTrainingClasses) {
//Loop the ArrayList
JTextField txtPriority = new JTextField(3);
txtPriority.setBounds(10,10,100,20);
txtPriority.setText("" + tclass.getPriority());
getContentPane().add(txtPriority);
textFields.add(txtPriority);
}
In your listener you can do the following
mTrainingClasses.get(textFields.indexOf((JtextField) event.getSource()));
The above will return the TrainingClass which got changed.

There are several options:
Pass the TrainingClass element to the listener which you attach to the textfield. This will require to attach the listener in your for loop where you have access to both the TrainingClass and JTextField variable
Use a Map as suggested by #Ted Hopp
Use a List as you already suggested. Trick is to store an index in the JTextField so that afterwards you know which JTextField corresponds to which element in the List. You can use JComponent#putClientProperty and JComponent#getClientProperty for this.
You can use those JComponent#putClientProperty and JComponent#getClientProperty methods to store the TrainingClass variable directly

In your loop, you can populate a Map<JTextField, TrainingClass>. Then you can use that to look up the element from the changed field.
Map<JTextField, TrainingClass> fieldMap = new HashMap<>();
for (TrainingClass tclass : mTrainingClasses) {
//Loop the ArrayList
JTextField txtPriority = new JTextField(3);
txtPriority.setBounds(10,10,100,20);
txtPriority.setText("" + tclass.getPriority());
getContentPane().add(txtPriority);
map.put(txtPriority, tclass);
}
Alternatively, you can subclass JTextField and declare a data field that you can then reference directly in event handling.

You need some kind of mapping between the JTextField and the TrainingClass. Either make text field a property of your class or make a map that maps the two.
Map<TrainingClass, JTextField> myMap= new HashMap<TrainingClass, JTextField>();
for (TrainingClass tclass : mTrainingClasses) {
//Loop the ArrayList
JTextField txtPriority = new JTextField(3);
txtPriority.setBounds(10,10,100,20);
txtPriority.setText("" + tclass.getPriority());
getContentPane().add(txtPriority);
// map the textField to the training class
myMap.put(txtPriority, tclass);
}
When the field changes inside the listener method, you'd simply call:
public void eventListenerMethod(InputEvent e) {
JTextField fieldThatGeneratedEvent= e.getSource();
TrainingClass tClass= myMap.get(fieldThatGeneratedEvent);
}

Related

Accessing text in the GWT TextBox from ChangeEvent

I'm dynamically generating a form based on data received from an RPC call into a FormFieldData object which has details about the field to be rendered such as, Field Name, expected length and type of input, if the field is a required field or not and valid input Regex in some cases etc.
I'd like to be able to perform validation on the field depending on above attributes.
Here's an example:
private void renderTextField(FormFieldData field){
FormGroup formGroup = new FormGroup();
FormLabel formLabel = new FormLabel();
if(field.isRequired()){
formLabel.setText(field.getName()+"*");
}else{
formLabel.setText(field.getName());
}
formGroup.add(formLabel);
TextBox textBox = new TextBox();
textBox.addChangeHandler(new ChangeHandler(){
#Overrride
public void onChange(ChangeEvent event){
//TODO - find a way to get the text entered in TextBox
// and perform validation on it
//and set the TextBox Style to "Validation-error"
}
});
formGroup.add(textBox);
form.add(formGroup);
}
There're similar methods to render dropdowns, Numeric fields, radio button fields etc. which would need similar validation.
The problem is I can't access the text from the TextBox inside the onChange method without declaring it final, which I can't do because I might be rendering multiple text fields. I don't know much about ChangeEvent and if there's a way to get the text from the that.
I'd really appreciate any pointers to a way to do this in real time as the data is entered into the form, other than having to iterate through the fields and their corresponding FormFieldData object when the form is submitted.
First off, you can make the variable final, no problem.
If you don't want to do that for whatever reason, you can get the TextBox from the event like this:
textBox.addValueChangeHandler(new ValueChangeHandler(){
#Overrride
public void onValueChange(ChangeEvent event){
TextBox box = (TextBox) event.getSource();
// Do whatever you need to here
}
});
You are probably also looking for ValueChangeHandler instead of ChangeHandler.

get access to each dynamically added jComponent

Before I already asked question and could get value from dynamically added jTextFields and jComboBoxes using this answer for my question.
Now in my subPanel I have 3 jComboBoxes and 4 jTextFields.
To get value of jComponent I am using this code:
Component[] children = jPanel1.getComponents();
// iterate over all subPanels...
for (Component sp : children) {
if (sp instanceof subPanel) {
Component[] spChildren = ((subPanel)sp).getComponents();
// now iterate over all JTextFields...
for (Component spChild : spChildren) {
if (spChild instanceof JTextField) {
String text = ((JTextField)spChild).getText();
System.out.println(text);
}
}
}
}
I would like to ask is it possible to access to each jComboBoxes and jTextFields separately, i.e. can I manipulate each jComponent and set them different values? How can I achieve this?
Thank you in advance.
I would like to ask is it possible to access to each jComboBoxes and jTextFields separately, i.e. can I manipulate each jComponent and set them different values? How can I achieve this?
Rather than traversing the Component hierarchy (which is fragile to Layout changes), you can keep references to your Components. The following example is a class that contains instance variables for the Child components:
public class ComponentWrapper extends JComponent{
private JComboBox combo;
private JTextArea textArea;
public ComponentWrapper(){
combo = new JComboBox();
textArea = new JTextArea();
add(combo);
add(textArea);
}
public Text getTextArea(){
return textArea;
}
public JComboBox getComboBox(){
return comboBox;
}
}
The above class extends JComponent, adds the components within the constructor, and can be added to another Container elsewhere. Note the above class is just an example for how to do this, and may need to be further adapted depending upon your requirements. Usage:
ComponentWrapper wrapper = new ComponentWrapper ();
add(wrapper);
revalidate();//if adding 'dynamically'
//later, when you want to get the text
String text = wrapper.getTextArea().getText();
Since both of those classes (JComboBox and JTextField) extend JComponent you can make an ArrayList and add them to it. i.e.
ArrayList<JComponent> components = new ArrayList<JComponent>();
JComboBox pie = new JComboBox();
components.add(pie)
//pie is now stored in components as a JComponent
When you need to reference pie you can call:
JComboBox pie = (JComboBox) components.get(0);
This can be done with any JComponent and to reference it you just simply cast it on it's way out. This method, however, can lead to some confusion. So you should either remember the order you add them, or add them in a very specific way (i.e TextFields first, then ComboBoxes).

Want to convert java struts 2 static code into dynamic

I have been assign to one struts2 project and its one of jsp contains more than 100 radio buttons and they have handled in statically not dynamically. As jsp contains 100 radio buttons so I am able to see the below list of radio buttons catches in actions with their getter and setter
List selectRadioList001
List selectRadioList002
List selectRadioList003
List selectRadioList004
etc
List selectRadioList100
I want to add these radio button in a list dynamically iterating through 1 to 100 something like below but when I try to access the variable like "searchBoxSelectRadioList"+i then it is pretending like a simple string. I want it to be like a List as shown above.
public class SelectRadioListPOJO {
private List<TicketDesignUtil> selectRadioList;
public List<TicketDesignUtil> getSelectRadioList() {
return selectRadioList;
}
public void setSelectRadioList(List<TicketDesignUtil> selectRadioList) {
this.selectRadioList = selectRadioList;
}
}
Action code:
List<SelectRadioListPOJO> selectRadioListPOJOList = new ArrayList<>();
SelectRadioListPOJO selectRadioListPOJO;
for (int i = 1; i <= 100; i++) {
selectRadioListPOJO = new SelectRadioListPOJO();
selectRadioListPOJO.setSelectRadioList("searchBoxSelectRadioList"+i);// ERROR
selectRadioListPOJOList.add(selectRadioListPOJO);
}
It's not clear what you're asking.
You can't pass arbitrary values to methods; setSelectRadioList takes a list of TicketDesignUtil.
If your action doesn't have getters and setters for all of those radio buttons then you should resort to accessing the request parameters directly, for example, via ParameterAware.
You would then access the radio button parameters by name from the injected parameter map.
Notes:
It's not "pretending" to be a simple string, it is a simple string, because... well, because it is.
Your for loop is wrong; I corrected it in your question to avoid others commenting on it. The POJO should be added to the POJOList inside the loop.
Naming is funky; just call it selectRadioListPojos. Better yet, name it something domain-specific: variables should be semantically meaningful, not just a description of the class(es) involved.
These shouldn't be static in the first place, but a map or array.

Java JPanel combobox that holds object types

So far from what I have seen combo boxes can only hold string and int types of values but this is what I am trying to achieve.
Class Node
{
//code here
}
Node a = new Node();
Node b = new Node();
//I am wondering if I can somehow achieve something like
Node item = comboBox.getSelectedItem();
So I want the combo box to hold items of type Node. The combo box will allow for a and b values but when selected they will register as Node objects. I am not sure that is even possible but just wondering. Thanks for input :)
Yes, JComboBox is able to contain any type of Object.
As of 1.7, you can also use the template definition to define the type contained.

Can I use the method if the object is held by an multidimensional array?

I saw some post quite similar but did not hit spot on.
I was thinking something like this:
Object[][] test = {
{"Name", new JTextField()},
{"Gender", new JComboBox()}
}
I tried something like this but i cannot use the method of the JTextField or the JComboBox. How do I instantiate this depending on there 1-index? Is this possible?
If you know for sure what it is, you can cast it when you get it out, like this
JComboBox box = (JComboBox)(test[1][1]);
box.whatever();
However, instead of using an Object[][], why not just make a class?
class UIWidgets {
JTextField name;
JComboBox gender;
}
You need to cast first before you can access methods specific to the type, since Java sees them all as instances of Object:
((JTextField)test[0][1]).CallMethodHere();
Or alternately:
JTextField tf = (JTextField)test[0][1];
// do something with tf
Try this:
((JTextField) test[0][1]).setText("someText");

Categories

Resources