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();
 }
 }
Member Avatar for iamthwee

Iterate through each one and call setSelectedIndex(0);

That would be the easiest

so how can i do this?

Member Avatar for iamthwee

Is this homework?

no its not.
its a personal project

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;
        } 
  }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.