Saturday, 15 February 2014

Java: JTable example without a model

JTable has different variations. One can be very simple and used to display vector or array data. Another one can display values from databases.
The disadvantages of simple JTable constructor are as follows from docs.oracle.com

  • They automatically make every cell editable.
  • They treat all data types the same (as strings). 
  • They require that you put all of the table's data in an array or vector, which may not be appropriate for some data.

Above diagram displays the output from the example program.
The simple JTable use no model and this example will demonstrate how it is used.

import java.awt.*;
import javax.swing.*;

@SuppressWarnings("serial")
public class JTableWithOutModel extends JFrame
{

// constructor that will display a JTable based on elements received as
// arguments
public JTableWithOutModel(Object[][] data, String[] columnNames)
{
super("Static JTable example");

// JPanel that contains the table
JPanel tablePanel = new JPanel(new BorderLayout());
JTable table = new JTable(data, columnNames);
tablePanel.add(new JScrollPane(table));
add(tablePanel);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
pack();
}

public static void main(String[] args)
{
// The constructor with array arguments is used for the JTabel
// Therefore we will declare the arrays holding the column names and
// data

String[] columnNames =
{ "First Name", "Last Name", "Game", "Age", "Smoking" };

// The two-dimensional Object array initializes and stored data
Object[][] data =
{
{ "Kathy", "Smith", "Snowboarding", new Integer(25), new Boolean(false) },
{ "John", "Doe", "Rowing", new Integer(23), new Boolean(true) },
{ "Sue", "Black", "Knitting", new Integer(24), new Boolean(false) },
{ "Jane", "White", "Speed reading", new Integer(20), new Boolean(true) },
{ "Joe", "Brown", "Pool", new Integer(30), new Boolean(false) } };

new JTableWithOutModel(data, columnNames);
}
}

No comments:

Post a Comment