Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Overriding paintcomponent method JButton

793881Apr 9 2010 — edited Apr 12 2010
Hi,

I'm trying to make my own buttons (with a JPEG image as template and a string painted on this template, depending on which button it is) by overriding the paintComponent-method of the JButton class, but I still have a small problem. I want to add some mouse-events like rollover and click and the appropriate animation with it (when going over the button, the color of the button becomes lighter, when clicking, the button is painted 2 pixels to the left and to the bottom). But my problem is there is some delay on these actions, if you move the mousepointer fast enough, the pointer can already be on another button before the previous button is restored to its original state. And of course, this isn't what I want to see.
I know you can use methods like setRollOverIcon(...), but if doing so, I think you need a lot of images ( for each different button at least 3) and I want to keep the number of images to a minimum.
I searched the internet and these forums for a solution, but I didn't found any. I'm quite sure there is at least one good tutorial on this since I already tried to do this once, but I forgot how to do it, and I can't find the tutorial anymore.

This is an example of the MyButton-class I already wrote, I hope it clarifies my problem:
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

public class MyButton extends JButton{
	
	BufferedImage button = null;
	int x, y;
	String text = "";
	
	MyButton(String t){
		super(t);
		text = t;
		setContentAreaFilled(false);
		setBorderPainted(false);
		setFocusPainted(false);
		addMouseListener(new MouseListener(){
			public void mouseClicked(MouseEvent arg0) {
				x += 2;
				y += 2;
			}
			public void mouseEntered(MouseEvent arg0) {
				//turn lighter
			}
			public void mouseExited(MouseEvent arg0) {
				x -= 2;
				y -= 2;
			}
			public void mousePressed(MouseEvent arg0) {}
			public void mouseReleased(MouseEvent arg0) {}
		});
	}
	
	protected void paintComponent(Graphics g){
		Graphics2D g2d = (Graphics2D)g;
		try{
			button = ImageIO.read(new File("Red_Button.jpg"));
		}catch(IOException ioe){}
		//Drawing JButton
		g2d.drawImage(button, null, x, y);
		g2d.drawString(text, x+5, y+5);	
	}
}
Thanks in advance,
Sam
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 10 2010
Added on Apr 9 2010
6 comments
836 views