简体   繁体   中英

jButton with a very strange behaviour

I've developed some desktop application, based on netbeans GUI creator, I'm facing strange problem with jButton behaviour, every time I click it, it acts 7 times:

jButton7.addActionListener(new ButtonListener());
class ButtonListener implements ActionListener {
ButtonListener() {
}
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("pushToTest")) {
            System.out.println("Button1 has been clicked");
            }
      }
}

and the output looks like:

Button1 has been clicked
Button1 has been clicked
Button1 has been clicked
Button1 has been clicked
Button1 has been clicked
Button1 has been clicked
Button1 has been clicked

just after one click. It happens to all of my buttons, I can't post gui's code, it's like 1700 lines, nobody would even bother reading it.

In fact I'll make my comment an answer:

My guess -- your problem is in code not shown, and that you are likely adding the ActionListener to each JButton 7 times. Are you using for loops to do this? You'll need to check your code carefully, and right now, we can't help you since again, the offending code has not yet been shown.

Edit: your pastebin post suggests that you are in fact doing a lot of GUi initialization stuff inside of a for loop, this loop: for (int ii = 0; ii < holder2.size() / 3; ii++) { . Check out where the closing curly brace is:

         setComponent(mainPanel);
     setMenuBar(menuBar);
     setStatusBar(statusPanel);
  }// </editor-fold>  // *** here ***

And there is a ton of code between these braces including most all of your GUI initialization code. This is likely what is causing you to add your ActionListener 7 times to your button. My guess is that you really don't want the for loop to call all that code, that your mistake was in not adding the loop's end brace at the right spot.

Also, consider re-factoring that monster program and use variable names that make logical sense, and you will find that it will be much easier to debug your program. Same for us.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM