import java.util.TreeSet;
class Student implements Comparable<Student> {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
@Override
public int compareTo(Student other) {
return Integer.compare(this.score, other.score);
}
@Override
public String toString() {
return "Name: " + name + ", Score: " + score;
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.TreeSet;
public class StudentFrame extends JFrame implements ActionListener {
private JTextField nameField, scoreField;
private JTextArea displayArea;
private TreeSet<Student> studentSet;
public StudentFrame() {
super("Student Score Sorter");
setLayout(new FlowLayout());
JLabel nameLabel = new JLabel("Name:");
add(nameLabel);
nameField = new JTextField(10);
add(nameField);
JLabel scoreLabel = new JLabel("Score:");
add(scoreLabel);
scoreField = new JTextField(5);
add(scoreField);
JButton addButton = new JButton("Add");
addButton.addActionListener(this);
add(addButton);
displayArea = new JTextArea(10, 20);
add(displayArea);
studentSet = new TreeSet<>();
}
@Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
int score = Integer.parseInt(scoreField.getText());
studentSet.add(new Student(name, score));
displayArea.setText("");
for (Student student : studentSet) {
displayArea.append(student.toString() + "\n");
}
}
public static void main(String[] args) {
StudentFrame frame = new StudentFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
}
}