What is the simplest way to implement "hover behavior" in Piccolo2D?
I.e. to change object's color or style when mouse cursor is above it? Need to take in account both move ins and outs correctly.
What is the simplest way to implement "hover behavior" in Piccolo2D?
I.e. to change object's color or style when mouse cursor is above it? Need to take in account both move ins and outs correctly.
You can add input event handlers to nodes. Below is a basic example that attaches PBasicInputEventHandler
to a layer to capture mouseEntered
and mouseExited
events. It is also possible to add event handler to individual nodes in a layer.
import java.awt.Color;
import javax.swing.SwingUtilities;
import edu.umd.cs.piccolo.event.PBasicInputEventHandler;
import edu.umd.cs.piccolo.event.PInputEvent;
import edu.umd.cs.piccolo.nodes.PPath;
import edu.umd.cs.piccolox.PFrame;
public class DemoInputHandler {
@SuppressWarnings("serial")
private static void createAndShowUI() {
new PFrame() {
@Override
public void initialize() {
PPath node = PPath.createRectangle(0, 0, 100, 100);
node.setOffset(50, 50);
node.setPaint(Color.BLUE);
getCanvas().getLayer().addChild(node);
node = PPath.createRectangle(0, 0, 100, 100);
node.setOffset(200, 50);
node.setPaint(Color.BLUE);
getCanvas().getLayer().addChild(node);
getCanvas().getLayer().addInputEventListener(
new PBasicInputEventHandler() {
@Override
public void mouseEntered(final PInputEvent event) {
event.getPickedNode().setPaint(Color.RED);
}
@Override
public void mouseExited(final PInputEvent event) {
event.getPickedNode().setPaint(Color.BLUE);
}
});
}
};
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}