Comparing components via setName() .

后端 未结 2 592
春和景丽
春和景丽 2021-01-28 04:13

I am coding an image puzzle game and one part of the code is to compare the pieces the user has selected to the pieces of the correct image.

Each image piece is already

相关标签:
2条回答
  • 2021-01-28 04:41

    In your mouseReleased event m.getButton() is returning the mouse button that was clicked. You'll want to do something more like this that will get you closer:

    if (m.getComponent().getName().equals(waa.getName())) {
    

    m.getComponent() returns the Component object (your JButton) that the event was fired from. From there you can do the comparison with the getName approach you are using.

    There's an additional issue in that your waa variable is an array. I'm not sure how you want to compare them, whether running through the arrays and making sure the index and names match, but that's an additional issue you need to look into.

    0 讨论(0)
  • 2021-01-28 04:42

    JButton uses an ActionListener to trigger notifications back to your program to indicate when it's been triggered. This allows the button to respond to different types of event, including the mouse, keyboard and program triggers.

    As apart of the action API, you can supply an action command for each button. See JButton#setActionCommand

    Basically you would integrate it in a simular way to your mouse listener...

    public void actio Performed(ActionEvent evt) {
        if (command.equals(evt.getActionCommand()) {...}
    }
    

    Depending on your requirements, it might even be easier to use the Action API

    The problem you are actually having is waa is an array, therefore, it doesn't have a getName method. I'm also unclear as to why you have two arrays of buttons?

    0 讨论(0)
提交回复
热议问题