使用 JButton 在 Java 中创建自定义按钮
我正在尝试创建一个具有自定义形状(六边形)的按钮,但在其他方面的行为就像普通的 JButton 一样(即与 ActionListener 一起使用)。
我创建了一个扩展 AbstractButton 的类,但当我单击它时,它似乎没有向 ActionListener 发送事件。如果我更改类来扩展 JButton,它会完美运行,但会破坏按钮的显示方式。我假设有一个方法需要重写才能触发事件,但我不知道它是什么。
I am trying to create a button that has a custom shape (hexagon), but otherwise acts like a normal JButton would (that is, works with an ActionListener).
I have created a class that extends AbstractButton, but it doesn't seem to be sending events to the ActionListener when I click it. If I change the class to extend JButton it works perfectly, but it screws up the way the button is displayed. I'm assuming that there is a method that I need to override to get it to fire events, but I can't figure out what it is.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想创建 CustomButtonUI,那么您必须
深入了解
BasicXxxUI
。覆盖JButton 的颜色列表
请注意,没有
paintComponent()
。这是错误的,只需使用paint()
方法,如果可能的话,下面只是一个简单的示例(对于 Metal JButton)。请注意,仅对于 Metal LaF,我太懒了,没有关于覆盖 PaintText、paintIcon、paintFocus、paintBorder 的内容(对于所有功能,您必须检查 BasicButtonUI 中的可用方法),以及我放入 ButtonModel 的内容,只是为了我的享受。
If you want to create a CustomButtonUI then you have to look
deepest to the
BasicXxxUI
.overide List of Colors from JButton
Note there isn't
paintComponent()
. It's wrong, just use thepaint()
method,Below is just a simple example if that is possible (for Metal JButton). Note just for Metal LaF, I'm so lazy and there isn't something about override paintText, paintIcon, paintFocus, paintBorder (for all funcionalities you have to check available methods from BasicButtonUI), and something I put to the ButtonModel, just for my enjoyment.
您必须扩展
JButton
类而不是AbstractButton
。尝试以下操作,您就会有所了解。第一步是子类化
JButton
。然后,在您的子类中,首先重新定义
paintComponent(Graphics)
方法。如果你想要任何改变。然后,重写
paintBorder(Graphics)
以赋予其六边形形状。You will have to extend
JButton
class notAbstractButton
. Try the following things and you will get idea.The first move is to subclass
JButton
.Then, in your subclass, start by redefining the
paintComponent(Graphics)
method. If you want any changes.Then, override
paintBorder(Graphics)
to give it a shape of hexagon.我知道这个问题已经得到解答,但您可能想看看使用内置方法,并使用图像在不同状态下绘制按钮。
这是我用来生成自定义按钮的一些代码。
然后,您可以像往常一样向其添加操作侦听器。
I know this question has been answered, but you might want to look at using the built-in methods, and using images to draw your button in different states.
Here is a bit of code I used to generate a custom button.
You can then add an action listener to it as normal.
尝试使用 Jlabel 并使用任何形状的图像!
try a Jlabel and use an image for any shape!!