Question

I have my JButton set up and everything but it does absolutely nothing. Could someone tell me how to add a command such as system.out.println or some Scanner commands to a JButton?

Here is my line of code. It is very simple and I'm just testing JButton to add it to some of my other programs

    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();
    }
}

No correct solution

OTHER TIPS

See How to Write an Action Listener.

I suggest you read the entire tutorial (or keep a link to it for reference) as it contains all the Swing basics.

Hope this helps

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");
    }
});  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top