I created several JComboBoxes using a for loop. I want them to reset when i click the reset button.
But this doesn't work.
These are my codes...
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
class TryCombo extends JFrame{
TryCombo(){
super("Trying JComboBox");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton but = new JButton("reset");
but.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
ComboBox myCombos = new ComboBox();
myCombos.setSelectedItem("Grades");
}});
JPanel pane = new JPanel();
pane.setLayout(new GridLayout(2,3));
for(int i = 1; i<=6; i++){
pane.add(new ComboBox());
}
add(pane,BorderLayout.CENTER);
add(but,BorderLayout.SOUTH);
pack();
setVisible(true);
}
class ComboBox extends JComboBox implements ItemListener{
ComboBox(){
final String[] Grades = {"Grades","A","A-","B+","B","B-","C+","C","C-","D","F"};
for(String grades : Grades){
addItem(grades);
}
addItemListener(this);
}
public void itemStateChanged(ItemEvent e){
Object item = getSelectedItem();
System.out.println(item);
}
}
public static void main(String[] args){
new TryCombo();
}
}