Sergei G
Sergei G

Reputation: 1570

jButton responds only to second click (Netbeans 6.9.1, Java)

I have an annoying problem, and I don't seem to understand where in comes from. I have an application and a simple UI for it. The problem is that when I run the program buttons respond only to the second click. After they do what they have to do, buttons respond to the first click. I really don't know what is the source of the problem. Here is some source code for binding jButton and actionlistener:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    jButton1.addActionListener(new SolutionListener());
}

And here is actionlistener itself (if it helps):

private class ListListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        jTextArea1.setText(null);
        if (jTextField2.getText().equals("")) {
            jTextArea1.append("Input a value");
        }
        else {
            for (int i = 2; i <= Integer.valueOf(jTextField2.getText().trim()); i++) {
                if(isSquare(i) == true) {
                    continue;
                }
                else {
                    PE pe = new PE(i);
                    answer = pe.solve();
                    jTextArea1.append(i + "\t");
                    jTextArea1.append(answer[0].toString() + " ");
                    jTextArea1.append(answer[1].toString() + "\n");
                }
            }
        }
    }
}

I would really appreciate any help, thanks in advance!

Upvotes: 0

Views: 2701

Answers (2)

Costis Aivalis
Costis Aivalis

Reputation: 13728

If you try this:

    jButton1.addActionListener(new ActionListener () {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            System.out.println("outside Action");
            jButton1.addActionListener(new ActionListener () {
                public void actionPerformed(java.awt.event.ActionEvent evt2) {
                    System.out.println("inside Action");
                }
            });
        }
   });

One key click will print "outside Action" and the second will print "inside Action".
You only need one ActionListener per JButton.

Upvotes: 0

camickr
camickr

Reputation: 324098

You should not be adding an ActionLIstener to the button in the actionPerformed() code. (I don't know how it works at all).

You must have two listeners in your program. Also because you add a second listener every time the button is pressed the event code will then be executed multiple times since you keep adding a new listener.

For more help post a SSCCE that demonstrates the problem. The few lines of code don't show us how the GUI is built.

Upvotes: 2

Related Questions