public class StudentMarks2 extends JFrame
1: //StudentMarks2.java
2: //Loads student names and marks from a textfile called "input.txt" and
3: //displays them in a JTextArea component on the screen.
4: //Extends StudentMarks1.java by using a better font, and by adding some
5: //(currently non-functional) user interface elements. In other words,
6: //this version doesn't really do any more, but it looks better.
8: import java.io.File;
9: import java.io.FileNotFoundException;
10: import java.util.Scanner;
11: import javax.swing.JFrame;
12: import javax.swing.JTextArea;
14: //New classes used:
15: import java.awt.BorderLayout;
16: import java.awt.Font;
17: import javax.swing.JButton;
18: import javax.swing.JPanel;
20: public class StudentMarks2 extends JFrame
21: {
22: private JTextArea display;
24: //New private members added:
25: private JPanel buttonPanel;
26: private JButton fileButton;
27: private JButton byNameButton;
28: private JButton byMarkButton;
29: private JButton quitButton;
30: private Font font;
32: public StudentMarks2(String title)
33: {
34: super(title);
35: display = new JTextArea(15, 30);
36: getDataFromFile();
38: //New code to create a font and tell the display to use it:
39: font = new Font("Monospaced", Font.PLAIN, 16);
40: display.setFont(font);
42: //New code to create a button panel and four buttons:
43: buttonPanel = new JPanel();
44: fileButton = new JButton("Load File");
45: byNameButton = new JButton("Sort by Name");
46: byMarkButton = new JButton("Sort by Mark");
47: quitButton = new JButton("Quit");
49: //New code to add buttons to button panel and
50: //to add the button panel and display to the JFrame:
51: buttonPanel.add(fileButton);
52: buttonPanel.add(byNameButton);
53: buttonPanel.add(byMarkButton);
54: buttonPanel.add(quitButton);
55: add(display, BorderLayout.CENTER);
56: add(buttonPanel, BorderLayout.SOUTH);
57: }
58:
59: public void getDataFromFile()
60: {
61: try
62: {
63: Scanner in = new Scanner(new File("input.txt"));
64: String line;
65: while (in.hasNext())
66: {
67: line = in.nextLine();
68: display.append(line + "\n");
69: }
70: in.close();
71: }
72: catch (FileNotFoundException e)
73: {
74: //This exception may or may not happen. It will not happen
75: //if a file called "input.txt" is available for reading.
76: System.out.println("Error: Required input file was not found.");
77: System.exit(0);
78: }
79: }
81: public static void main(String[] args)
82: {
83: StudentMarks2 app = new StudentMarks2("Record of Student Marks");
84: app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
85: app.pack();
86: app.setVisible(true);
87: }
88: }