/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:
* 作 者: 臧鹏
* 完成日期: 2013 年 8月 26日
* 版 本 号: 001
* 对任务及求解方法的描述部分
* 输入描述:
* 问题描述:1,在项目中创建窗体类SortArray。在窗体中添加一个文本框,一个文本域和一个“排序”按钮。
* 2,为“排序”按钮编写事件处理方法,在该方法中要接收用户的输入字符串,并以字符串中的空格字符分割字符串为数组
* 再把字符串数组转换为整数数组,然后调用Arrays类的sort()方法对其进行排序,最后显示到窗体中。
* 程序输出:
* 程序头部的注释结束
*/
import java.awt.BorderLayout;
public class 使用sort方法对数组进行排序 extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
使用sort方法对数组进行排序 frame = new 使用sort方法对数组进行排序();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public 使用sort方法对数组进行排序() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("\u7528\u6237\u8F93\u5165\u4E00\u7EC4\u6570\u636E");
lblNewLabel.setBounds(10, 10, 414, 24);
contentPane.add(lblNewLabel);
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
char key = e.getKeyChar(); //获取用户输入的字符
String mark = "0123456789"+(char)8; //定义规范化字符模板
if(mark.indexOf(key) == -1){ //判断输入的字符是否属于规范化模板字符
e.consume(); //取消非规范化字符的有效性
textField.setText(" ");
}
}
});
textField.setBounds(10, 44, 414, 21);
contentPane.add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("\u4F7F\u7528sort\u6392\u5E8F");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = textField.getText(); //获取输入
String[] str = text.split(" "); //拆分输入为数组
int[] array = new int [str.length]; //创建整数类型
textArea.setText("数组原有内容\n");
for(String str1 :str){
textArea.append(str1+" ");
}
for(int i = 0;i<array.length;i++){
array[i] = Integer.parseInt(str[i]);
}
textArea.append("\n");
Arrays.sort(array); //使用sort方法对整型数组进行排序
textArea.append("排序后的数组是:\n");
for(int value:array){ //输出排序后的数组
textArea.append(value+" ");
}
}
});
btnNewButton.setBounds(144, 89, 150, 23);
contentPane.add(btnNewButton);
textArea = new JTextArea();
textArea.setBounds(10, 122, 414, 130);
contentPane.add(textArea);
}
}
使用sort方法对数组进行排序
最新推荐文章于 2024-07-27 21:14:19 发布