Button Events

246 2 0
                                        

Alright, we are doing pretty good so far! We can make a GUI, and some of the components of one too. Now, what happens when we want something to happen when a button is hit. Well, we are going to have an inner class run that for us! Start by importing java.awt.event.* Now, type this code

myButton.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {

        //Code you want to execute when the button is hit

    }

});

And that is it! You can type whatever you want to happen there, for my first actionListener, I just had it bring up a JOptionPane.showMessageDialog box, saying that you hit my first button, and this was the action listener for it. We can get into some of the other types of listeners later, but first, you have to learn how to add all of those components! See you in the next chapter,

-Steve

Java Swing GUI DevelopmentWhere stories live. Discover now