Question

I have an ImageIcon inside of a JButton. The JButton knows what it's "position" is relative to another Object, but the ImageIcon doesn't. How can I get the JButton element from within the ImageIcon class?

I tried something like this:

storedPosition = getParent().getPosition();

but I'm getting a

The method getParent() is undefined for the type Piece

error.

Was it helpful?

Solution

How can I get the JButton element from within the ImageIcon class?

Yes you can do it using ImageIcon#getImageObserver() and ImageIcon#setImageObserver().

Sample code:

    ImageIcon icon = new ImageIcon();
    JButton btn = new JButton(icon);

    // set the Image Observer of the ImageIcon
    icon.setImageObserver(btn);

    ...

    // get Image Observer back from ImageIcon
    JButton observer = (JButton) icon.getImageObserver();

    if (observer == btn) {
        System.out.println("We got the JButton from ImageIcon");
    }

output:

We got the JButton from ImageIcon
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top