public class Student implements Comparable{
String name;
int grade;
Student(String name,int grade){
this.name=name;
this.grade=grade;
}
public int compareTo(Object obj){
return(this.grade<((Student)obj).grade?-1:(this.grade==((Student)obj).grade)?0:1);
}
}
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
@SuppressWarnings("serial")
public class StudentFrame extends JFrame{
@SuppressWarnings("rawtypes")
ArrayList list=new ArrayList();
JPanel panel;
JTextArea textArea;
JButton bt1,bt2;
JLabel label1,label2;
JTextField t1,t2;
JScrollPane scrollPane;
Container contentPane;
Box box1,box2,box;
public StudentFrame() {
super("成绩排序练习");
panel=new JPanel();
label1=new JLabel("姓名");
label2=new JLabel("成绩");
t1=new JTextField(10);
t2=new JTextField(10);
textArea=new JTextArea(10,30);
scrollPane=new JScrollPane(textArea);
bt1=new JButton("提交");
bt2=new JButton("查询");
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
panel1.add(label1);
panel1.add(t1);
panel2.add(label2);
panel2.add(t2);
panel3.add(bt1);
panel3.add(bt2);
panel.add(panel1);
panel.add(panel2);
panel.add(panel3);
panel.add(scrollPane);
/**box1=Box.createHorizontalBox();
box1.add(label1);
box1.add(t1);
box1.add(label2);
box1.add(t2);
box2=Box.createHorizontalBox();
box2.add(bt1);
box2.add(bt2);
box=Box.createVerticalBox();
box.add(box1);
box=Box.createVerticalBox();
box.add(box2);
panel.add(box);**/
//contentPane.add(panel,BorderLayout.NORTH);
//contentPane.add(scrollPane,BorderLayout.CENTER);
this.setContentPane(panel);
//this.setContentPane(paneln); //frame框架放入panel容器
panel.setLayout(new GridLa yout(5, 1, 5, 5)); //
//setLayout(new FlowLayout());
setSize(500,400);
setVisible(true);
//设置不允许用户自行调整窗口大小
//setResizable(false);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
bt1.addActionListener(new ActionListener(){
@SuppressWarnings("unchecked")
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String name;
int grade;
Student s;
name=t1.getText(); //文本框用get方法
grade=Integer.parseInt(t2.getText());
s=new Student(name,grade);
if(e.getSource()==bt1){
textArea.append(t1.getText()+":"+t2.getText()+",提交成功\n");
list.add(s);
}
}
});
bt2.addActionListener(new ActionListener(){
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent e) {
textArea.append("按成绩排序为:\n");
if(e.getSource() == bt2){//点击查看按钮,事件处理
Collections.sort(list);
@SuppressWarnings("rawtypes")
Iterator it = list.iterator(); //获取Iterator迭代器
while(it.hasNext()){ //判断是否存在下一个元素
Student b = (Student) it.next(); //读取下一个元素
textArea.append(b.name + ": " + b.grade + "\n");
}
}
}
} );
}
public static void main(String[] args) {
new StudentFrame();
}
}
编写一个应用程序,用户分别从两个文本框输入学术的姓名和分数,程序按成绩排序将这些学生的姓名和分数显示在一个文本区中。