编写一个应用程序,用户分别从两个文本框输入学生的姓名和分数,程序按成绩排序将这些学生的姓名和分数显示在一个文本区中。
程序运行代码如下:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Student extends JFrame {
JLabel lname,lscore;//姓名和成绩标签
JTextField tname,tscore; //文本框
JTextArea show; //用于显示的文本区域
JButton button;
JPanel pan;
Map<String,String> studentMap,resultMap;
public static void main(String[] args) {
new Student();
}
public Student() {
initialize();//初始化
click();//点击
}
public void initialize() {
lname=new JLabel("姓名");
lscore=new JLabel("成绩");
tname =new JTextField(10);
tscore=new JTextField(10);
button=new JButton("确定");
pan=new JPanel();
show=new JTextArea();
pan.add(lname);
pan.add(lscore);
pan.add(tname);
pan.add(tscore);
pan.add(button);
add(pan, BorderLayout.NORTH);
add(show,BorderLayout.CENTER);
setTitle("统计学生姓名和分数:");//设置窗口基础属性
setSize(400, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
validate();
studentMap= new HashMap<String,String>();
}
//点击按钮
public void click() {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
save();
ShowMap();
}
});
}
//保存方法
private void save() {
studentMap.put(tname.getText(),tscore.getText());
resultMap = sortMapByValue(studentMap); //按Value进行排序
tname.setText(""); //文本框内容清空
tscore.setText("");
}
//按值排序
public static Map<String, String> sortMapByValue(Map<String, String> map) {
if (map == null || map.isEmpty()) {
return null;
}
Map<String, String> sortedMap = new LinkedHashMap<String, String>();
List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(map.entrySet()); //将元素存入List中,类型为entry
Collections.sort(entryList, new MapValueComparator());
Iterator<Map.Entry<String, String>> iter = entryList.iterator();
Map.Entry<String, String> tmpEntry = null;
while (iter.hasNext()) {
tmpEntry = iter.next();
sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue()); //将List中的元素遍历出来存入map
}
return sortedMap;
}
//展示列表
private void ShowMap() {
show.setText("");
for(Map.Entry<String,String> entry:resultMap.entrySet()) {
show.append("姓名:"+entry.getKey()+" 成绩:"+entry.getValue()+"\n");
}
}
}
//比较器类
class MapValueComparator implements Comparator<Map.Entry<String, String>> {
public int compare(Entry<String, String> s1, Entry<String, String> s2) {
return s1.getValue().compareTo(s2.getValue());
}
}
运行效果图: