我有一个JComboBox与DefaultComboBoxModel这些的IntegerS:
{null, 1, 2, 3, 4, 5, 6, 7, 8, 9}
Run Code Online (Sandbox Code Playgroud)
说我5在我JComboBox和我点击JComboBox并选择2,然后下面的程序将显示:
5 ->
-> 2
Run Code Online (Sandbox Code Playgroud)
这是程序:
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import static java.lang.System.out;
public class Test {
public static void main(String[] args){
final JComboBox<Integer> cb = new JComboBox<>();
cb.setModel(new DefaultComboBoxModel<>(new Integer[]{null, 1, 2, 3, 4, 5, 6, 7, 8, 9}));
cb.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
switch (e.getStateChange()) {
case ItemEvent.DESELECTED:
out.format("%s ->\n", e.getItem());
break;
case ItemEvent.SELECTED:
out.format(" -> %s\n", e.getItem());
break;
}
}
});
final JFrame win = new JFrame();
win.setBounds(800,400,30,70);
win.add(cb);
win.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
win.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
我不清楚的是,为什么当值最初null(并且它是,因为它是模型数组中的第一个值)时,输出是
-> 3
Run Code Online (Sandbox Code Playgroud)
意思是ItemListener被称为一次,只有一个ItemEvent.SELECTED州.为什么不是用所谓ItemEvent.DESELECTED的null(如印刷null ->),与数字?
它也是另一种方式,如果我最初5进入JComboBox并且我选择了空值(即null),那么我在控制台中看到的只有:
5 ->
Run Code Online (Sandbox Code Playgroud)
那么为什么JComboBox忽略null值会出现?文档似乎没有说什么.
你说的是真的,我能看到的是在JCombobox课堂上的setSelectedItem方法:
if (anObject != null && !isEditable()) {
// For non editable combo boxes, an invalid selection
// will be rejected.
boolean found = false;
for (int i = 0; i < dataModel.getSize(); i++) {
E element = dataModel.getElementAt(i);
if (anObject.equals(element)) {
found = true;
objectToSelect = element;
break;
}
}
if (!found) {
return;
}
}
Run Code Online (Sandbox Code Playgroud)
它没有设定objectToSelect.
所以在DefaultComboBoxModel实现setSelectedItem方法中传递null并且它不调用fireContentsChanged事件.
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |