JButton被禁用后会重新启用自己 [英] JButtons re-enable themselves after being disabled
问题描述
我有一个JButton数组,它们构成一个键盘接口.输入六个数字后,我要禁用键盘,以便用户无法再输入数字.
I have an array of JButtons which form a keypad interface. After six numbers are entered I want to disable the keypad so that no further numbers can be entered by the user.
我已经编写了代码,并且按钮一直处于禁用状态,直到鼠标悬停在它们中的任何一个上方,然后按钮才能重新启用自身并运行添加到其中的actionEvents.
I have written the code and the buttons do disable until the mouse hovers above any of them, then the buttons seem to re-enable themselves and run actionEvents added to them.
完整的代码可在此处.
我认为可能是错误的事情.
Possible things that I think are wrong.
- 设置我的
button.setEnabled(false);
时会忽略某种MouseListener.
- 我没有正确地将属性与
buildGUI();
分开,我只是这样做了,以便内部类可以访问它们. - 可能与
gridLayout
有关,因为禁用了似乎按钮以使其适用于我的services
JPanel按钮.
- There is some sort of MouseListener which is ignoring when I set
button.setEnabled(false);
- I haven't separated attributes from the
buildGUI();
correctly, I only did this anyway so that the inner class could access them. - Possibly something to do with the
gridLayout
as disabling the buttons seems to work for myservices
JPanel buttons.
推荐答案
问题在于如何实例化Frame(CashMachine
),而不是(直接)实例化其实现.
The problem lies in how you instantiated your Frame (CashMachine
), not (directly) with its implementation.
您要两次调用buildGUI
,一次在对象的构造函数中,然后在Driver
类中实例化该对象.结果,您正在创建(并布置)两组按钮.
You are calling buildGUI
twice, one in the object's constructor, and then in the Driver
class that instantiates the object. As a result, you are creating (and laying out) two sets of buttons.
当第一组按钮最终被禁用时,您的鼠标活动显示了第二组按钮.而且ActionListener实现中的缺陷可能导致inputCount
的值大于6,因此第二组按钮最终不会像第一组按钮那样被禁用.
When the buttons of the first set were eventually disabled, your mousing activity was revealing the second set of buttons. And a flaw in your ActionListener implementation can cause inputCount
to take on values greater than 6, so buttons in the second set were not eventually disabled like those from the first set.
buildGUI
应该是私有的;应该在CashMachine构造函数中调用它,而不是在您的Driver
类中调用它.
buildGUI
should be private; it should be called in the CashMachine constructor, and not by your Driver
class.
相反,在我看来,CashMachine.setVisible
应该由Driver
类而不是CashMachine
构造函数调用.
Conversely, in my opinion, CashMachine.setVisible
should be called by the Driver
class, and not by the CashMachine
constructor.
这篇关于JButton被禁用后会重新启用自己的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!