Solved

How to Make Image Button

Posted on 2001-07-02
11
292 Views
Last Modified: 2012-05-04
Dear Friends



I want to make a gif/jpeg or any image work as a button.
When i am creating a button using
JButton my = new JButton("my.gif");

the image is coming on the button but some gap is coming in between the button and the image. I want that the gif should exactly work as a button.

bye
prasad
0
Comment
Question by:prasadtvsv
  • 5
  • 2
  • 2
  • +2
11 Comments
 
LVL 6

Expert Comment

by:jpk041897
ID: 6247301
One way you could do it is creating your own component.

The following applet sample code, from Exploring Java, O'Rilley should get you started:

import java.awt.*;
import java.awt.event.*;
public class PictureButtonApplet extends java.applet.Applet implements ActionListener {
    Image image;
    public void init() {
        image = getImage( getClass().getResource(getParameter("image")) );
        PictureButton pictureButton = new PictureButton( image );
        add ( pictureButton );
        pictureButton.setActionCommand("Aaargh!");
        pictureButton.addActionListener( this );
    }
   
    public void actionPerformed( ActionEvent e ) {
        System.out.println( e );
    }
}
class PictureButton extends Component {
    private Image image;
    boolean pressed = false;
    ActionListener actionListener;
    String actionCommand;
    PictureButton(Image image) {
        this.image = image;
        MediaTracker mt = new MediaTracker(this);
        mt.addImage( image, 0 );
        try { mt.waitForAll(); } catch (InterruptedException e) { /* error */ };
        setSize( image.getWidth(null), image.getHeight(null) );
        enableEvents( AWTEvent.MOUSE_EVENT_MASK );
    }
    public void paint( Graphics g ) {
        g.setColor(Color.white);
        int width = getSize().width, height = getSize().height;
        int offset = pressed ? -2 : 0;  // fake depth
        g.drawImage( image, offset, offset, width, height, this );
        g.draw3DRect(0, 0, width-1, height-1, !pressed);
        g.draw3DRect(1, 1, width-3, height-3, !pressed);
    }
    public Dimension getPreferredSize() {
        return getSize();
    }
    public void processEvent( AWTEvent e ) {
        if ( e.getID() == MouseEvent.MOUSE_PRESSED ) {
            pressed = true;
            repaint();
        } else
        if ( e.getID() == MouseEvent.MOUSE_RELEASED ) {
            pressed = false;
            repaint();
            fireEvent();
        }
        super.processEvent(e);
    }
    public void setActionCommand( String actionCommand ) {
        this.actionCommand = actionCommand;
    }
    public void addActionListener(ActionListener l) {
        actionListener = AWTEventMulticaster.add(actionListener, l);
    }
    public void removeActionListener(ActionListener l) {
        actionListener = AWTEventMulticaster.remove(actionListener, l);
    }
    private void fireEvent() {
        if (actionListener != null) {
            ActionEvent event = new ActionEvent( this,
                                ActionEvent.ACTION_PERFORMED, actionCommand );
            actionListener.actionPerformed( event );
        }
    }
}
0
 
LVL 1

Expert Comment

by:poluru
ID: 6247368
hi,
anyway u r using swings...
so u can use this code

import javax.swing.*;
public class ImageButton extends JFrame
{
     public static void main(String args[])
     {
          new ImageButton();
     }
     public ImageButton()
     {
          super("ImageButton");
          setSize(200,200);
          JButton jb=new JButton(new ImageIcon("my.gif"));
          getContentPane().add(jb);
          setVisible(true);
     }
}
0
 
LVL 92

Expert Comment

by:objects
ID: 6247465
> JButton my = new JButton("my.gif");

Is this a typo?
That'll create a button with the LABEL 'my.gif'.
It won't display the image.
0
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 
LVL 92

Expert Comment

by:objects
ID: 6247479
I'm geussing your actually using passing an Icon to the ctor.
To get rid of the 'gap', try the following:

button.setMargin(new Insets(0, 0, 0, 0));
0
 
LVL 1

Accepted Solution

by:
tonus earned 30 total points
ID: 6247984
This is in addition to what objects mentioned above:

    Image image = Toolkit.getDefaultToolkit().createImage("F:\\Netscape\\Server4\\docs\\images\\save_on.gif");
    MediaTracker traker = new MediaTracker(frame);
    traker.addImage(image,0);
    traker.waitForAll();
    JButton button = new JButton(new ImageIcon(image));

    //remove the border
    button.setBorderPainted(false);    

    //No painting on click of the image
    button.setContentAreaFilled(false);

    //remove the pads inside the button
    button.setMargin(new Insets(0, 0, 0, 0));
0
 
LVL 92

Expert Comment

by:objects
ID: 6248004
You don't need to use MediaTracker for ImageIcon's, they already handle it internally.
0
 

Author Comment

by:prasadtvsv
ID: 6251321
Dear poluru's



what my problem is that only u suggested me.
ys i am using swing and


JButton my = new JButton("my.gif");
what i was refereing is the one what u gave .
I used the ImageIcon only.
Byut the problem is i am not getting the complete image as button there is some gap coming in between so it is looking as that we have placed an image on the button. but what i want is that the image itself look as button
JButton jb=new JButton(new ImageIcon("my.gif"));



so pls get me the solution.


bye
prasad
0
 
LVL 92

Expert Comment

by:objects
ID: 6251371
Have you tried:

button.setMargin(new Insets(0, 0, 0, 0));

as I suggested above?


0
 
LVL 1

Expert Comment

by:poluru
ID: 6251467
oh sorry,
i misunderstood ur problem.
ok..as they told u can use if u want to display just the image....

button.setMargin(new Insets(0,0,0,0));
button.setBorderPainted(false);

0
 
LVL 92

Expert Comment

by:objects
ID: 6251520
poluru,

Can we please be a little bit original.
If you don't have anything new to add .....
0
 

Author Comment

by:prasadtvsv
ID: 6254330
Dear Friends

Thanxs a lot for ur support.
Dear Objects u were very near to my problem but only after adding the code of tonus only my problem solved.
Thanxs to all of you .

Dear friends after doing this i lot the dynamism of the button it lokks like static can anyone tell how to make it dynamism that is the image shows button action when i click it and leave it.If anyone can help it i will give 30 more points.

bye
prasad
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Protect jar file - windows app 2 50
groupSum5 challenge 5 84
groupSumClump challenge 9 115
mysql jsp example issue 32 32
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

815 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now