Create Swing Buttons using JButton

Here is a tutorial illustrating javax.swing.JButton class in Java used to create buttons.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class JButtonDemo extends JFrame
{
JButton button1,button2;
    public JButtonDemo()
    {
    setTitle("JButton Demo - I am the default title!");
    setSize(400,400);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(new FlowLayout());

    button1=new JButton("Click me!");
    button1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
            setTitle("You clicked me!");
            getContentPane().setBackground(Color.red);
            }
        });
    button2=new JButton("Click me too!");
    button2.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
            setTitle("You clicked me too!");
            getContentPane().setBackground(Color.blue);
            }
        });
    add(button1);
    add(button2);
    }
    public static void main(String args[])
    {
    new JButtonDemo();
    }

}

getContentPane(): By default, we cannot apply background to a JFrame so we use this method to get the container of the JFrame and paint the background on it.
ActionListener(){}: An anonymous inner class is written for ease because only we've got two buttons.
javax.swing.*: Import everything from swing package, including JFrame, JButton
java.awt.event.*: Everything to handle the events. Here ActionListener and ActionEvent
java.awt.*: For Color and FlowLayout class here.

-----------------------------------
Output
-----------------------------------


Posted by at on

Tags: Swing Components,