import java.applet.Applet; import java.awt.*; import java.awt.event.*; /** * Demonstrates use of a doubly-linked list * * @author Mr J * @version 20050208 */ public class NameList extends Applet implements ActionListener { // GUI objects private TextField name = new TextField("Type a name here!"); private Button add = new Button("Add name"); private Button next = new Button("Next"); private Button prev = new Button("Previous"); private TextArea display = new TextArea(20, 30); private Label messages = new Label("Messages will appear here"); // data members DoubleNode head = null; DoubleNode current = null; /** * Add objects to the Applet */ public void init() { add(name); add(add); add(next); add(prev); add(display); add(display); add(messages); // Causes button presses to be detected add.addActionListener(this); next.addActionListener(this); prev.addActionListener(this); } /** * When an event occurs on an object with an ActionListener attached, this * method is carried out. * * @param e carries details about the event that occurred */ public void actionPerformed(ActionEvent e) { messages.setText(""); // Check the button presses if (e.getSource() == add) { addName(); } else if (e.getSource() == next) { displayList( 1 ); } else { displayList( -1 ); } } public void addName() { // get the name and create a new node at the head String theName = name.getText(); DoubleNode newOne = new DoubleNode( theName, head, null); // if head is pointing to a node, set it's previous pointer if (head != null) { head.setPrev(newOne); } head = newOne; // if no currently selected name, point to head if (current == null) { current = head; } displayList( 0 ); } public void displayList(int move) { display.setText("start\n-----\n"); // Move the currently selected, if required if (move == 1) { if (current.getNext() != null) { current = current.getNext(); } else { messages.setText("At last name"); } } else if (move == -1) { if (current.getPrev() != null) { current = current.getPrev(); } else { messages.setText("At first name"); } } DoubleNode temp = head; // "walk" down the list, using the temp pointer while (temp != null) { if (temp == current) { display.append(temp.getName() + "<< current\n"); } else { display.append(temp.getName() + "\n"); } temp = temp.getNext(); } } }