问题描述
我需要你对以下任务的建议和指导。
I need your suggestions and guidence on following task.
我有一个框架有两个JComboBox,假设它们被命名为combo1和combo2,一个JTable和其他组件。
I have a frame which has two JComboBoxes supposed they are named combo1 and combo2, a JTable and other components.
在使用上面的组件可见框架的初始阶段。 combo1组合框中填充了一些值,但在初始阶段没有选择任何值,combo2组合框被禁用,表格为空。
At initial stage when frame is visible with above component. The combo1 combobox is filled with some values but no value is selected at initial stage, the combo2 combobox is disabled and the table is empty.
我在combo1上添加了一个actionListener以及combo2。 combo1中有两种类型的值,假设这些值是type1和type2。
I have added an actionListener on combo1 as well as combo2. There are two types of values in combo1 suppose those values are type1 and type2.
条件1:
当我们从Combo1中选择值type1时,将调用actionListener方法combo1调用combo2保持禁用的方法,并将一些行添加到与combo1中所选值type1相关的表。
Condition 1: When we selects value type1 from Combo1 the actionListener method is called of combo1 which invokes a method which combo2 remains disabled and adds some rows to table related to selected value type1 from combo1.
条件2:当我们选择值时
从combo1中调用type2的actionListener方法调用combo1,该方法调用一个方法,该方法使combo2填充了与type2相关的一些值并启用但没有从combo2中选择任何值,并且在我们从combo2中选择任何值之前,表也应保持为空。
Condition 2: when we selects value type2 from combo1 the actionListener method is called of combo1 which invokes a method who makes combo2 filled with some values related to type2 and gets enabled but no value is selected from combo2 and table also should remain empty until we selects any value from combo2.
表每增加一次combo2值,combo2的动作侦听器方法就会被触发。在combo2的actionListener方法中获取combo2选择的值,但是这里没有选择的combo2值导致NullPointerException。
table at every addition of value to combo2 the action listener method of combo2 is gets fired. In actionListener method of combo2 which gets combo2 selected value but here there is no selected value of combo2 which leads to a NullPointerException.
那么我应该怎么做动作列表器方法在向combo2添加值后,combo2将不会被执行。
So what should I do that the action listner method of combo2 will not be get executed after addition of an values to combo2.
推荐答案
您可以在添加之前删除动作侦听器新元素,并在完成后将其添加回来。 Swing是单线程的,因此无需担心需要触发监听器的其他线程。
You could remove the action listener before you add the new elements, and add it back once you're done . Swing is single threaded so there is no need to worry about other threads needing to fire the listener.
您的监听器可能还会检查是否选择了某些内容并采取适当的措施不。比获得NPE更好。
Your listener could probably also check if something is selected and take appropriate action if not. Better than getting a NPE.
这篇关于如何在java中动态添加项目时,如何避免触发JComboBox的actionlistener事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!