Search code examples
javaswingeventsactionlistenerjcombobox

ActionPerformed self-execution


I don't understand why the code in the jcombobox4ActionPerformed is being executed without me clicking on anything. As soon as the program is executed, the "executed" message appears. What is the problem ?

public class MainFrame extends javax.swing.JFrame
{

    public MainFrame()
    { 
        initComponents();
        initComboBox();
        initCourses();

        Course[] cours = new Course[7];

        for (int i = 0; i < cours.length; i++) 
        {
            cours[i] = new Course();
        }

        System.out.println(cours.length);
        System.out.println(cours[0].getNameCourse());


        System.out.println("hey");

    }

private void jComboBox4ActionPerformed(java.awt.event.ActionEvent evt) {                                           

    System.out.println("EXECUTED");
}

Solution

  • You could try print out the action command from the ActionEvent so you know what is firing it

    private void jComboBox4ActionPerformed(java.awt.event.ActionEvent evt) { 
        String action = evt.getActionCommand(); 
        System.out.println(action);
    } 
    

    Then if you want certian things to happen only on certain actions you can check that action command

    private void jComboBox4ActionPerformed(java.awt.event.ActionEvent evt) {  
        String action = evt.getActionCommand(); 
        System.out.println(action);
        if(action.equals("doBlah")
        {
           System.out.println("Blah blah blah blah");  
        }
    }