NekoLLX
NekoLLX

Reputation: 219

Listening to JComboBoxes and JTextFields to modify activate Class Mutators

I have a little form in a Swing GUI that once the object is change I want to call some custom mutators to my class but I just can't figure out how to fetch that info and call my mutators. Here is the relevant code, I know this is relatively simple but I just cant figure it out.

For reference namebox's content when changed or lost focus should call .setName(String x) genderbox's content when changed or lost focus should call .setGender(Boolean x) racebox's content when changed or lost focus should call .setRace(int a) where a is the index number of the array used to build the form classbox's functions identically to Racebox

update: Found some of what i need, i needed a label for the items and then use getsource, and getActioCommand but while that should work for Most aspects i still have a small problem the Genderbox stores a string but i want it to have a int value and only display a string is there a way with a j combo box to set a value and a display option text seperatly?

    JTextField namebox = new JTextField(nala.getName());
    namebox.addFocusListener(new FocusListener() {

    //Create the combo box for gender.
    String[] gender = { "male", "female" };
    JComboBox genderBox = new JComboBox(gender);
    if (nala.getGender()){genderBox.setSelectedIndex(1);}else{genderBox.setSelectedIndex(0);}
    genderBox.addActionListener(this);
    genderBox.setActionCommand("GenderBox");

    //Create the combo box for race.
    String[] cRace = new String[75];
    for (int i=0; i<75; i++){cRace[i] = nala.getRaceName(i);}
    JComboBox raceBox = new JComboBox(cRace);
    raceBox.setSelectedIndex((int)nala.getRace());
    raceBox.addActionListener(this);

    //Create the combo box for class.
    String[] cClass = new String[50];
    for (int i=0; i<50; i++){cClass[i] = nala.getClassName(i);}
    JComboBox classBox = new JComboBox(cClass);
    classBox.setSelectedIndex((int)nala.getRace());
    classBox.addActionListener(this);

    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("GenderBox")){
            JComboBox cb = (JComboBox)e.getSource();
            System.out.println(cb.getSelectedItem().toString());
        }
         JLabel label = new JLabel(setStatsInfo());
    }//actionPerformed(ActionEvent e)

Upvotes: 0

Views: 575

Answers (1)

Amarnath
Amarnath

Reputation: 8865

When there is selection change in the JComboBox use ItemListener.

Example:

JComboBox combo = new JComboBox();
combo.addItemListener(new ItemListener() {
  @Override
  public void itemStateChanged(ItemEvent arg0) {
  // TODO: Action.
  }
});

Your code shows only adding of the listeners which does give any clue to your problem. Please post the ActionEvent method code to show us the problem.

Upvotes: 2

Related Questions