Question

I am creating a game in which I have a menu with multiple views for selecting game type, options, etc. using game state transitions. Each of the menus will be actively rendered within a JFrame on Canvas objects. Since I am doing active rendering on every game state by drawing a BufferedImage to the Canvas, I can't use the JButton or any other JComponent or Component (awt) because the Graphics2D object can't draw them like:

Graphics2D g = bufferStrategy.getDrawGraphics();
g.draw(new JButton("Click me"));

How can I implement a custom button that can receive mouse input and be drawn with a Graphics2D object?

Was it helpful?

Solution

Add a mouse listener to the component you are drawling on and have it determine if a mouse click was in the area that you want to be a button or not.

OTHER TIPS

Why would you use a Canvas in an application that is already using Swing (JFrame is Swing)?

BufferedImage image = new BufferedImage(blah....)
Graphics2D gfx = image.createGraphics();
JButton but = new JButton("Click me");
but.update(gfx);

But that's really really really ugly !

Why don't you take a JPanel? Afaik you can overwrite the paint method to just call the update method so the panel doesn't get cleared (but it has been a while that I was playing with Java). Then you can use the Graphics2D you get as argument in the update method to draw stuff and it allows you to even add your own buttons and other stuff to it...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top