Java

Java JButton with Examples using NetBeans

Java JButton with Example:

A button can be implemented with the javax.swing.JButton class . This control is found in almost every application that allows you to perform a specific action. How to trigger an action by clicking a button will be covered in my next article in detail. At this point, we just want to cover how to display a JButton.


Java JButton Constructor:

In addition to the standard constructor, the java JButton class has a few other constructors that we would like to explain in more detail in the following table:

Constructor Description
JButton(Action a) Here, a Java JButton is directly assigned an action that is to be triggered when the button is clicked.
JButton(Icon icon) This constructor creates a JButton that displays an icon instead of a label. This usage is very common in toolbars (JToolBar). A typical example would be the “Save” button with the disk icon.
JButton(String text) this constructor is used to display the caption on java JButton.
JButton(String text, Icon icon) With the help of this constructor, the generated JButton object receives a text and an icon directly. The text appears behind the icon.



Example: How to display a Java JButton:

package com.mycompany.guiexamples;
import  javax.swing.* ;

/**
 *
 * @author Fawadkhan
 */
public class jButtonExample {
   public static void main(String arg[]) {
      JFrame myFrame = new JFrame("JButton Testing Example");
      myFrame.setSize(400, 350);
      myFrame.setLayout(null);
      // here i am Creating Button object
      JButton button = new JButton("Click");
      // this statement is used to Set the position and size of a button
      button.setBounds(130,150,120,40);
      //here i am adding the button to the frame
      myFrame.add(button);
      myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      myFrame.setLocationRelativeTo(null);
      myFrame.setVisible(true);
   }

}

when you compile and run the above source code, you will see the following output:

JButton



Program Explanation:

First, I create my JFrame object and set the title “JButton Testing Example”

JFrame myFrame = new JFrame("JButton Testing Example");

Then I set the frame size using the setSize method

myFrame.setSize(400, 350);

then I Create the object of the java JButton class  and set the caption as “Click”

JButton button = new JButton("Click");

Then I set the position and size of the button using setBound method. In this method first and the second argument is used for alignment (X, Y) and the third and fourth argument is used for sizing the button

button.setBounds(130,150,120,40);

then I add the button on the frame using add method of the Java JButton class

myFrame.add(button);


Java JButton Methods:

Below we present some methods of the Java JButton class:

Method Description
void addActionListener(ActionListener l) Assigns an ActionListener to the button. This is called when an ActionEvent (here: triggering the button) occurs on the relevant button.
void addChangeListener(ChangeListener l) Assigns a ChangeListener to the button. This is called when the state of the button changes.
int getHorizontalAlignment() Returns the horizontal alignment of text and icon.
int getHorizontalTextPosition() Returns the horizontal text position relative to the icon.
Icon getIcon() Returns the icon set for the button.
int getMnemonic()    Returns the set mnemonic (keyboard shortcut).
String getText( ) Returns the set text (label of the button).
int getVerticalAlignment()   Returns the vertical alignment of text and icon.
int getVerticalTextPosition() Returns the vertical alignment of the text relative to the icon.
boolean isSelected( ) Returns the state (selected / not selected) of the button.
void removeActionListener(ActionListener l) Removes the specified ActionListener.
void removeChangeListener(ChangeListener l) Removes the specified ChangeListener.
void setEnabled(boolean b) Enables (true) or disables (false) the button.
void setHorizontalAlignment(int alignment) Sets the horizontal alignment of text and icon. The integer values ​​for alignment are stored in the constants LEFT, RIGHT, CENTER, LEADING, and TRAILING, which JButton inherits from the javax.swing.SwingConstants class.
void setHorizontalTextPosition(int textPosition) Sets the horizontal alignment of the text in relation to the icon. 
void setIcon(Icon defaultIcon) Sets the icon that is displayed by default.
void setMnemonic(int mnemonic) Sets the shortcut key for the button. The respective character is underlined if it is contained in the button text. The integer values ​​for the individual keys are stored in the constants of the java.awt.event.KeyEvent class (eg KeyEvent.VK_U for the U key). If the ALT key is pressed in connection with the set abbreviation, the button is activated.
void setSelected(boolean b) Sets the state of the button (true for selected, false for not selected).
void setText(String text) Sets the text (label) of the button.
void setVerticalAlignment(int alignment) Sets the vertical alignment of text and icon.
void setVerticalTextPosition(int textPosition) Sets the vertical alignment of the text in relation to the icon. 


Example: Java JButton with ActionListener:

package com.mycompany.guiexamples;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

/**
 *
 * @author Fawadkhan
 */
public class jButtonExample {

    public static void main(String arg[]) {
        JFrame myFrame = new JFrame("JButton Testing Example");
        myFrame.setSize(400, 350);

        myFrame.setLayout(null);
        // here i am Creating Button object
        JButton button = new JButton("Click");
        // this statemen is used to Set the position and size of a button
        button.setBounds(130, 150, 120, 40);
        //here i am adding the butto to the frame
        myFrame.add(button);

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JDialog myJDialog = new JDialog();
                // title is set
                myJDialog.setTitle("Button Clicked");
                JLabel label = new JLabel("You Clicked the Button",
                        JLabel.CENTER);
                label.setVerticalAlignment(JLabel.TOP);
                label.setFont(new Font("Calibri", Font.BOLD, 25));

                myJDialog.setSize(300, 200);
                myJDialog.add(label);
                // Set dialog to modal
                myJDialog.setModal(true);
                myJDialog.setLocationRelativeTo(null);
                // We display our dialog 
                myJDialog.setVisible(true);

            }
        });

        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setLocationRelativeTo(null);
        myFrame.setVisible(true);

    }

}

By pressing the click button a dialog window will be opened as you can see in the below image. The dialog window code is placed in the addActionListener method. Whenever you clicked the button this code will be executed.

output:
JButton

JButton

Example of displaying an image on the button:

package com.mycompany.guiexamples;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

/**
 *
 * @author Fawadkhan
 */
public class jButtonExample {

    public static void main(String arg[]) {
        JFrame myFrame = new JFrame("JButton Testing Example");

        // here i Create java Button with image icon
        JButton button = new JButton(new ImageIcon("F:/icons/clickButton.png"));
        // this statement is used to Set the position and size of a button
        button.setBounds(60, 150, 388, 118);
        //this stataments is used to remove the button default color
        button.setBorderPainted(false);
        button.setContentAreaFilled(false);
        //here i am adding the button to the frame
        myFrame.add(button);

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JDialog myJDialog = new JDialog();
                // title is set
                myJDialog.setTitle("Button Clicked");
                // The width and height of the window are 

                JLabel label = new JLabel("You Clicked the Button",
                        JLabel.CENTER);
                label.setVerticalAlignment(JLabel.TOP);
                label.setFont(new Font("Calibri", Font.BOLD, 25));

                myJDialog.setSize(300, 200);
                myJDialog.add(label);
                // Set dialog to modal
                myJDialog.setModal(true);
                myJDialog.setLocationRelativeTo(null);
                // We display our dialog 
                myJDialog.setVisible(true);

            }
        });

        myFrame.setSize(500, 400);
        myFrame.setLayout(null);
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setLocationRelativeTo(null);
        myFrame.setVisible(true);

    }

}

output:

JButton

JButton



Program Explanation:

The rest of the code remains the same which I have previously explained. But in this example, I used the image icon on the java JButton. So I here created a Button with an image icon using ImageIcon class and pass the image path as an argument

JButton button = new JButton(new ImageIcon("F:/icons/clickButton.png"));

this statement is used to Set the position and size of a button first and the second argument is used for alignment, and the third and fourth argument is used for width and height

button.setBounds(60, 150, 388, 118);

these statements are used to remove the button’s default color and border

button.setBorderPainted(false);

button.setContentAreaFilled(false);

 

Related Articles

Leave a Reply

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

Back to top button