Java集合框架上機練習題2
阿新 • • 發佈:2019-01-23
package sci; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.Label; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.*; import javax.swing.*; public class grade { public static void main(String[] args) { new Window(); } } class Window extends JFrame implements ActionListener{ Box bx_1,bx_2; JTextField jt1=new JTextField(10); JTextField jt2=new JTextField(10); JButton button=new JButton("提交"); Container container=getContentPane(); JTextArea jTextArea=new JTextArea(); JPanel jPanel1=new JPanel(); ArrayList<stu> list=new ArrayList<stu>(); Window() { // TODO Auto-generated constructor stub、 bx_1=Box.createHorizontalBox(); bx_1.add(new Label("姓名:")); bx_1.add(jt1); bx_1.add(Box.createHorizontalStrut(8)); bx_1.add(new Label("分數")); bx_1.add(jt2); bx_1.add(button); jPanel1.add(bx_1); jPanel1.setLayout(new FlowLayout()); container.add(jPanel1,BorderLayout.NORTH); JScrollPane jScrollPane=new JScrollPane(jTextArea); add(jScrollPane); container.add(jScrollPane, BorderLayout.CENTER); setTitle("視窗"); setSize(500,400); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); button.addActionListener(this); } public void actionPerformed(ActionEvent e){ String name=jt1.getText().toString(); double grade=Double.parseDouble(jt2.getText()); stu s=new stu(); s.setName(name); s.setGrade(grade); list.add(s); Collections.sort(list, new SortByGrade()); jTextArea.setText(null); for (stu stu : list) { jTextArea.append(stu.getName()+" "+stu.getGrade()+"\n"); } } } class SortByGrade implements Comparator{ public int compare(Object obj1, Object obj2) { stu s1=(stu)obj1; stu s2=(stu)obj2; return s1.getGrade()<=s2.getGrade()?1:-1; } } class stu{ String name; double grade; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getGrade() { return grade; } public void setGrade(double grade) { this.grade = grade; } }
編寫一個應用程式,使用者分別從兩個文字框輸入學術的姓名和分數,程式按成績排序將這些學生的姓名和分數顯示在一個文字區中