8 May 2011

Java Swing - Create Image JButton



Java Swing - Create Image JButton

First Create Image Panel Class:-

            First Create a class called ImagePanel.java. Then write the  code in it.

This is the class we have developed in last post. You can check it here --

After doing that work do as shown below...

We will use following images for JButton.

 Use For JButton when application starts

 Use For Selected and Disabled JButton

 Use For JButton Roll Over

 Use For JButton Pressed

Add These images to your projects. And write Below code.


Now Create ImageButton.java Class:-

                                                 This class is for create Jbutton and we can use it in any class later after to use the image JButton. 


So this class is the skeleton for JButton. Now when we want to add JButoon in our class then just create the instance of  ImageButton.java class and pass any image you want to use as JButton in its Constructor...and you will see the magic of Java Swing....

Write Below code for create JButton in your JFrame...


import javax.swing.*;

public class ImageCheck {
   
    public static void main(String s[])
    {
        ImagePanel panel = new ImagePanel(new
            ImageIcon("aa.jpg").getImage());
       
        JFrame frame = new JFrame("Create Image-" +
                        "Themed Components");
       
        frame.getContentPane().add(panel);
       
        final ImageButton button = new ImageButton(
            new ImageIcon("Warehouse.png"));
           
        button.setPressedIcon(new ImageIcon("" +
                        "ButtonPressed.png"));
        button.setRolloverIcon(new ImageIcon("" +
                        "ButtonRollover.png"));
        button.setSelectedIcon(new ImageIcon("" +
                        "Selected&Disabled.png"));           
        button.setDisabledIcon(new ImageIcon("" +
                        "Selected&Disabled.png"));
       
        button.setLocation(150,30);
        panel.add(button);
       
        frame.pack();
        frame.setDefaultCloseOperation(2);
        frame.setVisible(true);
    }
}

The output of this will look like....



Here you can see the button is a round image. When you will move mouse on it, the image will change as per our code..and look like a web application button in your window application....So try & Enjoy.........

Leave Comments if you like.....

3 comments:

  1. Thanks, it was most helpful =)

    ReplyDelete
  2. Thank you Anonymous for your comment..

    ReplyDelete
  3. AMAZING NIRAV very helpfull to me "I LIKE IT"..:)

    ReplyDelete

Leave Comment If You Like This...Thank You..!