Java has a number of ways to display data. Applets can be used to display information and do computations. Web pages can display information on a server, ask for and receive data sent by a user and find and return data stored on the server. Frames can use some of the graphics available for applets, but they execute entirely on the local computer and so do not require a server.
Applets cannot read from or write to local files and databases. They are designed to be downloaded from a server and execute in a “sandbox” on the user’s computer. A sandbox is an area that is strictly separated from the rest of the computer. Web pages can be used without a server to display information, but a server is needed in order to send queries to the database.
Frames, however, are applications that run on the local computer. They can get requests and display the results on the screen. The display is in a frame that is separate from the console screen. This is a nice way to handle data without having to manage a server. The adjacent picture is an example of a frame.
This example reads data from a database of grocery products and displays it in a text area on the frame. A button is used to run the method that gets the data and displays it. First we will look at the Java class that creates the frame, text area and button. The text area and button are themselves displayed on a panel. A frame can have several panels with multiple text areas, text fields and buttons.
package grocery;
import java.awt.event.*;
import java.awt.*;
public class GroceryFrame extends
Frame
{
/**
* An example that uses frames, text fields,
panels and buttons.
*/
private static final long serialVersionUID
= 1L; // This constant is used to serialize (store) the class.
private Panel
panel;
private TextArea area;
private
Button showProducts;
public GroceryFrame ()
{
super
("Grocery Frame"); // The
super class is Frame. It contains all
the necessary methods.
setSize (300, 300);
// Add a window closer to the frame. This allows the user to close the window
using the ‘X’.
addWindowListener (new WindowAdapter()
{public void windowClosing(WindowEvent
e) {System.exit(0);}});
// Get a
new panel and set its background color.
panel = new
Panel ();
panel.setBackground (Color.cyan);
// Get
the Text Area and add it to the panel.
area = new TextArea (10, 30);
panel.add (area);
// Get a new button and add a listener
to it.
showProducts = new Button ("Show
Products");
showProducts.addActionListener (new ShowProductsListener ());
panel.add (showProducts);
// Add the panel to the frame.
add (panel);
} //
constructor
/* An inner class to listen for the showBooks
button. Inner classes can use all the
variables in the outer
class. This saves the
programmer from having to send all the data to it. /*
class ShowProductsListener implements ActionListener
{
public void actionPerformed
(ActionEvent event)
{
DisplayProducts.displayProducts(area);
} //
method actionPerformed
} // ShowBooksListener
// The main method gets a new frame and makes it visible.
public static void main (String [] args)
{
GroceryFrame frame = new GroceryFrame ();
frame.setVisible (true);
} // main
} // GroceryFrame
You should note the order that objects are created in
the constructor. The panel is created
first and then the text area and button are added to it. If the button had been created before the
text area, it would appear above the text area and not below it.
The inner class implements the ActionListener
interface. This interface has methods
that listen for a mouse click on the button.
When the button is clicked, the method, ActionPerformed,
is executed. The parameter, event, can
be used to specify which button was clicked, when there is more than one
button.
Well designed projects
separate the view (the frame) from the model.
This is called the MVC design, or model-view-controller design. Keeping the code for the display separate from
that for the access to the database makes it cleaner and easier to debug. In the frame class above, the text area is a
parameter to a method in another class.
For simplicity, the method is static and so does not require an instance
of the second class. In larger projects,
there would be several methods and classes.
It might be more efficient to create separate instances of these
classes.
package grocery;
import java.sql.*;
import java.awt.*;
public class DisplayProducts
{
/**
* DisplayProducts
will display on the frame all the products in the grocery database.
*/
public static void displayProducts (TextArea area)
{
try
{
//
Get a connection to the grocery database.
Class.forName
("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con = DriverManager.getConnection
("jdbc:odbc:grocery");
//
Create a statement and query the database.
Statement
stmt = con.createStatement ();
String
query = "Select * From fruit";
//
Get the ResultSet and display all the data.
ResultSet rs = stmt.executeQuery (query);
while (rs.next ())
{
// Display each row of the database
in the text area.
area.append ("ID: " + rs.getString
("id") + "\n");
area.append ("Name: " + rs.getString
("name") + "\n");
area.append ("Quantity: " + rs.getInt
("quantity") + "\n");
area.append ("Price: " + rs.getDouble
("price") + "\n");
area.append ("\n");
}
con.close ();
} catch (ClassNotFoundException
e){System.out.println
("Class Not Found exception.\n");}
catch (SQLException e){System.out.println ("SQL
Exception\n");}
} // displayProducts
}// DisplayProducts
Note that the data must be
appended to the text area. And to place
it on separate lines, the end of line character (\n) has to be added.