package com.aynu.layout;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DefaultListModelTest {
JFrame jf = new JFrame("测试DefaultListModel");
JTextField bookName = new JTextField(20);
JButton removeBtn = new JButton("删除选中的图书");
JButton addBtn = new JButton("添加指定图书");
//创建JList
JList<String> bookList;
DefaultListModel<String> model = new DefaultListModel<>();
public void init() {
//组装视图
model.addElement("水浒传");
model.addElement("西游记");
model.addElement("三国演义");
model.addElement("红楼梦");
bookList = new JList<>(model);
//设置JList
bookList.setVisibleRowCount(4);
//设置单选
bookList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jf.add(new JScrollPane(bookList));
//组装底部
addBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = bookName.getText();
if (!name.trim().equals("")) {
model.addElement(name);
}
}
});
removeBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int selectedIndex = bookList.getSelectedIndex();
if (selectedIndex >= 0) {
model.remove(selectedIndex);
}
}
});
JPanel bottonPanel = new JPanel();
bottonPanel.add(bookName);
bottonPanel.add(addBtn);
bottonPanel.add(removeBtn);
jf.add(bottonPanel, BorderLayout.SOUTH);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.pack();
jf.setVisible(true);
}
public static void main(String[] args) {
new DefaultListModelTest().init();
}
}