
Swing
Handling Events
In the previous chapter, we learn
how to create frames with labels, buttons and panels. However, when the button
is clicked it does nothing. In this chapter we will learn how to handle events
for buttons when it is clicked. The technique we use is called
event listening,
and it's one of the most important aspect of writing swing programs.
An event
is an object that's generated when the user does something with one of the user
interface components. For examples, a click of a button, selection of an item, a
drag of the mouse over a label and so on, all those are events. Then those event
objects are passed to a special method we create called
event listener.
Hence, the event listener determine exactly what type of event occurred, and
respond accordingly.
Look at the link (" Swing Method & constructor Table " ) below for a list of event and listener class with description.
When working with the swing class, we need to import javax.swing.*; for the swing components, import java.awt.*; for the color class, and import java.awt.event.*; for the event class.
Lets see a program that will
demonstrate a click of a button changes the background and text colors. The
method for changing the background color is
setBackground(name of color) and the method for changing the text color is
setForeground(name of color).
Here is a list of the color:
Color.BLACK
Color.RED
Color.PINK
Color.YELLOW
Color.GREEN
Color.ORNAGE
Color.WHITE
Color.CYAN
.
.
.
.
Example)
/*
The program demonstrates handling of events
It has 3 buttons, each buttons represent a different color
A push of a button changes the window background color
*
*/
import javax.swing.*; // Needed for the
swing class
import java.awt.*; // Needed for color
class
import java.awt.event.*; // Needed for
event listener interface
public class ChangeBackground extends JFrame
{
JLabel msg;
JButton blackButton;
JButton yellowButton;
JButton greenButton;
JButton pinkButton;
JPanel panel;
public ChangeBackground()
{
// Sets the title of
the window
setTitle("Change Background Window");
// Sets the size of the window
setSize(230, 400);
// Sets the action when the window is close
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Creates a label that print on the window
msg = new JLabel("Click a button to change the color");
// Creates the 4 button with names associate to it
blackButton = new JButton("Black");
yellowButton = new JButton("Yellow");
greenButton = new JButton("Green");
pinkButton = new JButton("Pink");
// Register an event listener with all the buttons
blackButton.addActionListener(new blackButtonListener());
yellowButton.addActionListener(new yellowButtonListener());
greenButton.addActionListener(new greenButtonListener());
pinkButton.addActionListener(new pinkButtonListener());
/*
Now we will create a panel
Then adds all the buttons to the
panel & the label
*
*/
panel = new JPanel();
panel.add(msg);
panel.add(blackButton);
panel.add(yellowButton);
panel.add(greenButton);
panel.add(pinkButton);
// Adds the panel to the content pane ( The JFrame window )
add(panel);
// Sets the window to be visible
setVisible(true);
}
/*
Here handles the event when the user
clicks the button
The background color will changes to
black
*
*/
public class blackButtonListener implements ActionListener
{
public void
actionPerformed(ActionEvent e)
{
// Sets the
panel's background to black
panel.setBackground(Color.BLACK);
// Sets the
label's text to blue
msg.setForeground(Color.BLUE);
}
}
// The background color changes to yellow
public class yellowButtonListener implements ActionListener
{
public void
actionPerformed(ActionEvent e)
{
// Sets the
panel's background to yellow
panel.setBackground(Color.YELLOW);
// Sets the
label's text to red
msg.setForeground(Color.RED);
}
}
// The background color changes to green
public class greenButtonListener implements ActionListener
{
public void
actionPerformed(ActionEvent e)
{
// Sets the
panel's background to green
panel.setBackground(Color.GREEN);
// Sets the
label's text to black
msg.setForeground(Color.BLACK);
}
}
// The background color changes to pink
public class pinkButtonListener implements ActionListener
{
public void
actionPerformed(ActionEvent e)
{
// Sets the
panel's background to pink
panel.setBackground(Color.PINK);
// Sets the
label's text to red
msg.setForeground(Color.RED);
}
}
public static void main(String[] args)
{
new ChangeBackground();
}
}
ClickHere to download ChangeBackground.java
The above example created 3 buttons, each button has its own event. A click of a button calls the event listener, then inside the event listener it changes the text and background color. Although, sometimes it would be a lot of work to write each event listener out hence we can use a else-if statement to determine which button is clicked with the help of two unique methods:
e.getSource(); --- Returns a reference to the object that generated this event
e.getActionCommand(); --- Returns the action command for this event as a String
Example)
/*
The program gets a name from the user using e.getSource
Then it outputs the name to the screen
*
*/
import javax.swing.*;
import java.awt.event.*;
public class NameFrame extends JFrame
{
JPanel panel;
JButton okbutton;
JLabel msg;
JTextField txtfield;
public NameFrame()
{
// Sets the title of the frame
setTitle("Name Window");
// Sets the size of the window
setSize(300, 400);
// Sets the action when window is
close
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Sets the visibility of the window
setVisible(true);
// Creates the panel
panel = new JPanel();
// Creates a label
msg = new JLabel("Enter a name: ");
// Creates the text field
txtfield = new JTextField(15);
// Creates the button
okbutton = new JButton("OK");
// Adds to the panel
panel.add(msg);
panel.add(txtfield);
panel.add(okbutton);
// Add the panel to the content pane
add(panel);
// Creates the action listener
okbutton.addActionListener(new
ButtonListener());
}
// Handles the event if a button is clicked
public class ButtonListener implements ActionListener
{
public void
actionPerformed(ActionEvent e)
{
// If ok
button is clicked, gets the input name
if(e.getSource()==okbutton)
{
// Gets the name from the text field
String name = txtfield.getText();
// If the text field is empty return a message
if(name.length() == 0)
{
JOptionPane.showMessageDialog(null, "You didn't enter anything");
}
else
{
JOptionPane.showMessageDialog(null, "Hello!! " + name);
}
txtfield.requestFocus();
}
}
}
public static void main(String[] args)
{
new NameFrame();
}
}
ClickHere to download NameFrame.java
The above program used the requestFocus() method, what it does is when the user enters a name, clicks the ok button, then the JOptionPane pops out and prints out a message. When the use clicks the ok button on the JOptionPane again, with the requestFocus() method, the focus will automatically go back to the text field. However, if we didn't put the requestFocus() method, the focus will go back to the ok button. It might be a little confusing just reading it, thus download/copy the program run it and test it out for yourself with the focus method then run once again without the focus method.
Creating JTextArea
A text area simply is a text field that allows the user to enter more than one line of text. The text area can use the scroll bar to help the user to see the entire text. To create a text area we must use two classes. First, we use the JTextArea class to create the text area, then we would use the JScrollPane class to create scroll bars for the text area. Lets see a basic example on how to create a JTextArea.
Note: For more GUI examples please refer to the Java Example, GUI on the home page or simply click here. As for the JTextArea & JScrollPane methods and constructors click on the link below " Swing Method & Constructor Table. "
/*
The program creates a JTextArea with scroll bars
*
*/
import javax.swing.*;
import java.awt.event.*;
public class TextArea extends JFrame
{
JPanel panel;
JButton ok;
JTextArea txt;
JScrollPane scroll;
public TextArea()
{
// Sets the title
setTitle("Text Area");
// Sets the size
setSize(300, 400);
// Sets the event when the window
close
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Creates a panel
panel = new JPanel();
// Creates an empty Text Area with 10
rows and 20 columns
txt = new JTextArea("", 10, 20);
// Creates a button
ok = new JButton("OK");
// Create a scroll pane in the text
area
scroll = new
JScrollPane(txt, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
// Adds the scroll to the panel
panel.add(scroll);
// Adds the button to the panel
panel.add(ok);
// Adds the panel to the content pane
add(panel);
// Sets the window to be visible
setVisible(true);
// Creates an action listener
ok.addActionListener(new
ButtonListener());
}
public class ButtonListener implements ActionListener
{
public void
actionPerformed(ActionEvent e)
{
if(e.getSource()==ok)
{
// Appends Hello World to the text area whenever ok button is clicked
txt.append("Hello World!!!\n");
}
}
}
public static void main(String[] args)
{
new TextArea();
}
}
ClickHere to download TextArea.java