Button click java swing

Java JButton Tutorial with ActionListener Programming Examples

Java JButton in swing is used for performing action when clicked on it. This action might be getting data from input field, saving or retrieving data to database or performing and displaying calculation result in swing frame. Following classes and methods are used for implementing JButton in Swing.

Constructors

Constructor Description
JButton() It creates a button with no text and icon.
JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon object.

Methods

Methods Description
void setText(String s) It is used to set specified text on button
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener (ActionListener a) It is used to add the action listener to this object.
Читайте также:  Script doc to html

Programming Example

package Test.MainJava.com; import javax.swing.*; public class JButton_Example < public static void main(String[] args) < JFrame frame=new JFrame(); JButton b=new JButton("Click Me");//creating instance of JButton b.setBounds(140,100,120, 40);//x axis, y axis, width, height frame.add(b);//adding button in JFrame frame.setSize(400,500);//400 width and 500 height frame.setLayout(null);//using no layout managers frame.setVisible(true);//making the frame visible >>

output

Output:

Action Listener

This was the simple JButton example that performed nothing when clicking on it. Now, I will add action listener so, this button will perform some action on clicking.

package Test.MainJava.com; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public FirstAppxample < public static void main(String[] args) < JFrame frame=new JFrame(); JButton b=new JButton("Click Me");//creating instance of JButton b.setBounds(140,100,120, 40);//x axis, y axis, width, height b.addActionListener(new ActionListener() < public void actionPerformed(ActionEvent e) < JOptionPane.showMessageDialog(null, "Hello World"); >>); frame.add(b);//adding button in JFrame frame.setSize(400,500);//400 width and 500 height frame.setLayout(null);//using no layout managers frame.setVisible(true);//making the frame visible > >

Output

package Test.MainJava.com; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class JButton_Example < public static void main(String[] args) < JFrame frame=new JFrame(); JButton b=new JButton("Click Me");//creating instance of JButton b.setBounds(140,100,120, 40);//x axis, y axis, width, height b.addActionListener(new ActionListener() < public void actionPerformed(ActionEvent e) < showmessage(); >>); b.addActionListener(null); frame.add(b);//adding button in JFrame frame.setSize(400,500);//400 width and 500 height frame.setLayout(null);//using no layout managers frame.setVisible(true);//making the frame visible > public static void showmessage() < JOptionPane.showMessageDialog(null, "Hello World"); >>

Output

package Test.MainJava.com; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class JButton_Example < protected JButton b1, b2; protected JFrame frame; public void TrackButton() < b1=new JButton("Button1"); b1.setBounds(140,100,120,40); b1.addActionListener(actions); b2=new JButton("Button2"); b2.setBounds(140,150,120,40); b2.addActionListener(actions); frame=new JFrame(); frame.add(b1); frame.add(b2); frame.setSize(400, 500); frame.setLayout(null); frame.setVisible(true); >private ActionListener actions = new ActionListener() < @Override public void actionPerformed(ActionEvent e) < if(e.getSource() == b1) < msg1(); >else if(e.getSource() == b2) < msg2(); >> >; public void msg1() < JOptionPane.showMessageDialog(null, "I am Button 1"); >public void msg2() < JOptionPane.showMessageDialog(null, "I am Button 2"); >public static void main(String[] args) < JButton_Example jb=new JButton_Example(); jb.TrackButton(); >>

Output

Summary

In this tutorial you learn how to play with JButton in Swing Application. I have tried to explain JButton with suitable, easy and complete programming example. In the next chapter you will learn some inputs field of Swing like JTextField, JPasswordField, JTextArea and JLabel

Источник

Java Button Click Event Tutorial For Beginners-JButton ActionListener

Hello Friends, In this tutorial, you will learn about Java Button Click Event in Java Swing. In my previous tutorial, you have seen how to create the Java Button in Swing, and if you haven’t seen my previous tutorial yet, then you can click on the link given below.

So you have learned how to create a Button in Java, But You don’t know How to perform JButton on click action on button in Java Swing which means if you click on the button, nothing happens because you have not added any action event associated with the JButton. So now in this tutorial, you are going to learn about Java Button Click Event or we can say Java button pressed Event using the JFrame step by step.

So Let’s start our Tutorial Java Button Click Event in Java Swing or JButton Click Event using JFrame.

Watch Video Tutorial

  • 1 Java Button Click Event
    • 1.1 What is An Event ??
    • 1.2 Event Source
    • 1.3 Event Listener
    • 1.4 Event Classes
    • 1.5 Event Classes and Associated Listener Interfaces
    • 2.1 Importing Packages
    • 2.2 Creating a class MainClass.java
    • 2.3 Creating another class ActionEventDemo.java
    • 2.4 Adding Java Button to JFrame
    • 2.5 Implementing ActionListener Interface
    • 2.6 Registering ActionListener to the JButton
    • 2.7 Performing Action Event

    Java Button Click Event

    What is An Event ??

    • It is an object which describes a change in a source.
    • Basically they are associated with a component.
    • Some examples of the events are Java Button Pressed Event, entering a character via keyboard, selecting an item in a list , clicking the mouse etc.
    • Events are supported by number of packages including java.util, java.awt, java.awt.event .

    Event Source

    • A source is an object that generates an Event .
    • This happens when the internal state of the object changes in some way.
    • A source can generate one or more types of events.
    • A method getSource() is associated with all events which returns the object on which the event is initially occurred.

    Event Listener

    Event Classes

    • Classes that represent events.
    • EventObject is the superclass for all events which means it is the root of the Java event class hierarchy.
    • EventObject contains two methods. getSource() and toString().
    • getSource() method returns the source and toString() method returns the string equivalent of the event .
    • AWTEvent is a subclass of EventObject class and it is superclass for all AWT events .
    • Package java.awt.event is used for defining interfaces and classed that is used for event handling in AWT and SWING.
    • Some common event classes in the package java.awt.event are given below :

    Event Classes and Associated Listener Interfaces

    So this was the brief description of event classes and listeners, and now we will see Java Button Click Event or Swing JButton click action using JFrame step by step in which we will learn about the JButton ActionListener interface, ActionPerformed() method and addActionListener() method.

    Handling Java Swing Button Click Event Step by Step

    Importing Packages

    • In the first step, we need to import all essential packages. In this program, we need to import another new package java.awt.event because we are dealing with event handling and this package provides classes and interfaces that are used for event handling in awt and Swing.

    Creating a class MainClass.java

    • In this step, create a class (MainClass.java in this example), and inside that class, there will be our main method.

    Creating another class ActionEventDemo.java

    • In this step, create another separate class (ActionEventDemo.java in this example).
    • Now create an object of the JFrame class.
    • Create a user-defined method prepareGUI(), and inside that method we will set the properties of the JFrame class like its title, its location and size, its default close operation, its visibility etc.
    • We will also change the Layout Manager of the frame’s content pane to null. By default frame’s content pane uses BorderLayout Manager as its Layout Manager.
    • Now we will create the constructor of the class ActionEventDemo and inside that constructor call the prepareGUI() method.

    Java Button Click Event

    • Now save your program, compile it and run it.
    • As you can see that we have successfully created our JFrame.
    • In next step, we will add a Java button to our JFrame.

    Adding Java Button to JFrame

    • Create an object of the JButton class.
    • Now again create another user-defined method buttonProperties() and inside that method set the location and size of the JButton using setBounds() method and finally add the JButton to the JFrame using add() method.

    Java Button Click Event

    • Now save your program, compile it and run it.
    • As you can see that we have successfully created and added the JButton to the JFrame.
    • Now we want that when we click on the button, some activity should be performed which means how to make a JButton do something when JButton is clicked.
    • For this, first of all, we need to implement the JButton Listener which means ActionListener interface into our class so that we will be able to do some JButton click event..

    Implementing ActionListener Interface

    • If we have implemented the ActionListener interface in any class, then we must have to override its method which is actionPerformed(ActionEvent e) which takes a parameter ActionEvent (a class defined in package java.awt.event ). Now when someone clicks on the button the actionPerformed() method is called.
    • Now let’s implement the ActionListener interface into our class ActionEventDemo.

    Registering ActionListener to the JButton

    • In this step, we will add or can say register ActionListener to the JButton.
    • For this, we have to call addActionListner() method using the object of the JButton class. The parameter of the addActionListener() method is the object of that class in which ActionListener interface is implemented or can say in which we have defined actionPerformed() method. So if we are in the same class in which ActionListener interface is implemented, then we will pass this as an argument.

    Performing Action Event

    • Now we want that if we click on the button the background color of the frame’s content pane should be changed. For this, we will write the desired codes inside the actionPerformed() method. Which means the behaviour we want in response to the action is coded inside the actionPerformed() method.

    Java Button Click Event

    • Now save the program, compile it and run it.
    • Now we can see that as soon as we click on the button, the background color of the JFrame has been changed to pink.

    Frequently Asked Questions

    The Answer is “Action Event”. The associated Listener interface is the ActionListener interface. When the user clicks on the button then the button fires an Action Event and that results in invocation of the ActionListener’s acitonPerformed() method.

    Click here for the step by step tutorial on How to Open a new JFrame on Button Click in Java.

    The Answer is “actionPerformed()” method. This method is invoked automatically when the button is clicked, and you can define the specific actions you want to perform inside this method.

    The Answer is “addActionListener()” method. addActionListener() method registers the ActionListener to the Java Button and the behaviour we want in response to the action is coded inside the “actionPerformed() method. The actionPerformed() method is called just after the user executes any action.

    So, guys, I am wrapping up this tutorial “Java Button Click Event” in Java Swing and Feel free to drop us a comment if you find out something difficult to understand. After learning this, you can also learn how to create a Login Form in Java Swing and GUI Number Guessing Game in Java.

    People are also Reading…..

    • Best Java Books For Beginners
    • Menu Driven Program in Java Using Switch Case
    • How to Create Calculator in Java Swing
    • How to Create Tic Tac Toe Game in Java
    • How to Create Login Form in Java Swing
    • Registration Form In Java with Database Connectivity
    • How to Create Splash Screen In Java
    • How to Create Mp3 Player in Java
    • How to Connect MySQL Database in Java Using NetBeans
    • 11 Best Site to Learn Java Online for Free

    Источник

Оцените статью