Java Graphical User Interface(GUI): JButton Functions

in #utopian-io6 years ago (edited)

What Will I Learn?

  • The user will learn the concept of JButton.
  • The user will learn how to create a button.
  • The user will also learn how to associated the created button with an event.

Requirements

  • A computer System is required for this tutorial.
  • Java Software Development Kit(JDK) must be installed on your computer.
  • An Integrated Development Environment(IDE) such as Eclipse or NetBeans is required to be installed on your computer.

Get JDK here

Get Eclipse here

Get NetBeans here

Difficulty

The codes in this tutorial are around the same level as other tutorials so difficulty level will be same as others - Intermediate.

Tutorial Contents

So far, We have been learning about Swing Components like JLabel, JTextField, JFrame, and JPasswordField. The Swing class has many of these components which has J as its first letter. This brings us to another J Component and the subject of this tutorial.

JBUTTON

The JButton class is used to create a labeled button that has platform independent implementation. In simpler terms, it used to create a button on the screen, it proves the functionality of a push button. JButton allows the programmer to associate an icon, a string or both with the button.
When the button is clicked, an ActionEvent is generated leading to an action performed.

This tutorial, creates two JButton components and adds them to the screen. An event is associated with each button, when the user clicks the buttons, an event occurs displaying the clicked command to the screen using a showMessage Dialog from the JOptionPane class.

1.png

2.png

CODE BLOCK

BUTTON CLASS
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class Button extends JFrame {
    private JButton ok;
    private JButton cancel;
    public Button() {
        super("JButton Demo");
        setLayout(new FlowLayout());
        ok = new JButton("OK");
        add(ok, BorderLayout.CENTER);
        cancel = new JButton("Cancel");
        add(cancel, BorderLayout.CENTER);
        newClass handler = new newClass();
        ok.addActionListener(handler);
        cancel.addActionListener(handler);      
    }
    private class newClass implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            JOptionPane.showMessageDialog(null, String.format("You clicked %s button", event.getActionCommand()));
        }   
    }
}
BUTTONMAIN CLASS
import javax.swing.JFrame;
public class buttonMain {
    public static void main (String args []) {
        Button jbutton = new Button();
        jbutton.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jbutton.setSize(300,150);
        jbutton.setVisible(true);
    }
}

BUTTON CLASS

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;

These are Import Statements. Import Statements are used to reference methods that are in other packages. Java comes with a bunch of in built methods and these methods are in different packages. When the user imports a class, the user has access to all methods in the class because they are automatically imported.

public class Button extends JFrame {

This is the name of the current class. When you start a new class, it must be saved with a name. This class extends JFrame. In Java, it is possible for classes to inherit properties of another class. Here, this class inherits basic Frame properties like a window with close, maximize and minimize buttons from the JFrame class. The extends keyword is used to achieve this.

private JButton ok;

A variable declaration of JButton type to create a button. The private keyword is used here, this means that this variable can only be accessed from within this class and not from other classes.
Public keyword is used if the user wants the variable to be accessed from anywhere.
This is similar to variable declarations in other tutorials, the main difference here is the JButton type.

private JButton cancel;

Another variable declaration of JButton type to create a button. The private keyword is used here, this means that this variable can only be accessed from within this class and not from other classes.
Public keyword is used if the user wants the variable to be accessed from anywhere.

public Button() {

A Constructor is a block of code that lets you initialize variables immediately an object is created. Methods can be created and called later but with constructors, initialization is done immediately. Constructors have the same name as the class name and is called when an object of the class in created.
The above constructor does not carry any arguments and is created to hold the JButton components.

super(“JTextField Demo”);

The super keyword is used here to refer to properties of a superclass; in this case the JFrame class.
In this context, it is used to set the title of the newly created window. The title of the window is “JButton Demo”

setLayout(new FlowLayout());

The FlowLayout class. This provides a simple layout that is used by JFrame components.

ok = new JButton("OK");

The basic job of JButton is to display a labelled, clickable button to the screen. Here, the JButton object creates a Button with the Label “OK”.

add(ok);

The created JButton object is then added to the screen making it visible.

cancel = new JButton("Cancel");

A second clickable button is created with the label “Cancel”.

add(cancel);

This also adds the created “Cancel” JButton object is then added to the screen making it visible.

OBJECT OF NEW CLASS
handlerClass handler = new handlerClass();
        ok.addActionListener(handler);
        cancel.addActionListener(handler);

When the new class which implements the ActionListener interface is created, an object of the new class is also created. The

.addActionListerer[]

method is then used to pass execution instructions to the JBUTTON component.

EVENT LISTENER CLASS

private class newClass implements ActionListener {

ActionListener is an interface (not a class) that contains the single method below

public void actionPerformed( ActionEvent event)

A class that implements the interface must contain an actionPerformed() method. The ActionEvent parameter is an Event object that represents an event (a button click).

public void actionPerformed(ActionEvent event) {

This is the single method for the listener interface for receiving action events. The ActionEvent is a class and event is an instance of that class. ***event *** can be used to call it’s properties.

JOptionPane.showMessageDialog(null, String.format("You clicked %s button", event.getActionCommand()));

The .showMessageDialog method of String type used to display a message to the screen.

The .getActionCommand gives a String representing the action command. In this case, it will automatically give the value of the clicked button. This simply returns the command in the button that was clicked.

The Program displays a pop up showing what the user clicked.

BUTTONMAIN CLASS

import javax.swing.JFrame;

This is an import statement. This statement is used specifically to import the JFrame class from Application Program Interface (API). This allows the user to use all methods contained in it.

public class Main {

This is just like creating a new file or document and saving it with a name. This is the name of the new class created.

public static void main (String args []) {

The Java main method. Every program must contain this method in order to execute. It is the point from which the program begins execution.
A program without this method will not execute.

Button jbutton = new Button();

An Object of the JButton class is created. This enables the user to call in built GUI methods that will help to properly display the JButton component to the screen.

jbutton.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

This inbuilt method needs to be called before the program is run . This method states the default behavior of the windows when the “close”(x) button is clicked.
Here, it tells the window to close.

jbutton.setSize(350,150);

This is to set the size of the object to the specified width and height. In this case, the specified dimensions are (350,150).
Values of width and height are non-negative integers. The constructors that allow you to create a dimension do not prevent you from setting a negative value for these properties. If the value of width or height is negative, the behavior of some methods defined by other objects is undefined.

jbutton.setVisible(true);

This simply determines whether a component is displayed on the screen. It has two states. True and false.
With setVisible( false ), if the Component is not already marked invisible, setVisible calls invalidate() which invalidates the Container’s layout and the chain of parents since there is now more screen real estate in the Container and the positions of the siblings must be adjusted to flow into the freed space.

With setVisible( true ), if the Component is not already marked visible,setVisible calls invalidate() which invalidates the Container’s layout and the chain of parents since there is now less screen real estate in the Container and the positions of the siblings must be adjusted to squeeze in this new Component.

3.png

When the program is run, it displays the JButton components in a container. The two created buttons "OK" and "Cancel" can be clicked by the user.

4.png

When OK is clicked, an event occurs displaying a message to the screen.

5.png

When Cancel is clicked, an event occurs displaying a message to the screen.

6.png

7.png

8.png

Source Codes from GitHub Account.

You can get the codes here if you want to try it on your own.

REFERENCES

Curriculum

Similar posts already posted on Utopian are:



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @will-ugo I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

good writing I like. expand the work again, and more articles. hopefully a little science that you provide useful to the reader
do not forget to follow me @amirdesaingrafis

Congratulations! This post has been upvoted from the communal account, @minnowsupport, by will-ugo from the Minnow Support Project. It's a witness project run by aggroed, ausbitbank, teamsteem, theprophet0, someguy123, neoxian, followbtcnews, and netuoso. The goal is to help Steemit grow by supporting Minnows. Please find us at the Peace, Abundance, and Liberty Network (PALnet) Discord Channel. It's a completely public and open space to all members of the Steemit community who voluntarily choose to be there.

If you would like to delegate to the Minnow Support Project you can do so by clicking on the following links: 50SP, 100SP, 250SP, 500SP, 1000SP, 5000SP.
Be sure to leave at least 50SP undelegated on your account.