如何在不放置空格的情况下从JList中删除行? 现在它将删除我需要它的部分,但是会在jlist中留下一个空格。
以下是我的代码的一些部分:
private final DefaultListModel model = new DefaultListModel();
protected JList myList = new JList(model);;
protected static String employee[] = new String[100];
protected String list[];
public EmployeeGUI()
{
scrollPane.setViewportView(myList);
populate();
myList = new JList(list);
myList.setFixedCellHeight(30);
myList.setFixedCellWidth(100);
myList.addListSelectionListener(this);
public int getIndex()
{
int idx = myList.getSelectedIndex();
return idx;
}
public void populate()
{
list = new String [Employee.count];
for(int i = 0; i < Employee.count; i++)
{
if(Employee.employeeArray[i] != null)
list[i] = Employee.employeeArray[i].getName();
}
}
@Override
public void actionPerformed(ActionEvent e)
{
else if(e.getSource() ==jbtDelete)
{
String k = JOptionPane.showInputDialog(null, "Are you sure you want"
+ " to delete?\n1: Yes\n2: No", "Delete",2);
switch(k)
{
case "1":
{
int idx = getIndex();
list[idx] = null;
Employee.deleteEmployee(idx);
//populate();
myList.setListData(list);
if (idx<0) return;
text2.setText(null);
text3.setText(null);
text4.setText(null);
text5.setText(null);
text6.setText(null);
text7.setText(null);
text10.setText(null);
type.setSelectedItem("No Type");
insurance.setSelectedItem("None");
break;
}
case "2":
break;
default:
JOptionPane.showMessageDialog(null, "Invalid Selection!",
"INVALID",1);
}
}
}
}
public static void deleteEmployee(int a)
{
employeeArray[a] = null;
//count--;
sortEmployees();
}
答案 0 :(得分:2)
您将需要一个自定义ListModel
,这将允许您维护一个虚拟的&#34;可用项目数量
删除项目时(我会从ListModel
进行管理,因为您还需要触发更新事件),您需要折叠数组,移动所有元素{{1下一个插槽,例如......
a
哪些输出......
String list[] = new String[]{"A", "B", "C", "D", "E", "F", "G", "H"};
int a = 4;
System.out.println(Arrays.toString(list));
System.arraycopy(list, a + 1, list, a, list.length - a - 1);
list[list.length - 1] = null;
System.out.println(Arrays.toString(list));
然后你需要减少&#34;虚拟&#34; [A, B, C, D, E, F, G, H]
[A, B, C, D, F, G, H, null]
模型的计数,以便报告正确的项目数...
或者你可以咬紧牙关并使用List
和List
处理所有这类东西...
或者你可以控制自己的专属DefaultListModel
...
ListModel
有关详细信息,请参阅How to Use Lists