[英]How do I delete a row from a JList without leaving a blank space in its place?
如何從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();
}
您將需要一個自定義ListModel
,這將允許您維護可用項目數量的“虛擬”計數
當你刪除一個項目(我會從管理這個ListModel
,因為你需要無論如何觸發更新事件),則需要折疊陣列,之前移動所有的元素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));
哪個輸出...
[A, B, C, D, E, F, G, H]
[A, B, C, D, F, G, H, null]
然后,您將需要減少List
模型的“虛擬”計數,以便它報告正確的項目數...
或者,您也可以硬着頭皮,使用List
和DefaultListModel
處理所有此類問題...
或者您可以控制並制作自己的專用ListModel
...
public class EmployeeListModel extends AbstractListModel<Employee> {
private List<Employee> employees;
public EmployeeListModel(List<Employee> employees) {
this.employees = employees;
}
@Override
public int getSize() {
return employees.size();
}
@Override
public Employee getElementAt(int index) {
return employees.get(index);
}
public void delete(Employee employee) {
delete(employees.indexOf(employee));
}
public void delete(int index) {
employees.remove(index);
fireIntervalRemoved(this, index, index);
}
}
有關更多詳細信息,請參見如何使用列表
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.