JPAINT
PART  2 – GUI INTERACTIVITY

separator-blank

In this part, we will add basic GUI interactivity.  For now, all that will mean is clicking the tool buttons and getting a message in the text area.  We will worry about the drawing interactivity in the next section.

DISCUSSION

You can add interactivity in several different ways.  A quick look back to our lesson notes will likely be useful to you.

In this guide, we will continue to work with a single class.  The class will implement ActionListener and will therefore also have the method actionPerformed(ActionEvent e) in it.

Here are the steps:

STEP 1

Make sure the class implements ActionListener.

STEP 2

Include the following method that will automatically be called when an action is performed:

                public void actionPerformed(ActionEvent e)
     {   }

STEP 3

Add action listeners to all buttons by using:

                                buttonName.addActionListener(this);

STEP 4

Add a simple sysout statement inside the actionPerformed method so that you can test to make sure that everything is working correctly.

Test your code.  Whenever a button is clicked, your sysout statement should be executed.

STEP 5

We now would like to be able to differentiate between the buttons that caused the event.  We also would like to be able to output the text inside the text area instead of in the console.  To do this, we need to declare all of these components as data fields (if you didn’t do this already).

Go ahead and declare all components as data fields.

STEP 6

We can now reconsider the sysout statement that was placed inside the actionPerformed method.  We can remove it and replace it by a statement that will place a message inside the text area.

STEP 7

We can now differentiate between buttons by using:

if(e.getSource() == button1Name)
{
   //do something
}
else if (e.getSource() == button2Name)
{
   //do something else
}

Add to the code above so that the text area gets a different message for a few buttons.

Your final product should look like this after two different buttons are clicked.

That’s it for this section.

separator-blank