Home » » Databases and Java Forms

Databases and Java Forms

In this section, you'll create a form with buttons and text fields. The buttons will be used to scroll forwards and backwards through the records in a database table. We'll also add buttons to perform other common database tasks. The form you'll design will look something like this:

Start a new project for this by clicking File > New Project from the NetBeans menu. When the dialogue box appears, select Java > Java Application. On step one of the dialogue box, type database_form as the Project Name. Uncheck the box at the bottom for Create Main Class. Click the Finish button to create an empty project.

In the Project area on the left locate your database_form project, and right click the entry. From the menu that appears select New > JFrame Form:

When the dialogue box appears, type Workersfor the Class name, and Employees as the package name. When you click Finish, you should see a blank form appear in the main NetBeans window.

Add a Panel to your form. Then place four Text Fields on the panel. Delete the default text for the Text Fields, leaving them all blank. Change the default variable names for the Text Fields to the following:

textID
textFirstName
textLastName
textJobTitle

Add a label to your panel. Position it just to the left of the job title Text Field. Enter "Job Title" as the text for the label. Arrange the Text Fields and the Label so that your form looks something like this:

Now have a look at the Inspector area to the left of NetBeans. (If you can't see it, click Window > Inspector from the NetBeans menu.) It should match ours:

What we want to do now is to have the first record from the database table appear in the text fields when the form first loads. To do that, we can call a method from the form's Constructor.

First, though, we can add Client Driver JAR file to the project, just like last time. This will prevent any "Driver Not Found" errors. So, in the Projects area, right click the Libraries entry for your project. From the menu that appears, select Add JAR/Folder. When the dialogue box appears, locate the derbyclient.jar file. Then click Open to add it to your project.

In the main NetBeans window, click the Source button at the top to get to your code. Now add the following import statements near the top:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;

You've met all these before, the first five from the previous section. The last one, JOptionPane, is so that we can display error messages.

Inside of the Class, add the following variable declarations:

Connection con;
Statement stmt;
ResultSet rs;

Just below the Workers Constructor, add the following method:

public void DoConnect( ) {

}

Now add a call to this method from the Constructor:

public Workers() {
initComponents();
DoConnect();
}

Your code window will then look like this: (Don't worry if you have underlines for the import statements. Unless they're red underlines. In which case, you may have made a typing error.)

What we've done here is to set up a Connection object called con, a Statement object called stmt, and a ResultSet object called rs. We've set them up at the top because our buttons will need access to these objects.

When the form loads, our DoConnect method will be called. We can add code here to connect to the database, and display the first record in the text fields.

The code to add for the DoConnect method is almost identical to the code you wrote in the previous section. It's this:

One line that you may not have met is this one:

String id = Integer.toString( id_col );

Because the ID column is an Integer, we need to convert it to a String for the setTextmethod of the Text Field. We need to do this because Text Field's don't accept Integer values directly - you need to convert them to text.

All the other lines in the code should be familiar to you by now. Study the code to make sure you know what's happening. Then add it your own DoConnect method.

You can run your programme now. First, though, make sure to start your Java DB server from the Services window.

When you run your programme, you should see the first record displayed in the Text Fields:

Now that we have the first record displayed, we can add some buttons to scroll through the rest of the table data. We'll do that in the next lesson

What we'll do now is to add four buttons to the form. The buttons will enable us to move forward through the records, move back, move to the last record, and move to the first record.

So add a new panel to your form. Enlarge it and then add for buttons to the panel. Change the variable names of the buttons to the following:

btnNext
btnPrevious
btnLast
btnFirst

Change the text on each button the Next, Previous, Last, First. You form will then look something like this:

Move to the Next Record

Double click your Next button to create a code stub.

You need to do two things with the Next button: first, check if there is a next record to move to; and second, if there is a next record, display it in the Text Fields. We can create an IF Statement for this. But it needs to be wrapped up in a try … catch block. So add the following to your Next button code stub:

try {
if ( rs.next( ) ) {

}
else {
rs.previous( );
JOptionPane.showMessageDialog(Workers.this, "End of File");
}
}
catch (SQLException err) {
JOptionPane.showMessageDialog(Workers.this, err.getMessage());
}


The IF Statement moves the ResultSet on one record at a time. If there isn't a next record then a value of false is returned. The Else part moves the ResultSet back one record. That's because the Cursor will have moved past the last record.

In the curly brackets for the IF Statement we can add the code to display the record in the Text Fields:

int id_col = rs.getInt("ID");
String id = Integer.toString(id_col);
String first = rs.getString("First_Name");
String last = rs.getString("Last_Name");
String job = rs.getString("Job_Title");

textID.setText(id);
textFirstName.setText(first);
textLastName.setText(last);
textJobTitle.setText(job);

This is the same code we have in our DoConnect method. (We could create a new method, so as not to duplicate any code, but we'll keep it simple.)

The code for your Next button should now look like this:

When you've added your code, run your programme and test it out. Keep clicking your next button and you'll scroll through all the records in the table. However, there is a problem.

When you get to the last record, you should see an error message appear:

ResultSet error message

The problem is that we've added an rs.previous line. However, we've used the default ResultSet type. As we explained in the last section, this gets you a ResultSet that can only move forward. We can use the type suggested in the error message.

Stop your programme and return to your coding window. In your DoConnect method, locate the following line:

stmt = con.createStatement( );

Change it to this (yours need to go on one line):

stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );

The ResultSet type will now allow us to scroll backwards as well as forwards.

Run your programme again. Click the Next button until you get to the last record. You should see the error message from the trypart of the try … catch block appear:

End of File error message

The code for the Previous button is similar to the Next button. But instead of using rs.Next, you use rs.Previous.

Return to the Design window and double click your Previous button to create a code stub.

Instead of typing out all that code again, simply copy and paste the code from your Next button. Then change the rs.Next, in the IF statement to rs.Previous. Change the rs.Previous in the ELSE part to rs.Next. You can also change your error message text from "End of File" to "Start of File".

Thanks for reading Databases and Java Forms

« Previous
« Prev Post
Next »
Next Post »

0 komentar:

Post a Comment