有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何让JButton做某事

我有我的JButton设置和一切,但它绝对没有做什么。有人能告诉我如何添加命令,例如system。出来打印LN或一些扫描命令到JButton

这是我的代码行。它非常简单,我正在测试JButton,以便将其添加到我的其他一些程序中

    import javax.swing.*;

    public class Swing extends JFrame {
    JButton load = new JButton("Load");
    JButton save = new JButton("Save");
    JButton unsubscribe = new JButton("Unsubscribe");

    public ButtonFrame() {
        super ("ButtonFrame");
        setSize(140, 170);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel pane = new JPanel();
        pane.add(load);
        pane.add(save);
        pane.add(unsubscribe);
        add(pane);
        setVisible(true);
}

    public static void main(String[] arguments) {
        ButtonFrame bf = new ButtonFrame();
    }
}

共 (2) 个答案

  1. # 1 楼答案

    How to Write an Action Listener

    我建议你阅读整个教程(或者保留一个链接以供参考),因为它包含了所有的Swing基础知识

  2. # 2 楼答案

    希望这有帮助

    load.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e)            {
            //Here goes the action (method) you want to execute when clicked
            System.out.println("You clicked the button load");
        }
    });   
    //The same for save button
    save.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e)            {
            //Here goes the action (method) you want to execute when clicked
             System.out.println("You clicked the button save");
        }
    });