制作交互式用户界面

有一个按钮,一切都很好,但如果点击它什么都不做,那又有什么意义呢? 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