swing Using Swing for Graphical User Interfaces Making Interactive User Interfaces


Example

Having a button there is all well and good, but what's the point if clicking it does nothing? ActionListeners are used to tell your button, or other component to do something when it is activated.

Adding ActionListeners is done as such.

buttonA.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        //Code goes here...
        System.out.println("You clicked the button!");
    }
});

Or, if you're using Java 8 or above...

buttonA.addActionListener(e -> {
    //Code
    System.out.println("You clicked the button!");
});

Example (Java 8 and above)

JFrame frame = new JFrame("Super Awesome Window Title!"); //Create the JFrame and give it a title
frame.setSize(512, 256); //512 x 256px size
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //Quit the application when the JFrame is closed

JPanel pane = new JPanel(); //Create a pane to house all content
frame.setContentPane(pane);

JButton button = new JButton("Click me - I know you want to.");
button.addActionListener(e -> {
    //Code goes here
    System.out.println("You clicked me! Ouch.");
});
pane.add(buttonA);

frame.setVisible(true); //Show the window