BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Swing – JButton tutorial and examples

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

JButton class is used for adding platform independent buttons to a swing application. In this tutorial we will learn how to create a button in Swing application and how to tweak their appearance as per the requirement. I have also shared some code snippets that may be useful for you while developing a Swing application.

Swing JButton Example

This example shows how to create a button in a Swing application and how to add it to a frame. Along with this, we will see various methods of JButton class.

import javax.swing.JButton;  
import javax.swing.JFrame;  
public class JButtonExample {
    JButtonExample(){  
        /* JFrame is a top level container (window)
         * where we would be adding our button
         */
        JFrame frame=new JFrame();  
                          
        // Creating Button          
        JButton b=new JButton("Click Me..");
        /* This method specifies the location and size
         * of button. In method setBounds(x, y, width, height)
         * x,y) are cordinates from the top left 
         * corner and remaining two arguments are the width
         * and height of the button.
         */
        b.setBounds(50,50,90, 50);  
             
        //Adding button onto the frame
        frame.add(b);  
                  
        // Setting Frame size. This is the window size
        frame.setSize(300,200);  
        
        frame.setLayout(null);  
        frame.setVisible(true);  
                  
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
                  
    }  
              
     public static void main(String[] args) {  
            new JButtonExample();  
     }  
}

Output:

Jbutton example - Swing

Some Useful JButton examples

You would find some useful code snippets in this section that you can use in your projects.

1) Adding image to JButton

The simplest way is this:

JButton b=new JButton(new ImageIcon("imageName.png"));

The above statement would work if you have the image in the folder where your Swing program files are stored.
However if you have image in some other folder then do like this:
For example if you have programs in “src” folder and image in “src/resources” folder then code it like this: This is the recommended way of adding image/icons to your buttons as this will reduce the chances of any ambiguities further.

JButton button = new JButton();
try {
    Image img = ImageIO.read(getClass().getResource("resources/myimage.png"));
    button.setIcon(new ImageIcon(img));
} catch (IOException ex) {
  }

Here is the complete code: Here I have a image play.gif placed in the folder where my program files are.

import java.awt.Image;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.*;

public class JButtonIcon {
    JButtonIcon(){  
        /* JFrame is a top level container (window)
         * where we would be adding our button
         */
        JFrame frame=new JFrame();  
                          
        // Creating Button          
        JButton b = new JButton();
        try {
            Image img = ImageIO.read(getClass().getResource("play.gif"));
            b.setIcon(new ImageIcon(img));
          } catch (IOException ex) {
          }
        
        b.setBounds(50,50,90, 50);  
             
        //Adding button onto the frame
        frame.add(b);  
                  
        // Setting Frame size. This is the window size
        frame.setSize(300,200);  
        
        frame.setLayout(null);  
        frame.setVisible(true);  
                  
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
                  
    }  
              
    public static void main(String[] args) {  
            new JButtonIcon();  
    }  
}

Output:

Adding image/icon to JButton example

Top Related Articles:

  1. Java AWT tutorial for beginners
  2. Java – How to Convert a String to ArrayList
  3. Nested or Inner interfaces in Java
  4. How to install Eclipse on Mac OS X
  5. Method References in Java 8

Tags: Java-Swing

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

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

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap