Search code examples
javaswingjtextfield

How can I create a generic setter for JTextField?


I am able to expose a private JTextField by doing this:

public void setTextField(String value) {
    someTF.setText(value);
}

It would be a lot of work if I have a lot of JTextFields. I tried doing this but failed. No error it's just not setting the right value on specified JTextField.

public class SomeView {

    private JTextField someTF = new JTextField(10);
    ...

    public void initComponents() {
        ...
    }

    public void setTextField(JTextField jTF, String value) {
        jTF.setText(value);
    }
}

public class SomeViewTable implements ...{

    public void mousePressed(MouseEvent e) {
        if (e.getSource() == someButton) {
            JTextField someTF = new JTextField(10);
            String value = "Some Value";
            SomeView sv = new SomeView();
            sv.initComponents();

            sv.setTextField(someTF, value);
        }
    }
 }

Im expecting this to happen in SomeView class when I called method sameTextField

someTF.setText("Some Value");

Is this possible, what rules in java am I breaking here?


Solution

  • In your listener, you are creating a local variable:

    JTextField someTF = new JTextField(10);
    ...
    sv.setTextField(someTF, value);
    

    But what you want is to set the text field of SomeView. So remove the first line, and replace the second with:

    sv.setTextField(sv.someTF, value);
    

    Now, to answer the more global question of how to expose many private JTextFields through one method, one possibility could be to assign a string ID to each of them, and store them all in a HashMap:

    Map<String,JTextField> map = new HashMap<String,JTextField>();
    map.put("field 1", textField1);
    ...
    map.put("field n", textFieldn);
    
    public void setTextField(String id, String value) {
        map.get(id).setText(value);
    }
    

    Or you could simply generate getters automatically for all your fields (most IDE do that painlessly)...