看看满意不:
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*;
public class SortApplet extends JApplet { public void init() { Container contentPane = getContentPane(); contentPane.add(new SortPanel()); } }
class SortPanel extends JPanel { public SortPanel() { Box box1 = Box.createHorizontalBox(); box1.add(new JLabel("请输入数字 ")); text_input = new JTextField(15); text_input.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { sortTheNumbers(); } }); box1.add(text_input);
Box box2 = Box.createHorizontalBox(); box2.add(new JLabel("顺序排序后 ")); text_result = new JTextArea(); text_result.setEditable(false); box2.add(text_result);
Box box = Box.createVerticalBox(); box.add(box1); box.add(Box.createVerticalStrut(10)); box.add(box2);
add(box); }
public void sortTheNumbers() { String input = text_input.getText(); StringTokenizer token = new StringTokenizer(input, " ,", false); float[] numbers = new float[token.countTokens()]; for(int i = 0; token.hasMoreTokens(); i++) { try { numbers[i] = Float.parseFloat(token.nextToken()); } catch(NumberFormatException e) { text_result.setText("请输入数字,并以逗号或空格分开。"); return; } }
Arrays.sort(numbers);
StringBuffer buffer = new StringBuffer(); for(int i = 0; i < numbers.length; i++) buffer.append(numbers[i] + " "); text_result.setText(buffer.toString()); }
private JTextField text_input; private JTextArea text_result; }