Java编程——单词排序
1 //WordSort.java 2 package javaapplication3; 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 import javax.swing.event.*; 7 import java.util.*; 8 import javax.swing.text.Document; 9 10 public class WordSort extends JFrame implements DocumentListener,ActionListener{ 11 JTextArea text1,text2; 12 JButton buttonClear; 13 WordSort(){ 14 setBounds(100,100,350,300); 15 setVisible(true); 16 validate(); 17 18 setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 19 text1=new JTextArea(20,15); 20 text2=new JTextArea(20,15); 21 buttonClear=new JButton("清空"); 22 text1.setLineWrap(true); 23 text1.setWrapStyleWord(true); 24 text2.setLineWrap(true); 25 text2.setWrapStyleWord(true); 26 add(text1); 27 add(text2); 28 add(buttonClear); 29 text2.setEditable(false); 30 Box box1=Box.createHorizontalBox(); 31 Box box2=Box.createHorizontalBox(); 32 box1.add(new JLabel("请输入单词:")); 33 box1.add(new JScrollPane(text1)); 34 box2.add(new JLabel("排序后的单词序列:")); 35 box2.add(new JScrollPane(text2)); 36 Box box3=Box.createHorizontalBox(); 37 box3.add(box1); 38 box3.add(box2); 39 Container con=getContentPane(); 40 con.add(box3,BorderLayout.SOUTH); 41 con.validate(); 42 text1.getDocument().addDocumentListener(this); 43 44 buttonClear.addActionListener(this); 45 } 46 public void insertUpdate(DocumentEvent e){ 47 handle(); 48 } 49 public void removeUpdate(DocumentEvent e){ 50 handle(); 51 } 52 public void changedUpdate(DocumentEvent e){ 53 handle(); 54 } 55 public void handle(){ 56 String s=text1.getText(); 57 StringTokenizer fenxi=new StringTokenizer(s,",\n"); 58 int n=fenxi.countTokens(); 59 String a[]=new String[n]; 60 for(int i=0;i<=n-1;i++){ 61 String temp=fenxi.nextToken(); 62 a[i]=temp; 63 } 64 Arrays.sort(a); 65 text2.setText(null); 66 for(int i=0;i<n;i++){ 67 text2.append(a[i]+"\n"); 68 } 69 } 70 public void actionPerformed(ActionEvent e){ 71 text1.setText(null);} 72 public static void main(String args[]){ 73 WordSort win=new WordSort(); 74 } 75 } 76