2011-11-30 16 views
22

Desidero impostare l'indice selezionato in un JComboBox in base al valore e non all'indice. Come farlo? EsempioCome impostare l'indice selezionato JComboBox in base al valore

public class ComboItem { 

    private String value; 
    private String label; 

    public ComboItem(String value, String label) { 
     this.value = value; 
     this.label = label; 
    } 

    public String getValue() { 
     return this.value; 
    } 

    public String getLabel() { 
     return this.label; 
    } 

    @Override 
    public String toString() { 
     return label; 
    } 
} 

JComboBox test = new JComboBox(); 
test.addItem(new ComboItem(0, "orange")); 
test.addItem(new ComboItem(1, "pear")); 
test.addItem(new ComboItem(2, "apple")); 
test.addItem(new ComboItem(3, "banana")); 
test.setSelectedItem("banana"); 

Ok, ho modificato la mia domanda un po '. Ho dimenticato di avere un oggetto personalizzato all'interno del mio JComboBox che lo rende un po 'più difficile. non posso fare setSelectedItem come ho un ComboItem all'interno di ogni articolo. Quindi, come faccio a fare questo?

+1

non riguardano gli articoli uso wrapper.Implementa invece un ListCellRenderer personalizzato che fa la mappatura del componente alla sua rappresentazione di stringa – kleopatra

risposta

36

setSelectedItem("banana"). Avresti potuto trovarlo da solo leggendo the javadoc.

Modifica: da quando hai cambiato la domanda, cambierò la mia risposta.

Se si desidera selezionare la voce avere l'etichetta "banana", allora si hanno due soluzioni:

  1. scorrere gli elementi per trovare l'uno (o l'indice del uno) che ha la data etichetta, e quindi chiamare setSelectedItem(theFoundItem) (o setSelectedIndex(theFoundIndex))
  2. Override equals e hashCode in ComboItem modo che due ComboItem istanze aventi lo stesso nome sono uguali, e semplicemente utilizzare setSelectedItem(new ComboItem(anyNumber, "banana"));
+0

Mi dispiace che mi sia sfuggita quella ovvia funzione, ma ho aggiornato la mia domanda in quanto ho dimenticato che non ho elementi "normali" nella mia combobox –

+3

La seconda soluzione è molto utile, grazie. –

5

Perché non prendere una raccolta, probabilmente una mappa come una HashMap e usarla come nucleo della propria classe di modello box combinata che implementa l'interfaccia ComboBoxModel? Quindi è possibile accedere facilmente agli elementi della casella combinata tramite le stringhe chiave anziché inte.

Per esempio ...

import java.util.HashMap; 
import java.util.Map; 

import javax.swing.ComboBoxModel; 
import javax.swing.event.ListDataListener; 

public class MyComboModel<K, V> implements ComboBoxModel { 
    private Map<K, V> nucleus = new HashMap<K, V>(); 

    // ... any constructors that you want would go here 

    public void put(K key, V value) { 
     nucleus.put(key, value); 
    } 

    public V get(K key) { 
     return nucleus.get(key); 
    } 

    @Override 
    public void addListDataListener(ListDataListener arg0) { 
     // TODO Auto-generated method stub 

    } 

    // ... plus all the other methods required by the interface 
} 
4

ad esempio

enter image description here

import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JComboBox; 
import javax.swing.JFrame; 
import javax.swing.JOptionPane; 
import javax.swing.SwingUtilities; 

public class ComboboxExample { 

    private JFrame frame = new JFrame("Test"); 
    private JComboBox comboBox = new JComboBox(); 

    public ComboboxExample() { 
     createGui(); 
    } 

    private void createGui() { 
     comboBox.addItem("One"); 
     comboBox.addItem("Two"); 
     comboBox.addItem("Three"); 
     JButton button = new JButton("Show Selected"); 
     button.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       JOptionPane.showMessageDialog(frame, "Selected item: " + comboBox.getSelectedItem()); 
       javax.swing.SwingUtilities.invokeLater(new Runnable() { 

        @Override 
        public void run() { 
         comboBox.requestFocus(); 
         comboBox.requestFocusInWindow(); 
        } 
       }); 
      } 
     }); 
     JButton button1 = new JButton("Append Items"); 
     button1.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       appendCbItem(); 
      } 
     }); 
     JButton button2 = new JButton("Reduce Items"); 
     button2.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       reduceCbItem(); 
      } 
     }); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setLayout(new GridLayout(4, 1)); 
     frame.add(comboBox); 
     frame.add(button); 
     frame.add(button1); 
     frame.add(button2); 
     frame.setLocation(200, 200); 
     frame.pack(); 
     frame.setVisible(true); 
     selectFirstItem(); 
    } 

    public void appendCbItem() { 
     javax.swing.SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       comboBox.addItem("Four"); 
       comboBox.addItem("Five"); 
       comboBox.addItem("Six"); 
       comboBox.setSelectedItem("Six"); 
       requestCbFocus(); 
      } 
     }); 
    } 

    public void reduceCbItem() { 
     javax.swing.SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       comboBox.removeItem("Four"); 
       comboBox.removeItem("Five"); 
       comboBox.removeItem("Six"); 
       selectFirstItem(); 
      } 
     }); 
    } 

    public void selectFirstItem() { 
     javax.swing.SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       comboBox.setSelectedIndex(0); 
       requestCbFocus(); 
      } 
     }); 
    } 

    public void requestCbFocus() { 
     javax.swing.SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       comboBox.requestFocus(); 
       comboBox.requestFocusInWindow(); 
      } 
     }); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       ComboboxExample comboboxExample = new ComboboxExample(); 
      } 
     }); 
    } 
} 
11
public static void setSelectedValue(JComboBox comboBox, int value) 
    { 
     ComboItem item; 
     for (int i = 0; i < comboBox.getItemCount(); i++) 
     { 
      item = (ComboItem)comboBox.getItemAt(i); 
      if (item.getValue().equalsIgnoreCase(value)) 
      { 
       comboBox.setSelectedIndex(i); 
       break; 
      } 
     } 
    } 

Spero che questo aiuto :)

6

Si dovrebbe utilizzare il modello

comboBox.getModel().setSelectedItem(object); 
1

Basta chiamare comboBox.updateUI() dopo doin g comboBox.setSelectedItem o comboBox.setSelectedIndex o comboModel.setSelectedItem

+0

Potresti per favore elaborare più la tua risposta aggiungendo un po 'più di descrizione della soluzione che fornisci? – abarisone

2

Il modo giusto per impostare una voce selezionata quando la casella combinata è popolata da un po 'di costruzione della classe (come @milosz pubblicato):

combobox.getModel().setSelectedItem(new ClassName(parameter1, parameter2)); 

Nella tua Se il codice sarebbe:

test.getModel().setSelectedItem(new ComboItem(3, "banana")); 
1
public boolean preencherjTextCombox(){ 
     int x = Integer.parseInt(TableModelo.getModel().getValueAt(TableModelo.getSelectedRow(),0).toString()); 

     modeloobj = modelosDAO.pesquisar(x); 
     Combmarcass.getModel().setSelectedItem(modeloobj.getMarca()); 
     txtCodigo.setText(String.valueOf(modeloobj.getCodigo())); 
     txtDescricao.setText(String.valueOf(modeloobj.getDescricao())); 
     txtPotencia.setText(String.valueOf(modeloobj.getPotencia())); 

     return true; 
    } 
Problemi correlati