How to check if my jButton has that specific imageIcon?

1.6k Views Asked by At
private void Table1ButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
    // TODO add your handling code here:

    ImageIcon i = new ImageIcon("images\\img.png");

    if(Table1Button.getIcon() == i){
          MakeABooking mab = new MakeABooking();
          mab.setVisible(true);
        }
}     

Hi could some one help me so that I can check if my jButton has that specific imageIcon please? Thanks

1

There are 1 best solutions below

5
Duško Mirković On

There is no default method for this as far as I know. What you could do is create a new class that extends the ImageIcon class, and create new field String name and override equals method to check if the names are equal.

Something like:

class MyImageIcon extends ImageIcon {

    private String name;

    public MyImageIcon(String filename, String imageName){
       super(filename);
       name = imageName;
    }

    // Override equals method and check if names are equal
    @Override
    public boolean equals(Object other){
        MyImageIcon otherImage = (MyImageIcon)other;
        if (other == null) return false;
        return name.equals(otherImage.name);
    }

}

Then to check you would do something like:

MyImageIcon myButtonIcon = (MyImageIcon)myButton.getIcon();
MyImageIcon myImageIcon = new MyImageIcon(imageFile, imageName);
if (myButtonIcon.equals(myImageIcon)) {
    // Do stuff
}