《Java2图形设计卷II:Swing》配套光盘源码
源代码在线查看: test.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import java.io.FileReader;
public class Test extends JApplet {
private JTextArea textArea = new JTextArea();
private Container contentPane = getContentPane();
public void init() {
readFile(textArea, "text");
contentPane.add(new ControlPanel(), BorderLayout.NORTH);
contentPane.add(new JScrollPane(textArea),
BorderLayout.CENTER);
}
private void readFile(JTextComponent textComponent,String s) {
try { (new DefaultEditorKit()).read(
new FileReader(s), textComponent.getDocument(), 0);
} catch(Exception ex) { ex.printStackTrace(); }
}
class ControlPanel extends JPanel {
JRadioButton radioButtons[] = new JRadioButton[] {
new JRadioButton("wrap off"),
new JRadioButton("wrap characters"),
new JRadioButton("wrap words"),
};
public ControlPanel() {
ButtonGroup group = new ButtonGroup();
Listener listener = new Listener();
for(int i=0; i < radioButtons.length; ++i) {
JRadioButton b = radioButtons[i];
b.addActionListener(listener);
group.add(b);
add(b);
if(i == 0)
b.setSelected(true); // "wrap off"
}
}
class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
textArea.setLineWrap(!action.equals("wrap off"));
textArea.setWrapStyleWord(
action.equals("wrap words"));
//textArea.repaint();
showStatus("rows: " + textArea.getRows() +
", columns: " + textArea.getColumns() +
", lines: " + textArea.getLineCount());
}
};
}
}