Solved

How to Make Image Button

Posted on 2001-07-02
11
286 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
Comment Utility
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
Comment Utility
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
Comment Utility
> 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
 
LVL 92

Expert Comment

by:objects
Comment Utility
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
Comment Utility
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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 92

Expert Comment

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

Author Comment

by:prasadtvsv
Comment Utility
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
Comment Utility
Have you tried:

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

as I suggested above?


0
 
LVL 1

Expert Comment

by:poluru
Comment Utility
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
Comment Utility
poluru,

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

Author Comment

by:prasadtvsv
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Performance issue while iterating with streams 5 39
Updating Java 9 87
@SBGen Method 3 25
Java Timer (static) 9 9
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
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 learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

772 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