• The JButton

    The JButton is the actual button of applications. Use JButton to send actions to your application whenever a user clicks the button.

    Example

    package com.javapointers.javase;
    
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    
    /**
     *
     * @author javapointers
     */
    public class JButtonTest implements ActionListener{
        JFrame frame;
        JButton button;
        
        public JButtonTest(){
            frame = new JFrame();
            frame.setTitle("My JFrame");
            frame.setSize(500, 400);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            button = new JButton("Click Me!");
            button.addActionListener(this);
            
            frame.setLayout(new FlowLayout());
            frame.add(button);
            frame.setVisible(true);
        }
        
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("You have click the button");
        }
        
        public static void main(String args[]){
            JButtonTest test = new JButtonTest();
        }
    }
    
    
    

    When we run the program, the output will be:

    and when the user click on the button, the string “You have click the button” will be displayed in the console.
    Explanation:

    1. import javax.swing.JButton – import the JButton class to be able to use.
    2. button = new JButton(“Click Me!”) – Create a new instance of JButton with label Click Me!
    3. button.addActionListener(this) -Adds action when the user clicks the button.
    4. frame.setLayout(new FlowLayout()) – Define how java will layout your components. You will learn more about layout manager later on this tutorial.
    5. frame.add(button) – add the our button to the frame.
    6. public void actionPerformed(ActionEvent e) – the method that will be called when the user click the button.

    Related Post