[JAVA100例]014、下拉列表
时间:2011-01-08
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/**
* <p>Title: 列表框</p>
* <p>Description: 通过输入框添加元素和点击“删除”按钮删除列表元素</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: ListDemo.java</p>
* @version 1.0
*/
public class ListDemo extends JPanel
implements ListSelectionListener {
private JList list;
private DefaultListModel listModel;
private static final String hireString = "添加";
private static final String fireString = "删除";
private JButton fireButton;
private JTextField employeeName;
public ListDemo() {
super(new BorderLayout());
//构建List的列表元素
listModel = new DefaultListModel();
listModel.addElement("Alan Sommerer");
listModel.addElement("Alison Huml");
listModel.addElement("Kathy Walrath");
listModel.addElement("Lisa Friendly");
listModel.addElement("Mary Campione");
listModel.addElement("Sharon Zakhour");
//创建一个List构件,并将列表元素添加到列表中
list = new JList(listModel);
//设置选择模式为单选
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//初始化选择索引在0的位置,即第一个元素
list.setSelectedIndex(0);
list.addListSelectionListener(this);
//设置列表可以同时看5个元素
list.setVisibleRowCount(5);
//给列表添加一个滑动块
JScrollPane listScrollPane = new JScrollPane(list);
JButton hireButton = new JButton(hireString);
HireListener hireListener = new HireListener(hireButton);
hireButton.setActionCommand(hireString);
hireButton.addActionListener(hireListener);
hireButton.setEnabled(false);
fireButton = new JButton(fireString);
fireButton.setActionCommand(fireString);
fireButton.addActionListener(new FireListener());
employeeName = new JTextField(10);
employeeName.addActionListener(hireListener);
employeeName.getDocument().addDocumentListener(hireListener);
String name = listModel.getElementAt(
list.getSelectedIndex()).toString();
//创建一个面板
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane,
BoxLayout.LINE_AXIS));
buttonPane.add(fireButton);
buttonPane.add(Box.createHorizontalStrut(5));
buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
buttonPane.add(Box.createHorizontalStrut(5));
buttonPane.add(employeeName);
buttonPane.add(hireButton);
buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
add(listScrollPane, BorderLayout.CENTER);
add(buttonPane, BorderLayout.PAGE_END);
}
/**
*<br>类说明
|