Tino APCS

Misc Things to Know

setOnAction()

Controls that have a discrete state (on/off/pressed/selected/etc.) have a setOnAction() method. You should use setOnAction() instead of onMouseClicked() because there are other ways the user could have invoked the Control.

  • If a user presses <Space> when a Button has focus, setOnAction() is invoked and it counts as a click.
  • If a user clicks on a Button, setOnAction() is invoked and it counts as a click.
  • If another part of the GUI fires the button, it counts as a click.

Some classes that use setOnAction() are Button, RadioButton, ToggleButton, CheckBox, ChoiceBox, ComboBox, MenuItem

Summary: Whenever a GUI element has a setOnAction() method, you should use it instead of onMouseClicked().

One event handler for multiple GUI elements

When creating private inner classes for custom event handlers, you only need to make one handler for each type. For example, let's say you have the following event handler to handle button presses:

private class MyButtonHandler implements EventHandler<ActionEvent> {
    @Override
    public void handle(ActionEvent e) {
        // Handle button code here
    }
}

You can detect which button was pressed by invoking the getSource() method of the ActionEvent parameter. getSource() returns the object that triggered the event.

private class MyButtonHandler implements EventHandler<ActionEvent> {
    @Override
    public void handle(ActionEvent e) {
        // Handle all buttons
        if (e.getSource() == okBtn) {
            System.out.println("OK");
        }
        else if (e.getSource() == cancelBtn) {
            System.out.println("CANCEL");   
        }
    }
}

Note that okBtn and cancelBtn will need to be declared as instance variables in order to be accessible here.

MouseEvent Notes

If the parameterized type of your ActionEvent is a MouseEvent, you can ask the MouseEvent object for any mouse info you need.

private class MyMouseHandler implements EventHandler<MouseEvent> {
    @Override
    public void handle(MouseEvent e) {
        // Look in the MouseEvent API for methods
    }       
}

Here are some common MouseEvent methods:

  • getButton() returns a constant from MouseButton.

    if (e.getButtion() == MouseButton.PRIMARY)
    
  • getEventType() returns the kind of mouse event that happened. Compare the return value to the constants defined in MouseEvent.

    if (e.getEventType() == MouseEvent.MOUSE_CLICKED)
    
  • getX() and getY() return the mouse (x, y) relative to the Control being interacted with

  • getSceneX() and getSceneY() return the mouse (x, y) relative to the Scene

  • getScreenX() and getScreenY() return the mouse (x, y) relative to the user's entire screen

Video Demo

The links below are part 1 and 2 of a demo showing how to use EventHandlers and ChangeListeners to make buttons and sliders do things.

Dark Mode

Outline