Creating a Simple JTable


Notice that the JTable created by the following code has a built-in storage implementation. It constructs a JTable to display values in a two-dimensional array, called data , with column names ( colNames ). Although cell values can be changed, rows and columns cannot be added or deleted.

 Object[][] data = {  {"col1", "col2"}, //row1                      {"col1", "col2"}  //row2                   }; String[] colNames =  {"col1", "col2"}; JTable table = new JTable(data, colNames); 

There are seven JTable constructors total, but only three are mentioned in the preceding code. You can create a table in a similar fashion by passing Vectors containing the data and the column names to the constructor. Notice that the values are in a Vector of Vector s, like so:

 Vector columns = new Vector(); Vector data = new Vector(); Vector columnNames = new Vector(); columnNames.addElement("Name"); columnNames.addElement("Age"); columns.addElement("Matty"); columns.addElement(new Integer(4)); data.addElement(columns); JTable table = new JTable(data, columnNames); 

Listing 15.1 is a working example. It has all the basic pieces to create a JTable component in which the amount of data to add is flexible because of using Vector s. This flexibility is important for dynamically loading the JTable from a file when you do not know beforehand how many rows of data there are.

Listing 15.1 An Example Using JTable
 import javax.swing.JTable; import javax.swing.JScrollPane; import javax.swing.JPanel; import javax.swing.JFrame; import java.util.Vector; import java.awt.Dimension; import java.awt.BorderLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class MyTable extends JFrame {     public MyTable()     {         super("MyTable");         //simpler way, but must know array size beforehand         Object[][] data = { {"Matty", new Integer(5)},                             {"Daniel", new Integer(8)},                             {"Peter", new Integer(11)},                             {"Kasienne", new Integer(12)},                             {"Austin", new Integer(13)},                             {"Carter", new Integer(14)},                           };         String[] columnNames={"Name","Age"};         Vector columns = new Vector();         Vector data = new Vector();         Vector columnNames = new Vector();         columnNames.addElement("Name");         columnNames.addElement("Age");         columns.addElement("Matty");         columns.addElement(new Integer(5));         data.addElement(columns);         columns = new Vector();         columns.addElement("Daniel");         columns.addElement(new Integer(8));         data.addElement(columns);         columns = new Vector();         columns.addElement("Peter");         columns.addElement(new Integer(11));         data.addElement(columns);         columns = new Vector();         columns.addElement("Kasienne");         columns.addElement(new Integer(12));         data.addElement(columns);         columns = new Vector();         columns.addElement("Austin");         columns.addElement(new Integer(13));         data.addElement(columns);         columns = new Vector();         columns.addElement("Carter");         columns.addElement(new Integer(14));         data.addElement(columns);         final JTable table = new JTable(data, columnNames);         table.setPreferredScrollableViewportSize(new Dimension(200, 100));         //Add the table to scroll pane.         JScrollPane scrollPane = new JScrollPane(table);         //Add the scroll pane to this window.         getContentPane().add(scrollPane, BorderLayout.CENTER);         //If you don't do this, the program won't terminate         //when you click the window's close button         addWindowListener(new WindowAdapter()         {             public void windowClosing(WindowEvent e)             {                 System.exit(0);             }         });     }     public static void main(String[] args)     {         MyTable frame = new MyTable();         frame.pack();         frame.setVisible(true);     } } 

Listing 15.1 produces the screen shown in Figure 15.1.

Figure 15.1. A simple JTable example.

graphics/15fig01.jpg

To demonstrate a more compelling example, Listing 15.2 is a simplified database file reader. The database in this case is an ASCII text file of data in which the first row is the set of column names and the remaining rows are data. You could easily add the capability to handle comma separated values (CSV), but the file structure is deliberately kept simple to help highlight the algorithm steps. It is similar to Listing 15.1, except now you are getting your data from a file that acts as a database. This example starts to meet the central goal of the assignment: You must read data from a database file and display it in a Swing JTable component. Run Listing 15.1 with the following command line: java DBViewer filename , where filename is the name of the file (the file provided is named data.db ).

Listing 15.2 Displaying a Database File Using JTable
 import javax.swing.JTable; import javax.swing.JScrollPane; import javax.swing.JPanel; import javax.swing.JFrame; import java.util.Vector; import java.io.StreamTokenizer; import java.io.FileReader; import java.io.BufferedReader; import java.awt.Dimension; import java.awt.BorderLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class DBViewer extends JFrame {     public DBViewer(String filename)     {         super("DBViewer");         Vector rowValues = new Vector();         Vector data = new Vector();         Vector columnNames = new Vector();         boolean firstLine = true;         String line;         //1  open file         try         {             FileReader reader = new FileReader(filename);             BufferedReader br = new BufferedReader(reader);             StreamTokenizer tokenizer = new StreamTokenizer(br);             tokenizer.eolIsSignificant(true);      // we need '\n'             //2  get line             //3  get next field from line             int type;             while ( (type = tokenizer.nextToken())                      != StreamTokenizer.TT_EOF)             {                   //4  add names to columnNames, values to rowValues                   switch (type)                   {                     case StreamTokenizer.TT_NUMBER:                         //add to value vector                         rowValues.addElement(new Double(tokenizer.nval));                         break;                     case StreamTokenizer.TT_WORD:                         //add to column name vector                         if (firstLine)                         {                             columnNames.addElement(tokenizer.sval);                         //add to value vector                         } else                         {                             rowValues.addElement(tokenizer.sval);                         }                         break;                     case StreamTokenizer.TT_EOL:                         //5  add row of values to data                         if (!firstLine && rowValues.size() > 0)                         {                             data.addElement(rowValues);                             rowValues = new Vector();                         }else                         {                             firstLine = false;                         }                   }             }         } catch (java.io.FileNotFoundException fnfe)         {             System.out.println(fnfe);             System.exit(0);         } catch (ArrayIndexOutOfBoundsException aibe)         {             System.out.println(aibe);             System.exit(0);         } catch (java.io.IOException ioe)         {             System.out.println(ioe);             System.exit(0);         }         final JTable table = new JTable(data, columnNames);         table.setPreferredScrollableViewportSize(new Dimension(200, 100));         //Add the table to scroll pane.         JScrollPane scrollPane = new JScrollPane(table);         //Add the scroll pane to this window.         getContentPane().add(scrollPane, BorderLayout.CENTER);         //If you don't do this, the program won't terminate         //when you click the window's close button.         addWindowListener(new WindowAdapter()         {             public void windowClosing(WindowEvent e)             {                 System.exit(0);             }         });     }     public static void main(String[] args)     {         if (args.length == 0)         {             System.out.print("No file name provided. Terminating.");             System.exit(0);         }         DBViewer frame = new DBViewer(args[0]);         frame.pack();         frame.setVisible(true);     } } 

Assume the database file has the following structure:

 ID   Name         Amount 1234 Patricia     7000.00 5678 Kasienne     5000.00 8910 James        2000.00 

Remember that the usage is java DBViewer DB_file_name . Listing 15.2 produces the screen shown in Figure 15.2.

Figure 15.2. Viewing a database with a JTable.

graphics/15fig02.jpg

Now try putting on your architecture hat. Suppose you want to solidify the design with a formal grammar for the file structure. You could say that the file acting as a database table has the following grammar:

 table : ( row (EOL) )* ; row : ( COLUMN (DELIMITER COLUMN)* ) ; COLUMN : ( ~( '\t'  ' '  '\r'  '\n' ) )+ ; EOL : ( '\n'  '\r' ) ; DELIMITER : '\t'  (' ')+ ; 

This grammar specifies a file as having delimiters that are a tab character or space(s). Note that the asterisk (*) means zero to many, and the plus sign (+) means one to many. means or and ~ means not. The end of line (EOL) could be a carriage return or a newline character. The column is a sequence of one or more characters that are not tabs, one or more spaces, newline characters , or carriage returns.

So, to read this grammar we would say a row contains one or more columns separated by delimiters. Finally, a table contains zero or more rows, each ending with one EOL. This design is simple, but it demonstrates clearly how you should proceed for a real application. It includes the basic grammar constructs of concatenation, alternation , repetition zero or more times, repetition one or more times, and negation. The grammar in the preceding example disallows an empty row by defining a row as comprising columns that must contain at least one character.

The primary goal is to read a file and correctly display it in a JTable. There are several things you can do to improve Listing 15.2's functionality. For example, you can use a regular expression construct rather than the StreamTokenizer class. The following snippet is a start:

 try {     FileInputStream fis = new FileInputStream(filename);     FileChannel fc = fis.getChannel();     // Create a read-only CharBuffer on the file     ByteBuffer bbuf = fc.map(FileChannel.MapMode.READ_ONLY,                              0, (int)fc.size());      // Need a CharSequence for use by regex.     CharBuffer cbuf = Charset.forName("8859_1").newDecoder().decode(bbuf);      // Create matcher on file     Pattern pattern = Pattern.compile("([A-Za-z][0-9])+");     Matcher matcher = pattern.matcher(cbuf);     // Get matches     while (matcher.find())     {         String match = matcher.group();         //do something with match     } } catch (IOException e) {     System.out.print(e); } 


JavaT 2 Developer Exam CramT 2 (Exam CX-310-252A and CX-310-027)
JavaT 2 Developer Exam CramT 2 (Exam CX-310-252A and CX-310-027)
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 187

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net