Create a Jlabel and place an image to your liking, the texture you want and the format you want. To simulate the effect of a button override the methods of mousePressed()
, mouseReleased()
and mouseMoved()
.
When passing the mouse over the image one must check whether the current point is transparent or not, not to change the image erroneously, since its Jlabel remains a rectangle however the image does not. You should also check at mouse click, to not allow the Jlabel to be clicked if the mouse is over a transparent area of the image.
To correctly simulate the behavior of a button you must create an image for each state: imagem normal
, imagem clicada
and imagem com o mouse em cima
.
Here are examples I created:
Pawn(regular). png
Pawn(hovering). png
Pawn(clicking). png
Put the following code inside your constructor to implement exactly the algorithm I wrote above:
final ImageIcon regular = new ImageIcon(ClassLoader.getSystemResource("pawn(regular).png"));
final ImageIcon hovering = new ImageIcon(ClassLoader.getSystemResource("pawn(hovering).png"));
final ImageIcon clicking = new ImageIcon(ClassLoader.getSystemResource("pawn(clicking).png"));
final BufferedImage img = ImageIO.read(ClassLoader.getSystemResource("pawn(regular).png"));
final JLabel lblNewLabel = new JLabel(regular);
lblNewLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int pixel = img.getRGB(e.getPoint().x, e.getPoint().y);
if( (pixel>>24) == 0x00 ) {
return;
}
else {
System.out.println("I was clicked! I really look like a button.");
lblNewLabel.setIcon(clicking);
}
super.mousePressed(e);
}
@Override
public void mouseReleased(MouseEvent e) {
int pixel = img.getRGB(e.getPoint().x, e.getPoint().y);
if( (pixel>>24) == 0x00 ) {
lblNewLabel.setIcon(regular);
}
else {
lblNewLabel.setIcon(hovering);
}
super.mouseReleased(e);
}
});
lblNewLabel.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
int pixel = img.getRGB(e.getPoint().x, e.getPoint().y);
if( (pixel>>24) == 0x00 ) {
lblNewLabel.setIcon(regular);
lblNewLabel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
else {
lblNewLabel.setIcon(hovering);
lblNewLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
super.mouseMoved(e);
}
});
contentPane.add(lblNewLabel);
To make it cooler I changed the cursor to little hand when I’m over a non-transparent Jlabel area.
I recently created a repository to make complete project on my Github, just download it and import it into Eclipse. All images are already in the repository for ease.
Are you using Swing? is a desktop application?
– Lucio
Yes, I’m in the swing library, it’s for desktop normally, a little game!
– Isaac Reinaldo
@Isaacreinaldo added a link in my reply to the full project on Github, in case you had difficulties running the code, now it’s easier.
– Math