Java Swing Program to demonstrate JButton

Program

import javax.swing.*;
public class JButtonDemo
{
	public static void main(String args[])
	{
		JFrame frm = new JFrame("JButton Demo");
		JButton btnSubmit;
		btnSubmit = new JButton("Login");
		btnSubmit.setBounds(0, 0, 100, 50);
		frm.add(btnSubmit);
		frm.setSize(300, 300); 
		frm.setLayout(null);
		frm.setVisible(true);
		frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}

This Java Swing program demonstrates how to create and use a JButton in a graphical user interface (GUI). The program creates a simple window (JFrame) with a JButton labeled "Login". The button is positioned manually within the window, and when clicked, it can be used to trigger actions (though no event handling is implemented in this basic example).

  1. Imports:

    • The program imports the javax.swing.* package to use Swing components like JFrame and JButton.
  2. Creating the JFrame:

    • JFrame frm = new JFrame("JButton Demo"): Creates a window (frame) with the title "JButton Demo".
    • frm.setSize(300, 300): Sets the size of the window to 300x300 pixels.
    • frm.setLayout(null): Disables the default layout manager, allowing manual positioning of components (in this case, the button).
    • frm.setVisible(true): Makes the window visible when the program runs.
    • frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Ensures the program will terminate when the window is closed.
  3. Creating the JButton:

    • btnSubmit = new JButton("Login"): Creates a JButton with the label "Login" that will be displayed on the button.
    • btnSubmit.setBounds(0, 0, 100, 50): Sets the position and size of the button. The button is positioned at (0, 0) on the frame with a width of 100 pixels and height of 50 pixels.
  4. Adding the JButton to JFrame:

    • frm.add(btnSubmit): Adds the JButton to the frame.
  5. Key Swing Methods Used:

    • JButton("Label"): Creates a button with the specified label (text) to be displayed on the button.
    • setBounds(x, y, width, height): Sets the position and size of the button on the frame. The button is placed at the coordinates (0, 0) and has a width of 100 pixels and a height of 50 pixels.
    • add(Component component): Adds the button to the frame so that it appears in the GUI.
    • setVisible(true): Makes the frame visible to the user.
    • setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Closes the application when the window is closed.

Output

<img alt="Swing JButton with text" title="Swing JButton with text" src=/commons/images/posts/tutorials/jbutton-with-text-demo.png" />