How can I make a button without Swing in Java?

I am creating a game in which I have a menu with several views for choosing the type of game, parameters, etc., using transitions of the game state. Each of the menus will be actively displayed in JFrame objects on the Canvas. Since I am doing active rendering in every state of the game, drawing a BufferedImage on Canvas, I cannot use JButton or any other JComponent or Component (awt), because the Graphics2D object cannot draw them as:

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

How can I implement a custom button that can accept mouse input and draw using a Graphics2D object?

+4
source share
2 answers

Add a mouse listener to the component you are using and determine if the mouse click was in the area in which you want to be a button or not.

+1
source

Why are you using Canvas in an application that already uses Swing (JFrame is Swing)?

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

But it really is really really ugly!

Why aren't you taking JPanel? Afaik, you can overwrite the paint method to just call the update method so that the panel does not clear (but some time has passed when I was playing with Java). Then you can use Graphics2D, which you get as an argument in the update method, to draw the material, and it allows you to add your own buttons and other things to it ...

0
source

Source: https://habr.com/ru/post/1334368/


All Articles