Using ActionListener, actionPerformed in Java Applet using swing for Textfield and Button

Q.: Create java applet using swing which will accept string or input from user in textfield and after submitting(button click), it will display that input in console screen.

OR

Q. Create java applet using swing to demonstrate use of ActionListener, actionPerformed, event.getSource, .getText, JTextField, JButton, applet.

Compatibility/Version: Java 2 Platform Standard Edition Version 1.5 (Java 2 SDK, SE v1.5.0)

Concepts used:

  • applet
  • swing
  • JApplet
  • JTextField
  • JButton
  • JTextField
  • ActionListener
  • actionPerformed(ActionEvent event)
  • event.getSource()
  • getText()

Code:

import java.applet.Applet;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class button extends JApplet
{
/*
<APPLET
    CODE="button.class"
    WIDTH=200
    HEIGHT=100 >
</APPLET>
*/
	JTextField text1;
	JButton button1;

	public void init()
	{
		setLayout(new FlowLayout());
		text1 = new JTextField(20);
		getContentPane().add(text1);
		button1 = new JButton("Click Here!");
		getContentPane().add(button1);
		button1.addActionListener(new handler ());
	}
	class handler  implements ActionListener
	{
		public void actionPerformed(ActionEvent event)
			{
			String msg = new String ("Welcome to Java Programming !!");
			if (event.getSource()==button1)
			System.out.println("Hello " + text1.getText() + " ! " + msg);
			//System.out.println(event.getWhen());
			//text1.setText(msg);
		}
	}
}

Output:

Step 1:

Java TextField and Button using Swing

Fig.: Java TextField and Button using Swing

 Step 2:

Java console screen output

Fig.: Output printed in Java Console after entering data

Download Now (.Zip File – 27KB)…

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

CommentLuv badge

Human Verification: In order to verify that you are a human and not a spam bot, please enter the answer into the following box below based on the instructions contained in the graphic.