VisualizingLinkedListsApplet
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class VisualizingLinkedListsApplet extends Applet
implements ActionListener,
ItemListener {
String[] imageName = { "original", "empty","addLast","addFirst",
"add", "removeFirst", "removeLast", "remove" };
List imageList;
TextField inputImg;
Label inputLabel;
Button imageButton[];
DrawPanel drawPanel;
Panel buttonPanel;
Panel promptPanel;
public void init() {
buttonPanel = new Panel();
promptPanel = new Panel();
drawPanel = new DrawPanel();
drawPanel.imageDisp = getImage(getCodeBase(), imageName[0] + ".gif");
setLayout(new BorderLayout());
buttonPanel.setLayout(new GridLayout(1,8));
promptPanel.setLayout(new FlowLayout(FlowLayout.LEFT,10,10));
imageButton = new Button[imageName.length];
imageList = new List(imageName.length);
inputLabel = new Label("Type operation and press return");
inputImg = new TextField(20);
add("Center",drawPanel);
for (int i = 0; i < imageName.length; i++) {
imageButton[i] = new Button(imageName[i]);
buttonPanel.add(imageButton[i]);
imageButton[i].addActionListener(this);
}
add("North",buttonPanel);
for (int i = 0; i < imageName.length; i++)
imageList.add(imageName[i]);
add("East",imageList);
imageList.addItemListener(this);
promptPanel.add(inputLabel);
promptPanel.add(inputImg);
add("South",promptPanel);
// anonymous inner class
inputImg.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
drawPanel.imageDisp = getImage(getCodeBase(), inputImg.getText() + ".gif");
inputImg.setText("");
drawPanel.repaint();
}
}
);
}
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < imageButton.length; i++)
if (e.getSource().equals(imageButton[i])) {
drawPanel.imageDisp = getImage(getCodeBase(), imageName[i] + ".gif");
drawPanel.repaint();
}
}
public void itemStateChanged(ItemEvent ie) {
drawPanel.imageDisp= getImage(getCodeBase(), imageList.getSelectedItem() + ".gif");
drawPanel.repaint();
}
}
customized panel DrawPanel
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class DrawPanel extends Panel implements MouseListener {
public Image imageDisp;
private Point lineStart = new Point(0, 0); // Line start point
private Graphics g; // Create a Graphics object for drawing
public DrawPanel() {
setBackground(Color.white);
addMouseMotionListener(
new MouseMotionAdapter() {
public void mouseDragged( MouseEvent e ) {
g = getGraphics(); // Get graphics context
g.setColor(Color.red);
g.drawLine(lineStart.x, lineStart.y,
e.getX(), e.getY());
lineStart.move(e.getX(), e.getY());
// Dispose this graphics context
g.dispose();
}
}
);
addMouseListener(this);
}
public void paint(Graphics g) {
g.drawImage(imageDisp, 10, 10,this);
}
public void mousePressed(MouseEvent e) {
lineStart.move(e.getX(), e.getY());
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
}