Java JButton create button with an icon.

Introduction

To add icon to JButton, use Java ImageIcon class which supports GIF, JPEG, or PNG image.

import java.awt.FlowLayout;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main extends JFrame {

  public Main() {
    super("demo from demo2s.com");
    //from   w  w w .  j a v a2s  .c o m
    // Create icons
    Icon icon = new ImageIcon("icon.png");
    JButton closeButton = new JButton("Close", icon);
    
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    setLayout(new FlowLayout());

    getContentPane().add(closeButton);

    closeButton.addActionListener(e -> System.exit(0));
  }

  public static void main(String[] args) {
    Main frame = new Main();
    frame.pack();
    frame.setVisible(true);
  }
}



PreviousNext

Related