//Required by ActionListener.
public void actionPerformed(ActionEvent e) {
String name = ename.getText();
//User didn't type in a unique name...
if (name.equals("") || alreadyInList(name)) {
Toolkit.getDefaultToolkit().beep();
ename.requestFocusInWindow();
ename.selectAll();
return;
}
int index = list.getSelectedIndex();
if (index == -1) {
index = 0;
} else {
index++;
}
listModel.insertElementAt(ename.getText(), index);
//Reset the text field.
ename.requestFocusInWindow();
ename.setText("");
//Select the new item and make it visible.
list.setSelectedIndex(index);
list.ensureIndexIsVisible(index);
}
protected boolean alreadyInList(String name) {
return listModel.contains(name);
}
//Required by DocumentListener.
public void insertUpdate(DocumentEvent e) {
enableButton();
}
//Required by DocumentListener.
public void removeUpdate(DocumentEvent e) {
handleEmptyTextField(e);
}
//Required by DocumentListener.
public void changedUpdate(DocumentEvent e) {
if (!handleEmptyTextField(e)) {
enableButton();
}
}
private void enableButton() {
if (!alreadyEnabled) {
button.setEnabled(true);
}
}
private boolean handleEmptyTextField(DocumentEvent e) {
if (e.getDocument().getLength() <= 0) {
button.setEnabled(false);
alreadyEnabled = false;
return true;
}
return false;
}
}
//This method is required by ListSelectionListener.
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {
if (list.getSelectedIndex() == -1) {
//No selection, disable deleteButton.
deleteButton.setEnabled(false);
} else {
//Selection, enable the deleteButton button.
deleteButton.setEnabled(true);
}
}
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Single list example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new SingleList();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
frame.setSize(300,200);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
-------------------------------------------
Read for more information.
http://www.roseindia.net/java/Thanks.