Image as a JButton

I am still not able to  make a image a JButton after all the help in previous post.

Thanks to my poor Java Knowledge.

Can some one please help more on this ? May be some little code snippet.

I am trying to make a image act as a JButton and not to insert a image in a button.

Thanks !
hipalAsked:
Who is Participating?
 
ksivananthConnect With a Mentor Commented:
you can simply use JButton/JLabel and set this as icon with empty border and it will just seem like an image in the UI!
0
 
objectsCommented:
thats going to be a fair bit of work to do properly.
far easier to use existing JButton class
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
CEHJCommented:
Can you attach an image you'd like to use?
0
 
hipalAuthor Commented:
Thanks everyone.

@CEHJ, Please find the pic attached. Or you can just use any pic.

I have to make a lot of buttons using different pics.
pic.png
0
 
CEHJConnect With a Mentor Commented:
Try the following
import java.awt.*;
import java.awt.event.*;

import java.io.*;

import java.util.*;

import javax.swing.*;


public class F extends JFrame {
    private void setGui() {
	try {
	    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    Container cp = getContentPane();
	    cp.setLayout(new FlowLayout());
	    JButton b = new JButton();
	    b.setIcon(new ImageIcon("pic.png"));
	    b.setBorder(null);
	    b.setContentAreaFilled(false);
	    cp.add(b);
	    b.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent e) {
		    System.out.println("Clicked");
		}
	    });
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

    public static void main(String[] args) {
	try {
	    SwingUtilities.invokeAndWait(new Runnable() {
		public void run() {
		    F f = new F();
		    f.setGui();
		    f.pack();
		    f.setVisible(true);
		}
	    });
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }
}

Open in new window

0
 
CEHJCommented:
>>you can simply use JButton/JLabel and set this as icon with empty border

An empty border isn't sufficient actually
0
 
hipalAuthor Commented:
yes, we need to set the contentfillarea too .. :(

I just realized that ksiv.suggested just to make border zero ..

Anyways ....
0
 
objectsCommented:
that what I had already suggested ;)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.