如何在 Java 中制作非 Swing 按钮?

发布于 2024-10-10 15:26:53 字数 430 浏览 6 评论 0原文

我正在创建一个游戏,其中有一个带有多个视图的菜单,用于使用游戏状态转换来选择游戏类型、选项等。每个菜单都将在 Canvas 对象上的 JFrame 内主动呈现。由于我通过在 Canvas 上绘制 BufferedImage 来对每个游戏状态进行主动渲染,因此我无法使用 JButton 或任何其他< em>JComponent 或 Component (awt),因为 Graphics2D 对象无法像这样绘制它们:

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

如何实现可以接收鼠标输入并使用 Graphics2D 对象绘制的自定义按钮?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

荭秂 2024-10-17 15:26:53

向您正在绘制的组件添加一个鼠标侦听器,并让它确定鼠标单击是否位于您想要成为按钮的区域。

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.

挖鼻大婶 2024-10-17 15:26:53

为什么要在已经使用 Swing 的应用程序中使用 Canvas(JFrame 就是 Swing)?

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

但这真的真的真的很丑!

你为什么不拿一个 JPanel 呢?据我所知,您可以覆盖 Paint 方法以仅调用 update 方法,这样面板就不会被清除(但我已经使用 Java 有一段时间了)。然后,您可以使用在更新方法中作为参数获得的 Graphics2D 来绘制内容,它甚至允许您向其中添加自己的按钮和其他内容...

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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文