Part 1 – Build a GUI program. DisplayStudent – Create the DisplayStudent class.
ID: 669964 • Letter: P
Question
Part 1 – Build a GUI program.
DisplayStudent – Create the DisplayStudent class. It will extend JFrame and contain a main() method. Set the title on the frame to “Display Student”. The frame will have a JPanel that contains two components. A JTextArea and another JPanel below the JTextArea.
The second JPanel will contain two JLabels side by side. It also has a border.
Both panels use BorderLayout.
Load the Text area with a couple of lines of test data (hint: a string that ends in “
” will cause a newline to be displayed in the JTextArea).
Put text into the two JLabels as shown below.
The only buttons that have to work are the buttons on the title bar (including the Exit button).
Here is a screen shot:
Part 2 – Adding menus
Add a menu bar and two menus: File and Edit
On the File menu add three menu items: Connect, Close & Exit.
On the Edit menu add two menu item: Search and Clear.
Make sure you have reasonable mnemonics for each menu and menu item: ‘F’ for File, ‘E’ for Edit, ‘C’ for connect, etc. Note, you can NOT have one mnemonic character represent more than one menu or menu item.
When the program starts make sure the JTextArea is blank, the left hand JLabel’s text says “No Connection” and the right hand JLabel says “Number of Students = 0”.
When the Connect menu item is clicked put up an Input Dialog that asks for a database. Store the input from the user in a new instance String variable called database_name. Set the text in the left hand JLabel to “Connected to xxxx” where xxxx is the database_name and print the name to standard out.
When the Close menu item is clicked put up a Confirmation Dialog box. Print out the users response (yes or no to close). If the user response is “Yes” then set the database_name string to null. Set the left hand JLabel to “No Connection”.
When the Exit menu item is clicked, shut down the program.
When the Search menu item is clicked, check to see if the database_name is null. If so put up an Error dialog. Else put up an Input Dialog requesting a Student Social Security number. Store the input from the user in a new instance String variable called search_ssn and then put some test data into the JTextArea. Set the right hand JLabel to “Number of students = n” where n is the number of lines of test data.
When the Clear menu item is clicked, clear out the data in the JTextArea. Set the right hand JLabel to “Number of students = 0”.
Here are two screen shots: - one just before connection and the other after search.
Part 3 – Adding a JTable
DisplayStudent – We will add some code to the DisplayStudent class.
Replace the JTextArea with a JTable. You’ll do this by adding a DefaultTableModel that has a header of four columns: SSN, First Name, Last Name, and Major and a JTable in a JScrollPane.
Depending on how you designed the original program this will probably mean modifying the following methods: the constructor as well as the search and clear event handler methods.
You will have to change your test data that you display to add a SSN for each row.
Compile and test to insure that all the menu items still work. 6. Play with making the table columns wider or narrower, making the window larger or smaller to insure that everything looks and acts OK.
Here is a screen shot:
Hints:
To start out with your Object[][] data reference variable will contain a null value, but you still need it when you create the DefaultTableModel.
If you have trouble with your labels not showing up, Try adding the label panel to the big panel (that holds everything) first then add the JScrollPane (with the JTable in it) to the big panel. It shouldn’t matter to the Layout Manager, but I’ve had trouble with this sort of thing.
Explanation / Answer
************Add information ************
CREATE A DATABASE "addItemDB.mdb" IN MS-ACCESS.
CREATE A TABLE "persons" with the following fields
id- Auto Number
firstName-Text
middleName-Text
familyName-Text
Age- Number
SAVE THE DATABASE.
java program to add student information
//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class addItemToDatabase extends JFrame {
//Initializing Components
private JTextField inputs[];
private JButton add, reset;
private JLabel labels[];
private String fldLabel[] = {"First Name: ","Middle Name: ","Family Name: ","Age: "};
private JPanel p1;
Connection con;
Statement st;
ResultSet rs;
String db;
//Setting up GUI
public addItemToDatabase() {
//Setting up the Title of the Window
super("Adding Data to the Database");
//Set Size of the Window (WIDTH, HEIGHT)
setSize(300,180);
//Exit Property of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Constructing Components
inputs = new JTextField[4];
labels = new JLabel[4];
add = new JButton("Add");
reset = new JButton("Reset");
p1 = new JPanel();
//Setting Layout on JPanel 1 with 5 rows and 2 column
p1.setLayout(new GridLayout(5,2));
//Setting up the container ready for the components to be added.
Container pane = getContentPane();
setContentPane(pane);
//Setting up the container layout
GridLayout grid = new GridLayout(1,1,0,0);
pane.setLayout(grid);
//Creating a connection to MS Access and fetching errors using "try-catch" to check if it is successfully connected or not.
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=addItemDB.mdb;";
con = DriverManager.getConnection(db,"","");
st = con.createStatement();
JOptionPane.showMessageDialog(null,"Successfully Connected to Database","Confirmation", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
//Constructing JLabel and JTextField using "for loop" in their desired order
for(int count=0; count<inputs.length && count<labels.length; count++) {
labels[count] = new JLabel(fldLabel[count]);
inputs[count] = new JTextField(20);
//Adding the JLabel and the JTextFied in JPanel 1
p1.add(labels[count]);
p1.add(inputs[count]);
}
//Implemeting Even-Listener on JButton add
add.addActionListener(
new ActionListener() {
//Handle JButton event if it is clicked
public void actionPerformed(ActionEvent event) {
if (inputs[0].getText().equals("") || inputs[1].getText().equals("") || inputs[2].getText().equals("") || inputs[0].getText() == null || inputs[1].getText() == null || inputs[2].getText() == null)
JOptionPane.showMessageDialog(null,"Fill up all the Fields","Error Input", JOptionPane.ERROR_MESSAGE);
else
try {
String add = "insert into person (firstName,middleName,familyName,age) values ('"+inputs[0].getText()+"','"+inputs[1].getText()+"','"+inputs[2].getText()+"',"+inputs[3].getText()+")";
st.execute(add); //Execute the add sql
Integer.parseInt(inputs[3].getText()); //Convert JTextField Age in to INTEGER
JOptionPane.showMessageDialog(null,"Item Successfully Added","Confirmation", JOptionPane.INFORMATION_MESSAGE);
}catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,"Please enter an integer on the Field AGE","Error Input", JOptionPane.ERROR_MESSAGE);
}catch (Exception ei) {
JOptionPane.showMessageDialog(null,"Failure to Add Item. Please Enter a number on the Field AGE","Error Input", JOptionPane.ERROR_MESSAGE);
}
}
}
);
//Implemeting Even-Listener on JButton reset
reset.addActionListener(
new ActionListener() {
//Handle JButton event if it is clicked
public void actionPerformed(ActionEvent event) {
inputs[0].setText(null);
inputs[1].setText(null);
inputs[2].setText(null);
inputs[3].setText(null);
}
}
);
//Adding JButton "add" and "reset" to JPanel 1 after the JLabel and JTextField
p1.add(add);
p1.add(reset);
//Adding JPanel 1 to the container
pane.add(p1);
/**Set all the Components Visible.
* If it is set to "false", the components in the container will not be visible.
*/
setVisible(true);
}
//Main Method
public static void main (String[] args) {
addItemToDatabase aid = new addItemToDatabase();
}
}
**********following program to retrieve the information *******
CREATE A DATABASE "addItemDB.mdb" IN MS-ACCESS.
CREATE A TABLE "persons" with the following fields
id- Auto Number
firstName-Text
middleName-Text
familyName-Text
Age- Number
SAVE THE DATABASE.
TYPE THE FOLLOWING CODE IN THE NOTEPAD AND RUN THE PROGRAM
//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class retrieveDBUsingJList extends JFrame {
//Initializing program components
private DefaultListModel model;
private JButton buttons[];
private JList dbList;
private JPanel p1,p2;
private String bLabel[] = {"ID","First Name","Middle Name","Last Name","Age"};
Connection con;
Statement st;
ResultSet rs;
String db;
//Setting up GUI
public retrieveDBUsingJList() {
//Setting up the Title of the Window
super("Retrieve DB and Display Using JList");
//Set Size of the Window (WIDTH, HEIGHT)
setSize(300,200);
//Exit Property of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Constructing JButtons, JList, and DefaultListModel
model = new DefaultListModel();
buttons = new JButton[5];
dbList = new JList(model);
//Setting up JList property
dbList.setVisibleRowCount(5);
dbList.setFixedCellHeight(27);
dbList.setFixedCellWidth(130);
dbList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//Constructing JPanel 1 and its property
p1 = new JPanel();
p1.setBorder(BorderFactory.createTitledBorder("Database: "));
p1.add(new JScrollPane(dbList)); //Adding JList in JPanel 1
//Constructing JPanel 2 and its property
p2 = new JPanel();
p2.setLayout(new GridLayout(5,1));
p2.setBorder(BorderFactory.createTitledBorder("Display: "));
//Constructing all 5 JButtons using "for loop" and add it in JPanel 2
for(int count=0; count<buttons.length; count++) {
buttons[count] = new JButton(bLabel[count]);
p2.add(buttons[count]);
}
//Setting up the container ready for the components to be added.
Container pane = getContentPane();
setContentPane(pane);
//Setting up the container layout
GridLayout grid = new GridLayout(1,2);
pane.setLayout(grid);
//Creating a connection to MS Access and fetch errors using "try-catch" to check if it is successfully connected or not.
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=addItemDB.mdb;";
con = DriverManager.getConnection(db,"","");
st = con.createStatement();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE);
System.exit(0);
}
//Implemeting Even-Listener on JButton buttons[0] which is ID
buttons[0].addActionListener(
new ActionListener() {
//Handle JButton event if it is clicked
public void actionPerformed(ActionEvent event) {
try {
model.clear();
rs=st.executeQuery("select * from person");
while (rs.next()) {
model.addElement(rs.getString("id"));
}
} catch (Exception e) {
System.out.println("Retrieving Data Fail");
}
}
}
);
//Implemeting Even-Listener on JButton buttons[1] which is First Name
buttons[1].addActionListener(
new ActionListener() {
//Handle JButton event if it is clicked
public void actionPerformed(ActionEvent event) {
try {
model.clear();
rs=st.executeQuery("select * from person");
while (rs.next()) {
model.addElement(rs.getString("firstName"));
}
} catch (Exception e) {
System.out.println("Retrieving Data Fail");
}
}
}
);
//Implemeting Even-Listener on JButton buttons[2] which is Middle Name
buttons[2].addActionListener(
new ActionListener() {
//Handle JButton event if it is clicked
public void actionPerformed(ActionEvent event) {
try {
model.clear();
rs=st.executeQuery("select * from person");
while (rs.next()) {
model.addElement(rs.getString("middleName"));
}
} catch (Exception e) {
System.out.println("Retrieving Data Fail");
}
}
}
);
//Implemeting Even-Listener on JButton buttons[3] which is Last Name
buttons[3].addActionListener(
new ActionListener() {
//Handle JButton event if it is clicked
public void actionPerformed(ActionEvent event) {
try {
model.clear();
rs=st.executeQuery("select * from person");
while (rs.next()) {
model.addElement(rs.getString("familyName"));
}
} catch (Exception e) {
System.out.println("Retrieving Data Fail");
}
}
}
);
//Implemeting Even-Listener on JButton buttons[4] which is Age
buttons[4].addActionListener(
new ActionListener() {
//Handle JButton event if it is clicked
public void actionPerformed(ActionEvent event) {
try {
model.clear();
rs=st.executeQuery("select * from person");
while (rs.next()) {
model.addElement(rs.getString("age"));
}
} catch (Exception e) {
System.out.println("Retrieving Data Fail");
}
}
}
);
//Adding components to the container
pane.add(p1);
pane.add(p2);
/**Set all the Components Visible.
* If it is set to "false", the components in the container will not be visible.
*/
setVisible(true);
setResizable(false);
}
//Main Method
public static void main (String[] args) {
retrieveDBUsingJList rdjl = new retrieveDBUsingJList();
}
}