Search code examples
javaswinghashmapjtextfield

Trying to setText for the textfields


I am currently working a on a team project for school and I am having difficulty setText() on the textFields within fieldMap. I am able to get values from them using fieldMap.get(fieldTitle.values()[i]) but i cant figure out how i would go about setting text to the text fields due to my lack of understanding in regards to HashMaps and gbcs.

class InstructorEditorPanel extends JPanel {
enum FieldTitle {
  B_NUMBER("B Number"), FIRST_NAME("First Name"), LAST_NAME("Last Name");
  private String title;

  private FieldTitle(String title) {
     this.title = title;
  }

  public String getTitle() {
     return title;
  }
};

private static final Insets WEST_INSETS = new Insets(5, 0, 5, 5);
private static final Insets EAST_INSETS = new Insets(5, 5, 5, 0);
private Map<FieldTitle, JTextField> fieldMap = new HashMap<FieldTitle, JTextField>();

public InstructorEditorPanel() {
  setLayout(new GridBagLayout());
  setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Instructor Editor"),
        BorderFactory.createEmptyBorder(5, 5, 5, 5)));
  GridBagConstraints gbc;
  for (int i = 0; i < FieldTitle.values().length; i++) {
     FieldTitle fieldTitle = FieldTitle.values()[i];
     gbc = createGbc(0, i);
     add(new JLabel(fieldTitle.getTitle() + ":", JLabel.LEFT), gbc);
     gbc = createGbc(1, i);
     JTextField textField = new JTextField(10);
     add(textField, gbc);

     fieldMap.put(fieldTitle, textField);
  }
}

private GridBagConstraints createGbc(int x, int y) {
  GridBagConstraints gbc = new GridBagConstraints();
  gbc.gridx = x;
  gbc.gridy = y;
  gbc.gridwidth = 1;
  gbc.gridheight = 1;

  gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
  gbc.fill = (x == 0) ? GridBagConstraints.BOTH
        : GridBagConstraints.HORIZONTAL;

  gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
  gbc.weightx = (x == 0) ? 0.1 : 1.0;
  gbc.weighty = 1.0;
  return gbc;
}

public String getFieldText(FieldTitle fieldTitle) {
  return fieldMap.get(fieldTitle).getText();
}

Solution

  • Just guessing for symmetry reasons:

    public void setFieldText (FieldTitle fieldTitle, String toSet) {
       fieldMap.get (fieldTitle).setText (toSet);
    }
    

    You would put the method into your InstructorEditorPanel, where the other method is. To call it, you have to access the inner enum of that class:

    public class TestFrame extends JFrame {
    
        public TestFrame () {
            super ("testframe");
            setSize (400, 400);
            setVisible (true);
        }
    
        public static void main (String [] args)
        {
            InstructorEditorPanel iep = new InstructorEditorPanel ();
            TestFrame tf = new TestFrame ();
            tf.add (iep);
            iep.setFieldText (InstructorEditorPanel.FieldTitle.FIRST_NAME, "Donald");
        }
    }
    

    Tested, worked.