简体   繁体   中英

ActionListener on JButton creating “image” of a button in my frame?

I am creating a game of connect-4 using swing in java. I have an array of 6 buttons which are used to input the move the player wants to make.

When I click a button, the ActionListener does what I want it to do, but also places an image of the most recently pressed button in the upper left of the screen. I say "image" of a button because it cannot be clicked. Here's my code:

public class ButtonPanel extends JPanel implements ActionListener{
    ArrayList<JButton> buttonList;

    public ButtonPanel(){

        //set up the JPanel...

        for (int i = 0; i < 7; i++){
            buttonList.add(new JButton("" + i));
            buttonList.get(i).addActionListener(this);
            add(buttonList.get(i));
        }
    }
    public void actionPerformed(ActionEvent e) {
        for (JButton b : buttonList){
            if(e.getSource() == b){
                frame.playerMove =  buttonList.indexOf(e.getSource());
                return;
            }
        }
    }
}

Here's what happens when I click the button 3

And when I click button 5

Does anybody know what's happening here, or how to fix it?

but also places an image of the most recently pressed button in the upper left of the screen. I say "image" of a button because it cannot be clicked.

Sounds to me like you are doing custom painting.

  1. Make sure you are overriding paintComponent() , not paint();
  2. Make sure the first statement in the paintComponent() method is super.paintComponent(...) so the background of your panel is cleared before the custom painting is done.

If this doesn't help, then post a proper SSCCE that demonstrates the problem.

In the future, make sure you post a SSCCE with all your questions.

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