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();
 }
 }

Edited 3 Years Ago by Neon Tetras

no its not.
its a personal project

loop inside container where JComboBoxes are laid, by checking if(xxx instanceof JComboBox(Oracle APi)/ComboBox(your class)) desired and filtered Objects is accesible, pseudocode

  Component[] comp = container.getComponents();
  for (int i = 0; i < comp.length; i++) {
        if (comp[i] instanceof Xxx) {
            comp[i].wheteverMethodImplementedInConcreteAPI;
        } 
  }

Edited 3 Years Ago by mKorbel

This article has been dead for over six months. Start a new discussion instead.