Page 1 of 1

Swing Tutorial part II Handling Events in swing Rate Topic: ***** 1 Votes

#1 jinnyishere  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 46
  • View blog
  • Posts: 127
  • Joined: 06-July 09

Post icon  Posted 17 September 2009 - 11:51 PM

*
POPULAR

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

}




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

	}
}



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.


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



Is This A Good Question/Topic? 8
  • +

Replies To: Swing Tutorial part II

#2 jinnyishere  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 46
  • View blog
  • Posts: 127
  • Joined: 06-July 09

Posted 04 October 2009 - 10:09 AM

Please!! Do leave some feedbacks so i know what to improve...

is it confusing, not clear enough, needs more examples and so on..

open for any suggestions...
Was This Post Helpful? 1
  • +
  • -

#3 Guest_salma*


Reputation:

Posted 19 March 2010 - 11:36 PM

View Postjinnyishere, on 04 October 2009 - 09:09 AM, said:

Please!! Do leave some feedbacks so i know what to improve...

is it confusing, not clear enough, needs more examples and so on..

open for any suggestions...


the nameframe is not working properly i guess
it gives me window with the window name but there is no box in it to enter the name n there is no ok button in it
pls check the code and let me know... .
Was This Post Helpful? 0

#4 Guest_salma*


Reputation:

Posted 20 March 2010 - 07:30 AM

View Postsalma, on 19 March 2010 - 10:36 PM, said:

View Postjinnyishere, on 04 October 2009 - 09:09 AM, said:

Please!! Do leave some feedbacks so i know what to improve...

is it confusing, not clear enough, needs more examples and so on..

open for any suggestions...


sorry its working properly....

Was This Post Helpful? 0

#5 jinnyishere  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 46
  • View blog
  • Posts: 127
  • Joined: 06-July 09

Posted 06 May 2010 - 02:42 AM

:online2long:
Was This Post Helpful? 0
  • +
  • -

#6 nmslave  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 28-September 10

Posted 03 November 2010 - 07:50 AM

Hi, nice tuto but I have one doubt. In the last example, you didn't add "txt" object to the panel. I can see it is related with the "scroll" object, but can you explain the reason why it is not necesary to add this to the panel? Thak you. New java programmer xD.
Was This Post Helpful? 0
  • +
  • -

#7 mogallin  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 5
  • Joined: 21-August 10

Posted 14 January 2011 - 01:56 PM

I didn't get the second example to work at first. Putting the setVisible(true) statement after add(panel) did the trick for me though. Any idea why it is so? Otherwise it seems like a good tutorial so far.
Was This Post Helpful? 0
  • +
  • -

#8 jgonzalez498  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 43
  • Joined: 29-May 11

Posted 31 May 2011 - 08:49 PM

Wow really awesome it helped me with understanding more Swing components looking forward to reading the next one only one click away :D however I have one problem on all of your sample codes you wrote this code? Why do you need to write that?
 
public static void main(String[] args)
    {
        new ChangeBackground();
    }


Was This Post Helpful? 0
  • +
  • -

#9 jinnyishere  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 46
  • View blog
  • Posts: 127
  • Joined: 06-July 09

Posted 08 December 2011 - 02:06 PM

Hi! all sorry for the delay replies, have been busy working on new tutorials for JDK 7, if you guys haven't try it. It's pretty neat with new swing features, it pretty easy to modify the shape of the window or change the opacity, and with JavaFX 2.0 in play, graphics are such much easier to deal with. Also, I have several tutorial on Java slick 2d game engine and android up too. Anyway, back to the questions, you guys probably won't need it anymore but here it is, First answer to mogallin, you gotta put setVisible(true) at the end, if you don't do that the window will not appear. Try it out, to make setVisible to false and see what happen. nmslave: The reason why i didn't add the txt to the panel because it's already added to JScrollPane, so adding JScrollPane to the panel will add the txt also, therefore we don't need to add it to the panel. jgonzalez498 The first time when a java program executes, it will go to main first, thus by calling new ChangeBackground(), it will call the class, and in that class we created a window with objects in it. So let said we have another class "Background2" with a different JFrame and consists of different components, if we call that in the main " new Background2()", it will display the Background2() JFrame and not the ChangeBackground JFrame. I have a atm example demonstrating. hope that helps,

Happy coding...
Was This Post Helpful? 1
  • +
  • -

#10 Hoddie54  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 14-January 12

Posted 14 January 2012 - 04:16 AM

Thank you. This tutorial has helped me understand Swing better. :)
Was This Post Helpful? 0
  • +
  • -

#11 sykoticm  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 28
  • Joined: 07-October 11

Posted 23 January 2012 - 08:27 AM

Hey, i figured this would be the place to post this instead of making a new thread. So I am a semi new to java, and even more "new" to java swing. My question is how would or is this even possible? Create a JTextBox and lets say "align" it to the left, right, or center Even better set its location to a specific location on the frame using pixel arrangement?

-- Sykoticm
Was This Post Helpful? 0
  • +
  • -

#12 jinnyishere  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 46
  • View blog
  • Posts: 127
  • Joined: 06-July 09

Posted 24 February 2012 - 10:17 AM

View Postsykoticm, on 23 January 2012 - 08:27 AM, said:

Hey, i figured this would be the place to post this instead of making a new thread. So I am a semi new to java, and even more "new" to java swing. My question is how would or is this even possible? Create a JTextBox and lets say "align" it to the left, right, or center Even better set its location to a specific location on the frame using pixel arrangement?

-- Sykoticm


Hi! Sykoticm, Sorry for replying so late, I don't get notification send to my email when someone leaves a message here. What you are looking is Java Layouts. You can use BorderLayout to control your JTextBox to be left, right, center, up or down. There are a lot of good tutorials out there for Java Layouts. If for some reason you can't find any, I have a few tutorials regarding to layouts on my site. "cppjj.com"

~Thank you
Jay Lei
Was This Post Helpful? 0
  • +
  • -

#13 Benzoate  Icon User is offline

  • D.I.C Head


Reputation: 51
  • View blog
  • Posts: 230
  • Joined: 29-February 12

Posted 28 March 2012 - 07:41 PM

[code ]txt.append("Hello World!!!\n"); [/code]

what does the "\n" at the end do? I've seen this before yet I've never been able to figure it out..
Was This Post Helpful? 0
  • +
  • -

#14 Benzoate  Icon User is offline

  • D.I.C Head


Reputation: 51
  • View blog
  • Posts: 230
  • Joined: 29-February 12

Posted 28 March 2012 - 08:05 PM

View PostBenzoate, on 28 March 2012 - 07:41 PM, said:

txt.append("Hello World!!!\n"); 


what does the "\n" at the end do? I've seen this before yet I've never been able to figure it out..


never mind, I figured it out. :)
Was This Post Helpful? 0
  • +
  • -

#15 jinnyishere  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 46
  • View blog
  • Posts: 127
  • Joined: 06-July 09

Posted 04 May 2012 - 09:58 AM

:P
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1