《Java2图形设计卷II:Swing》配套光盘源码
源代码在线查看: test.java
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.undo.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Test extends JApplet {
private TextFieldPanel panel = new TextFieldPanel();
private StateEdit stateEdit;
private JButton startButton = new JButton("Start Edit"),
endButton = new JButton("End Edit"),
undoButton = new JButton("Undo");
public void init() {
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(startButton);
contentPane.add(endButton);
contentPane.add(undoButton);
contentPane.add(panel);
endButton.setEnabled(false);
undoButton.setEnabled(false);
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stateEdit = new StateEdit(panel);
endButton.setEnabled(true);
startButton.setEnabled(false);
}
});
endButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stateEdit.end();
undoButton.setEnabled(true);
endButton.setEnabled(false);
}
});
undoButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = undoButton.getText();
boolean isUndo = name.equals("Undo");
if(isUndo) stateEdit.undo();
else stateEdit.redo();
undoButton.setText(isUndo ? "Redo" : "Undo");
}
});
}
}
class TextFieldPanel extends JPanel implements StateEditable {
JTextField[] fields = new JTextField[] {
new JTextField("text field 1"),
new JTextField("text field 2"),
new JTextField("text field 3"),
new JTextField("text field 4"),
};
public TextFieldPanel() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
for(int i=0; i < fields.length; ++i)
add(fields[i]);
}
public void storeState(Hashtable hashtable) {
for(int i=0; i < fields.length; ++i)
hashtable.put(fields[i], fields[i].getText());
}
public void restoreState(Hashtable hashtable) {
Enumeration keys = hashtable.keys();
while(keys.hasMoreElements()) {
JTextField field = (JTextField)keys.nextElement();
field.setText((String)hashtable.get(field));
}
}
}