dinamico JComboBoxes
-
02-10-2019 - |
Domanda
Ho seguenti dati (String):
Course1: A1
Course1: A2
Course2: B1
Course2: B2
Course2: B3
Course2: B4
Course3: C1
Course3: C2
Mi piacerebbe creare due JComboBox (JComboBox1, JComboBox2) in modo che JComboBox1 contiene corso1, ciclo di formazione2, Course3, ecc.
Se si seleziona, per esempio, ciclo di formazione2 da JComboBox1 poi corrispondente B1, B2, B3, B4 deve essere compilato in JComboBox2.
Come implementare questo? Molte grazie.
Soluzione
Sì, è sufficiente creare un DefaultComboBoxModel
per ogni set, e fare setModel()
su JComboBox2
quando i cambiamenti JComboBox1
.
Addendum: Ad esempio,
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ComboTest extends JPanel implements ActionListener, Runnable {
private final JComboBox combo1 = new JComboBox(
new String[]{"Course 1", "Course 2", "Course 3"});
private final JComboBox combo2 = new JComboBox();
private ComboBoxModel[] models = new ComboBoxModel[3];
public ComboTest() {
models[0] = new DefaultComboBoxModel(
new String[]{"A1", "A2"});
models[1] = new DefaultComboBoxModel(
new String[]{"B1", "B2", "B3", "B4"});
models[2] = new DefaultComboBoxModel(
new String[]{"C1", "C2"});
combo2.setModel(models[0]);
this.add(combo1);
this.add(combo2);
combo1.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
int i = combo1.getSelectedIndex();
combo2.setModel(models[i]);
}
@Override
public void run() {
JFrame f = new JFrame("ComboTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new ComboTest());
}
}
Altri suggerimenti
Sì. È possibile aggiungere un listener cambiamento evento per la prima JComboBox che aggiorna i valori della seconda JComboBox.
Qualcosa di simile a questo
// first comboBox
final JComboBox courseBox = new JComboBox(
new String[]{"Course 1", "Course 2", "Course 3"});
final JComboBox box2 = new JComboBox();
// Now listen for changes
courseBox.addActionListener(new ActionListener(){
void actionPerformed(ActionEvent e){
if(courseBox.getSelectedItem().equals("Course 1")){
// we know that the user picked "Course 1", now change box2 to match
// first clear everything
box2.removeAllItems();
// now add back relevant values
box2.addItem("A1");
box2.addItem("A2");
}else if(...){
// ...
}
}
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow