简体   繁体   English

JList在Java中显示空行

[英]JList showing empty lines in Java

I have a following array: 我有以下数组:

static String[] nameData = new String[100];

And a JList , with displays the array's contents: 还有一个JList ,它显示数组的内容:

rightPanel.add(Box.createRigidArea(new Dimension(20, 20)));
final JList list = new JList(nameData);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setLayoutOrientation(JList.VERTICAL);
list.setVisibleRowCount(-1);
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(250, 80));
listScroller.setAlignmentX(LEFT_ALIGNMENT);
rightPanel.add(listScroller);

But when for example only first slot in the array are filled and rest are with the value null, JList still displays them as an empty line and lets you select it (I have added an image below). 但是,例如,当仅填充数组中的第一个插槽,而其余插槽的值为null时, JList仍将它们显示为空行并让您选择它(我在下面添加了图片)。

数组中的第7个元素

This is how a 7th element in array would be selected, although I would like the JList only to display elements that have a value besides null. 这是在数组中选择第7个元素的方式,尽管我希望JList仅显示具有null值以外的元素。

I think you need to read tutorial for JList . 我认为您需要阅读JList教程。

You add new String[100] to your list, because of it has 100 values. 您将new String[100]添加到列表中,因为它具有100个值。 You can filter your array before adding to JList or ListModel for getting only notNull and notEmpty values. 您可以在添加到JList或ListModel之前对数组进行过滤,以仅获取notNull和notEmpty值。

If you dont want to display null/empty values, you can either create another String by removing null entries or the more preferable option, use a DefaultListModel 如果您不想显示null / empty值,则可以通过删除null条目来创建另一个String,或者使用更可取的选项,使用DefaultListModel

Create another String 创建另一个字符串

int i=0;
for(i=0;i<nameData.length;i++){
    if(nameData[i]==null) break;   // count number of elements
}
String[] myString = new String[i];  // declare string
for(i=0;i<myString.length;i++){
    myString[i] = nameData[i];      // copy
}
// Create JList
final JList list = new JList(nameData);

Or 要么

Use DefaultListModel 使用DefaultListModel

DefaultListModel model = new DefaultListModel();
for(int i=0;i<nameData.length;i++){
    if(nameData[i]==null) break;
    model.addElement(nameData[i]);   // build defaultlistmodel
}
final JList list = new JList();
list.setModel(model);

那是因为您使用100个null元素组成的数组,所以可以使用Vector代替

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM