Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

How to Make Image Button

Posted on 2001-07-02
11
Medium Priority
?
310 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
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 90 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses

972 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