Java JButton create image button

Description

Java JButton create image button


// Demonstrate an icon-based JButton. 
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

class Demo extends JPanel implements ActionListener {
  JLabel jlab;//from   w w w  . j a  va 2 s . c o m

  public Demo() {

    // Change to flow layout.
    setLayout(new FlowLayout());

    // Add buttons to content pane.
    ImageIcon i1 = new ImageIcon("1.png");
    JButton jb = new JButton(i1);
    jb.setActionCommand("Hourglass");
    jb.addActionListener(this);
    add(jb);

    ImageIcon i2 = new ImageIcon("2.png");
    jb = new JButton(i2);
    jb.setActionCommand("Analog Clock");
    jb.addActionListener(this);
    add(jb);

    ImageIcon i3 = new ImageIcon("3.png");
    jb = new JButton(i3);
    jb.setActionCommand("Digital Clock");
    jb.addActionListener(this);
    add(jb);

    ImageIcon i4 = new ImageIcon("4.png");
    jb = new JButton(i4);
    jb.setActionCommand("Stopwatch");
    jb.addActionListener(this);
    add(jb);

    // Create and add the label to content pane.
    jlab = new JLabel("Choose a Timepiece");
    add(jlab);
  }

  // Handle button events.
  public void actionPerformed(ActionEvent ae) {
    jlab.setText("You selected " + ae.getActionCommand());
  }

}

public class Main {
  public static void main(String[] args) {
    Demo panel = new Demo();

    JFrame application = new JFrame();

    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    application.add(panel);
    application.setSize(250, 250);
    application.setVisible(true);
  }
}



PreviousNext

Related