使用 JButton 在 Java 中创建自定义按钮
我正在尝试创建一个具有自定义形状(六边形)的按钮,但其他方面的行为与普通 JButton 一样(即,与 ActionListener 配合使用).
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).
我创建了一个扩展 AbstractButton 的类,但是当我单击它时,它似乎没有向 ActionListener 发送事件.如果我更改类以扩展 JButton,它可以完美运行,但会破坏按钮的显示方式.我假设有一个方法需要重写才能触发事件,但我不知道它是什么.
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.
您将不得不扩展 JButton
类而不是 AbstractButton
.尝试以下事情,你就会有想法.
You will have to extend JButton
class not AbstractButton
. Try the following things and you will get idea.
第一步是继承JButton
.
然后,在您的子类中,首先重新定义 paintComponent(Graphics)
方法.如果您想要任何更改.
Then, in your subclass, start by redefining the paintComponent(Graphics)
method. If you want any changes.
然后,覆盖 paintBorder(Graphics)
以赋予其六边形形状.
Then, override paintBorder(Graphics)
to give it a shape of hexagon.