Using an editable JComboBox

I am trying to permit the player to choose from predefined factions, but allow him to rename his own if it suits him. For this, I’m trying to use an editable JComboBox. However, the box refuses to be edited. That is, it comes up on the screen as it should, and I can select my hardcoded strings; but when I click on it to try editing, it doesn’t seem to gain the keyboard focus. Do I need to do anything special, other than call setEditable(true), to make it do so? Here’s my code so far :


   constructor {
      (...)
      familyChoice = Family.getFamilyChoice();
      familyChoice.setBounds(250, 50, 175, 30);
      familyChoice.setVisible(false);
      familyChoice.setEditable(true);
      getLayeredPane().add(familyChoice, JLayeredPane.PALETTE_LAYER);
   }

  // In class Family :
  public static JComboBox getFamilyChoice () {

      String[] temp = new String[allFamilies.length];
      for (int i = 0; i < temp.length; i++)
         temp[i] = allFamilies[i].name;

      return new JComboBox(temp);
   }

I call setVisible(true) in actionPerformed, and it pops up just as it should. I am not overwriting any of the painting methods. Suggestions?

You are calling setEditable correctly, this seems to be spcifically a focus issue. I noticed you are using LayeredPane stuff… could that be affecting focus? Can you use the TAB key to move focus to the control? I.e. can you use any keyboard actions to select an item in that combo-box?

It doesn’t seem to be the layeredPane, I get the same result just using the contentPane. Nix on the TAB, though I didn’t see what would happen if I wrote a keyboard listener to move the focus around. I did try calling requestFocus in actionPerformed (when a button was clicked), but no dice.

However, I’ve decided that a TextField, with buttons on either side to traverse the names, is a cooler solution anyway. So it’s not a huge priority. Would be nice to know what’s going on, though. Let’s hope I can give focus to a TextField. :slight_smile:


import javax.swing.*;

public class TestApp extends JFrame {
      public TestApp() {
            Container c = getContentPane();
            JComboBox jc = new JComboBox();
            c.add(jc, BorderLayout.NORTH);
            jc.setEditable(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
            show();
      }
      public static void main(String args[]) {
            TestApp t = new TestApp();
      }
}

This worked for me.