製作互動式使用者介面

有一個按鈕,一切都很好,但如果點選它什麼都不做,那又有什麼意義呢? ActionListeners 用於告訴你的按鈕或其他元件在啟用時執行某些操作。

新增 ActionListeners 就是這樣完成的。

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

或者,如果你使用的是 Java 8 或更高版本……

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

示例(Java 8 及更高版本)

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