Create a JLabel and place an image to your liking, in the texture you want and in the format you want. To simulate the effect of a button, overwrite the methods of mousePressed()
, mouseReleased()
and mouseMoved()
.
When you hover over the image you should check whether the current point is transparent or not, so that you do not change the image wrongly, since your JLabel remains a rectangle but the image does not. You should also check at the time of the mouse click, not to 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 should create an image for each state: imagem normal
, imagem clicada
and imagem com o mouse em cima
.
Here are examples I've created:
pawn (regular) .png
pawn(hovering).png
pawn (clicking) .png
PutthefollowingcodeinsideyourconstructortoimplementexactlythealgorithmIwroteabove:
finalImageIconregular=newImageIcon(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've moved the cursor to my hand when it's over a non-transparent area of JLabel.
I recently created a repository to make the complete project available on my GitHub , just download it and import it into Eclipse. All images are already in the repository for ease.