Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to add Image button to a Frame using Swing API in Java ?

Program to demonstrate adding of Image Button to a Frame

package com.hubberspot.awtSwing.example;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonTest implements ActionListener
{
  JFrame frame;
  JButton button1, button2,button3;
  JTextField textfield;
  ButtonTest()
  {
    frame = new JFrame("Button Test");
    button1 = new JButton("Yes");
    button2 = new JButton("No");
    button3 = new JButton("Image Button", 
        new ImageIcon("c:\\smile.jpg"));
    button1.setMnemonic('Y');
    button2.setMnemonic('N');
    textfield = new JTextField(20);

    frame.setLayout(new FlowLayout());
    frame.add(textfield);
    frame.add(button1);
    frame.add(button2);
    frame.add(button3);

    button1.addActionListener(this);
    button2.addActionListener(this);

    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
   public void actionPerformed(ActionEvent event)
   {
     if(event.getSource()==button1)
       textfield.setText("You clicked YES");
     else
        textfield.setText("You clicked NO");
   }
   public static void main(String[] args)
   {
     new ButtonTest();
   }
}

Output of the program :






 
© 2021 Learn Java by Examples Template by Hubberspot