Download presentation
Presentation is loading. Please wait.
2
College Student Tracker
PC02 Term 2 Project College Student Tracker
3
College Student Tracker
You will create a table that keeps track of students in a college A class for a Student needs to be made, as well as classes for the logic of the table
4
Creating a Student (1) Exercise
Create a new Java project containing the class Student Create five private instance variables in this class: String name int age String double height String subject Create getters and setters for each of these instance variables Add a constructor which accepts arguments and assigns their values to each of the instance variables Override the toString() function to output all the instance variables of the Student – try and make the output neat
5
Creating a Student (2) Exercise
Create a class called Program and give it the main method In this method, instantiate a Student (giving it all the needed values) Output this Student to the console and see what the output looks like when you run the program
6
Colleges typically only support a range of subjects
College Subjects Colleges typically only support a range of subjects You won’t find many colleges offering “Clowning 101”, for example If the college doesn’t offer it, a Student shouldn’t be allowed to have it as their subject We will make a static array of strings with available subjects
7
College Subjects Exercise
Add a public static array of strings to your Student class called subjects Think of some subjects (e.g. “Biology”, or “Carpentry”) and add them to it Include at least 7 subjects
8
Application Logic When dealing with programs that use GUIs, the logic and the graphics should always be kept separate This means we could easily change the way the program is presented if we wanted to If they were combined, this would be trickier and would require some work to “untangle” them This program will need a class to handle its logic – store all the students, sort them by name and subject, and so on
9
Application Logic Exercise
Create a class called AppLogic Give it a private instance variable: a List of Student objects, called register Create a getter and a setter for this variable Give this class a constructor that accepts an integer argument This argument is the number of Students to make by default Use this argument to instantiate the register and give it the correct number of Student objects You can use “default” values for the arguments of each Student (e.g. “Student” for their name, age of 0, and so on)
10
For now, we can move on to the GUI class
Application GUI We will add more functions to the AppLogic class as and when we need them For now, we can move on to the GUI class This will instantiate the frames and panels needed to display the register of students We will be using a grid layout It’s like a border layout, but uses a grid and allows to customise the number of cells it contains
11
Application GUI (1) Exercise
Add a class called AppGUI to your project Give it a private AppLogic instance variable called logic Create a constructor with no parameters which starts by instantiating this logic object with 5 Students
12
Application GUI (2) Exercise
After instantiating the logic object, make the constructor instantiate a JFrame object called mainFrame The mainFrame should have a default close operation that exits from the program Then instantiate a JPanel object called gridPanel The gridPanel should Have a preferred size of 800 by 600 Use the GridLayout with 6 rows and 5 columns (pass “6, 5” to the constructor) Then the constructor should add the gridPanel to the mainFrame
13
Application GUI (3) Exercise
After adding the gridPanel, pack()the mainFrame and then make it visible On a side note, if you want the window to appear in the centre of the screen, then use the following instruction after packing, but before setting it to be visible: mainFrame.setLocationRelativeTo(null); Instantiate an AppGUI object from the main method and make sure the window appears
14
GUI Table We have the frame and panel set up
The next thing we need to do is create the ‘table’ structure This involves adding the buttons along the top of the panel with the different fields beneath them
15
Add the following private instance variables to the AppGUI class:
GUI Table (1) Exercise Add the following private instance variables to the AppGUI class: 5 JButtons: nameButton, ageButton, Button, heightButton, and subjectButton A List of JComboBoxes of Strings called boxes A List of JTextFields called fields Instantiate each of these instance variables in the constructor
16
Also for each Student, create a new JComboBox of Strings
GUI Table (2) Exercise For every Student in the register of the logic instance variable, add 4 JTextFields to the fields instance variable These 4 JTextFields should contain the name, age, , and height of the Student Also for each Student, create a new JComboBox of Strings Instantiate it and pass subjects array from Student to the constructor Then, add the JComboBox to the boxes instance variable
17
With the JTextFields and JComboBoxes made, add them to the gridPanel!
GUI Table (3) Exercise With the JTextFields and JComboBoxes made, add them to the gridPanel! Follow these steps when adding these components to the gridPanel: Start by adding all of the JButtons in this order – nameButton, ageButton, Button, heightButton, and then subjectButton Then add 4 JTextFields from the fields list Then add 1 JComboBox from the boxes list Repeat steps B. and C. until there are no more JComboBoxes to add
18
Menus This setup so far lets us see the buttons (which we will use to sort the students), the text fields, and the drop-down boxes However, we still don’t have a menu at the top yet
19
There are three classes in Swing that we will use to create a menu:
Menus There are three classes in Swing that we will use to create a menu: JMenuBar is a class that represents a menu bar at the top JMenu is a class for different menus (File, View, Edit, etc) JMenuItem is a class for buttons in these menus
20
Menus This is how we can make a quick menu: Then, you just add menu items: Just like with buttons, we can also add action listeners to them
21
Menus Exercise Still in the AppGUI constructor, instantiate a JMenuBar object after adding the text fields and combo boxes to the gridPanel Create two JMenu objects for the “File” and “Options” menus Create a JMenuItem object for the “Exit” option and add it to the “File” menu Give this JMenuItem an ActionListener which, when the menu option is selected, closes the program via System.exit(0) Try and do this “anonymously”, i.e. not making AppGUI implement ActionListener Set this JMenuBar as the menu bar for the mainFrame Run your program and test that The menu bar appears at the top There are two menus – “File” and “Options” The “File” menu contains the “Exit” option Clicking on “Exit” closes the program
22
Converting to Text The program, as it is at the moment, lets us edit the name, age, address, height, and subject for five students After sufficient use, we may at some point want to save the register This would let us open the same register at a later date for editing We are going to create a function that converts all the text fields and combo boxes into a single string, ready for saving to a file (if we ever wanted to do that)
23
Converting to Text (1) Exercise
In AppGUI’s constructor, add a JMenuItem that says “Convert to text format…” to the “File” JMenu Give this JMenuItem an anonymous ActionListener In the actionPerformed() function of this ActionListener, instantiate a JTextArea called printArea
24
Converting to Text (2) Exercise
Go through all the JTextFields and JComboBoxes (in the correct order) and add their values (using getText() and getSelectedText()) to the JTextArea Create a JFrame, add the JTextArea to the JFrame, and then show the JFrame Try and format the text so that it looks like the example image below
25
The Options menu needs to be added next
Adding Rows The Options menu needs to be added next Will eventually have more options For now only Add Blank Row needed
26
This menu should add a new row to the table
Adding Rows This menu should add a new row to the table Using default information Windows should be resized to all rows are roughly same size
27
Adding Rows (1) Exercise
Create a JMenuItem (addRow) and add it to the “Options” menu Add an ActionListener to this menu item The actionPerformed function should increase the number of rows in GridLayout of the gridPanel Can get layout of gridPanel using getLayout() function (and casting result to GridLayout) Can use setRows() and getRows() to set/get rows of layout After, add a new Student to the register of the logic variable
28
Adding Rows (2) Exercise
Create 4 JTextField objects (same way how fields variable was initially set up) Add these to both fields and gridPanel Create a JComboBox (as before) and add to boxes and gridPanel Run updateUI() on gridPanel to refresh its look Use setSize() or setPreferredSize() to change mainFrame’s size to fit new row Check the setPreferredSize() of the “Convert to text…” action so that it works for all possible sizes of grid
29
Starting Size Extra Exercise
Try letting the user decide on the number of rows to start with Change the AppGUI() constructor so that it accepts an integer argument It should use this argument as the parameter when constructing AppLogic Make sure initial size of window works no matter what grid size selected
30
AppLogic class should include functions for sorting table
Sorting Students AppLogic class should include functions for sorting table Based on different fields (e.g. Subject or Name) Now need to create functions for sorting based on each field sortByName(), sortByAge(), sortBy (), sortByHeight(), sortBySubject()
31
string1.compareTo(string2);
Sorting Students Sorting alphabetically can be done using compareTo() on the String E.g. A is less than B string1.compareTo(string2); string1 == string2: returns 0 string1 > string2: returns 1 string1 < string2: returns -1 Could use sorting algorithm (Bubble, Quick, Insertion etc.) to sort list
32
Sorting Students Exercise
Create function reassignRegister() in AppGUI class Assigns register of the AppLogic the values currently in the grid, using getText() of elements in fields and boxes Create function reassignGrid() which assigns values to fields and boxes from register (using setText() of elements) Add a new ActionListener to each field’s Jbutton These should all run reassignRegister(), then run the sort function for their field, then reassignGrid()
33
Make sure sorting tested and working before continuing
Number Validation Make sure sorting tested and working before continuing What happens if invalid age entered into age field, etc. The program will crash This shouldn’t happen Errors need to be handled Need to create functions which try and parse text in fields Will return value if parsed correctly, or 0 if not
34
Number Validation Exercise
Create two functions, parseInteger() and parseDouble() Return integers and doubles respectively They should “try” parsing argument as integer/double If successful, should return parsed value If fails, return 0 Change reassignRegister() so it uses these parsing functions before assigning age and height Test your program to make sure it works Enter a valid value Enter an invalid value
35
Changing Background Colour
Going to add some “extra” items to “Options” menu Will let the user change background colour for the text fields and boxes
36
Changing Background Colour (1) Exercise
Create a JMenu with text “Change Background Colour” – add to “Options” menu Add a separator between previous “Options” menus and this new one Create two arrays – Color and String The Color array: contain colours like Color.RED or Color.BLACK The String array: contain names of colours (“Red” or “Black”) Makes sure the arrays have the same number of elements, and the names/colours appear in the same order Create a JMenuItem array (backgroundColours) and fill it with JMenuItems Text of each JMenuItem should be from String array Add new ActionListener to each JMenuItem
37
Changing Background Colour (2) Exercise
Override actionPerformed for each new ActionListener Run the setBackground() function on all elements in fields and boxes using correct colour from Color array Add each JMenuItem to the “Change Background Colour…” menu Test your program and make sure this changing of colours works Edit the “Convert to Text Format…” logic so the window that appears uses the same colour
38
Changing Text Colour Extra Exercise
Create another JMenuItem array called foregroundColours Fill it with JMenuItem objects with text from String array Add new ActionListener to each one (as before) Use setForeground() instead of setBackground() Add all of these JMenuItems to JMenu with text “Change Text Colour…” Add this JMenu to “Options” menu and test that this works correctly
39
Age and height already being validated Email still isn’t
Validating Age and height already being validated still isn’t Will create a validate function for addresses Checks Checks for . Not most rigorous of checks, but will suffice
40
Validating Email Exercise
Add a String function to AppGUI: validate Looks symbol in String using substring() in any position other than first index If found, then looks for full stop at least two positions If full stop found, return original String Otherwise use JOptionPane.showMessageDialog to show warning message and then return default Change reassignReigster() to validate before reassignment
41
Student with Parameters
Make another entry in Options menu Add new student Creates a new Student given some arguments Must retrieve data from user Can use JOptionPane.showInputDialog() for this Must cast for numerical values
42
Student with Parameters (1) Exercise
Create new JMenuItem for “Options”: “Add new student…” Override new ActionListener Using JOptionPane.showInputDialog() Ask user for “name” Ask user for “age” Ask user for “height” Use parsing/validation on age and height (e.g. no negative values)
43
Student with Parameters (2) Exercise
For “ ” input, use validate () function to get valid First ask for input from user Pass input into validate () Get result for Student parameter Get “subject” from user Use “Arrays.asList(Student.subjects).contains(tmp)” with an if statement or a loop It will check if user input is valid Handle wrong input appropriately Add new row to table using information from new Student using these parameters Must add to register Create new fields and boxes
44
Ascending/Descending Sort
Sorting functions run when button clicked From smaller to larger What if we want to go from larger to smaller? Surprisingly easy to implement Need a variable and a function Boolean instance variable called descending in AppLogic Private void function reverse() which reverses order of register When sorting function is run, we check descending If true, run reverse() function Otherwise don’t do anything Invert value of descending
45
Ascending/Descending Sort Exercise
Create Boolean instance variable descending in AppLogic Set to false in constructor Create private void reverse() Reverses order of register (up to you how) if descending is true Inverts descending afterwards This function should be called after other sorting functions
46
Loading Students Going to add “Read from text…” item to File menu
Converts String input into Students Opposite of “Convert to text…” Will show window for user to enter text Text then converted into Students Added to table
47
Loading Students (1) Exercise
Create JMenuItem readTextMenu and add to “File” menu Add anonymous ActionListener Function actionPerformed() should show blank JTextArea (editable) and JButton (“Confirm”) Add JTextArea and JButton to CENTRE and SOUTH of new JPanel (using BorderLayout) Show JPanel using JFrame.
48
Loading Students (2) Exercise
Add anonymous ActionListener to JButton Clears fields and boxes Splits JTextArea text into lines Splits each line (using tab or comma or any other delimiter) Takes values from split lines to create new JTextFields and JComboBoxes for each one (adding to fields and boxes)
49
Loading Students (3) Exercise
Clear gridPanel using removeAll() Add the following back to gridPanel The five JButtons (for sorting) Repeatedly 4 fields and 1 box (until all added) Run updateUI() on gridPanel Close the text input window using dispose() on the JFrame
50
Program is practically complete Would be nice to fix some bugs
Bug Fixes Program is practically complete Would be nice to fix some bugs Can you find them? Following are some examples of bugs in the program Can you work out how to fix them?
51
If grid colours change, do new rows use same colour?
Bug Fixes (1) Exercise If grid colours change, do new rows use same colour? Do JComboBoxs have same background as JTextFields? String null is returned if user “Cancels” new student window Does this cause a crash? Is there a way to stop it?
52
Bug Fixes (2) Exercise When “reading text” for loading Students, what does entering nothing do? Is there a way to fix this? What if not enough/too many columns added? Does the window size change to reflect newly added Students from loading text?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.