Swing高级组件JList:动态增加删除list元素

动态增加list元素依靠ListModel类来实现。元素值通过properties文件的值保存,以分号间隔
	/**
* 添加邮箱地址按钮
*
* **/
private void jButton3ActionPerformed(ActionEvent evt) {
String address = jTextField_addMail.getText().trim();

if (!address.isEmpty()) {
Vector dataVector = new Vector();
ListModel listDataModel = mailAddrList.getModel();
StringBuffer write2File = new StringBuffer();
for (int i = 0; i < listDataModel.getSize(); i++) {
String s = (String) listDataModel.getElementAt(i);
dataVector.add(s);
write2File = write2File.append(";" + s);
}
if (address != null && !address.isEmpty()) {
dataVector.add(address);
write2File.append(";" + address); //写进配置文件的字符串
}
while (write2File.toString().startsWith(";"))
write2File = write2File.replace(0, 1, ""); //就是去掉";"
mailAddrList.setListData(dataVector);

SettingsAction.setProperty(path, "MailAddr", write2File
.toString());
JOptionPane.showMessageDialog(null, "添加并保存成功。", "提示",
JOptionPane.INFORMATION_MESSAGE);
}
}

/**
* 删除邮箱list选择项按钮动作
*
* **/
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

if (!mailAddrList.isSelectionEmpty()) {
initMailAddrList();
mailAddr = mailAddr.replace((String) mailAddrList.getSelectedValue(), "");
while (mailAddr.contains(";;"))
mailAddr = mailAddr.replace(";;", ";");
try { //同步写入文件
SettingsAction.setProperty(path, "MailAddr", mailAddr
.startsWith(";") ? mailAddr.substring(1) : mailAddr);
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "发生未知错误,请重试。", "提示",
JOptionPane.INFORMATION_MESSAGE);
}
Vector dataVector = new Vector();
ListModel listDataModel = mailAddrList.getModel();
for (int i = 0; i < listDataModel.getSize(); i++) {
String s = (String) listDataModel.getElementAt(i);
if (!((String) mailAddrList.getSelectedValue()).equals(s)) //排除所选项
dataVector.add(s);
}
mailAddrList.setListData(dataVector);
JOptionPane.showMessageDialog(null, "删除并保存成功。", "提示",
JOptionPane.INFORMATION_MESSAGE);
}
}



	private JList mailAddrList;
private JTextField jTextField_addMail;
private String mailAddr;
private Properties pros = new Properties();
private String path = System.getProperty("user.dir")
+ "\\src\\conf.properties";


初始化一些全局变量
	private void initMailAddrList() {
FileInputStream fis = new FileInputStream(path);
pros.load(fis);
mailAddr = (String) pros.get("MailAddr");
fis.close();
}


初始化List通过一个匿名内部类实现:
		mailAddrList.setModel(AbstractListModel() {
String[] strings = mailAddr.split(";");

public int getSize() {
return strings.length;
}

public Object getElementAt(int i) {
return strings[i];
}
});

你可能感兴趣的:(Swing高级组件JList:动态增加删除list元素)