Page 1 of 1

From basic JTable to a JTable with a TableModel Rate Topic: ***** 3 Votes

#1 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8346
  • View blog
  • Posts: 31,904
  • Joined: 06-March 08

Posted 08 May 2011 - 01:03 AM

*
POPULAR

How to pass from a basic JTable built calling the constructor that expects as parameter an array of Object[][] for each row and each column and an array of String[] for the headers to a modifiable JTable.

Here is the shortest example I can think of.

First a simple program that display in a JPanel contained in a JFrame a simple JTable. The elements of the JTable are built in the main() method.

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

public class StaticTable extends JFrame {

	// constructor that will display a JTable based on elements received as arguments
	StaticTable(Object[][] obj, String[] header) {
		super("Static JTable example");
		
		// JPanel to horl the JTable
		JPanel panel = new JPanel(new BorderLayout());
		// constructor of JTable with a fix number of objects
		JTable table = new JTable(obj, header);
		panel.add(new JScrollPane(table));
		add(panel);    // adding panel to frame
		// and display it
		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setVisible(true);
		pack();
	}
	
	// to run the whole thing
	public static void main(String[] args) {
		// defines rows and column of the JTable
		String[][] rowAndColumn = {
				{"Dog", "Mammal"},
				{"Cat", "Mammal"},
				{"Shark", "Fish"},
				{"Parrots", "Bird"}
		};
		// defines the header
		String[] header = {"Animal", "Family"};
		// build the GUI
		new StaticTable(rowAndColumn, header);
	}
}


Now to make this JTable editabled we have to use a TableModel. The easiest way is to have a class that extends AbstractTableModel. In this example we will use an ArrayList to hold the JTable rows.
Again the initial rows are passed as parameter to the constructor of the class that will display the JTable.
The program will then display at the console a prompt to receive new rows that will be added to the JTable.
import java.awt.*;
import java.util.*;

import javax.swing.*;
import javax.swing.table.*;

public class TableWithModel extends JFrame {

	// the Model in instance variable so we can access it
	MyModel model;
	
	// constructor that will display a JTable based on elements received as arguments
	TableWithModel(Object[][] obj, String[] header) {
		super("Static JTable example");
		
		// JPanel to horl the JTable
		JPanel panel = new JPanel(new BorderLayout());
		// constructor of JTable model
		model = new MyModel(obj, header);
		// the table from that model
		JTable table = new JTable(model);
		panel.add(new JScrollPane(table));
		add(panel);    // adding panel to frame
		// and display it
		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setVisible(true);
		pack();
	}
	
	// to run the whole thing
	public static void main(String[] args) {
		// defines rows and column of the JTable
		String[][] rowAndColumn = {
				{"Dog", "Mammal"},
				{"Cat", "Mammal"},
				{"Shark", "Fish"},
				{"Parrots", "Bird"}
		};
		// defines the header
		String[] header = {"Animal", "Family"};
		// build the GUI
		TableWithModel twm = new TableWithModel(rowAndColumn, header);
		// now we will add elements.  We could imageie deleting elements or modifying
		// them. But for simplicity lets just add
		Scanner in = new Scanner(System.in);
		// prompt for animal and family until empty line
		while(true) {
			System.out.print("Enter animal name and family: ");
			String line = in.nextLine();
			// test if empty line
			if(line.length() == 0)
				break;
			String[] token = line.split(" ");
			// if not 2 strings exit
			if(token.length != 2)
				continue;
			// add the 2 Strings based throw the model
			twm.model.add(token[0], token[1]);
			twm.repaint();   // this is the laziest way but it works
		}
	}
	
	// class that extends the AbstractTableModel
	class MyModel extends AbstractTableModel {

		// to store our elements it will be great to avoid parallel array and use 
		// an ArrayList<Animal> but for simplicity and not to have to add a new 
		// class with will use an ArrayList<Object> for each row
		ArrayList<Object[]> al;
		// the headers
		String[] header;
		
		// constructor 
		MyModel(Object[][] obj, String[] header) {
			// save the header
			this.header = header;	
			// and the rows
			al = new ArrayList<Object[]>();
			// copy the rows into the ArrayList
			for(int i = 0; i < obj.length; ++i)
				al.add(obj[i]);
		}
		// method that needs to be overload. The row count is the size of the ArrayList
		public int getRowCount() {
			return al.size();
		}

		// method that needs to be overload. The column count is the size of our header
		public int getColumnCount() {
			return header.length;
		}

		// method that needs to be overload. The object is in the arrayList at rowIndex
		public Object getValueAt(int rowIndex, int columnIndex) {
			return al.get(rowIndex)[columnIndex];
		}
		
		// a method to return the column name 
		public String getColumnName(int index) {
			return header[index];
		}
		
		// a method to add a new line to the table
		void add(String animal, String family) {
			// make it an array[2] as this is the way it is stored in the ArrayList
			// (not best design but we want simplicity)
			String[] str = new String[2];
			str[0] = animal;
			str[1] = family;
			al.add(str);
			// inform the GUI that I have change
			fireTableDataChanged();
		}
	}
}



Happy coding

This post has been edited by pbl: 08 May 2011 - 01:07 AM


Is This A Good Question/Topic? 8
  • +

Replies To: From basic JTable to a JTable with a TableModel

#2 immeraufdemhund  Icon User is offline

  • D.I.C Regular

Reputation: 79
  • View blog
  • Posts: 495
  • Joined: 29-March 10

Posted 12 May 2011 - 08:35 PM

Now that you bring it up.. I saw a DefaultTableModel and it looked like I wanted to implement it, but since my code was built up from AbstractTableModel it didn't convert without me going threw everything... I know it's kinda vague but which is better? Like a pro's/con's list
Was This Post Helpful? 0
  • +
  • -

#3 pillpusher  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 48
  • Joined: 13-May 09

Posted 30 October 2011 - 04:16 AM

THANKS PBL!!! I've been using Netbeans and I've found it difficult to use JTables unless you are populating your table from a database. My current project uses Vectors, and your simple implementation of the AbstractTableModel gave me something to work from. This is the only tutorial I've found that helped me solved my problem. Thanks again!
Was This Post Helpful? 0
  • +
  • -

#4 Ruben1123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 19-May 12

Posted 27 May 2012 - 08:04 PM

This tutorial worked wonders, but I can't get the header to show up. I have made very few modifications only changing the variable names on the add method and modifying the constructor.


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

public class MyModel extends AbstractTableModel {

	private ArrayList<Object[]> al;
	private String[] header = {"Course", "Grade"};

	public MyModel() {
		al = new ArrayList<Object[]>();
	}


	public int getRowCount() {
		return al.size();
	}

	public int getColumnCount() {
		return header.length;
	}

	public Object getValueAt(int rowIndex, int columnIndex) {
		return al.get(rowIndex)[columnIndex];
	}

	public String getColumnName(int index) {
		return header[index];
	}

	public void add(String course, String grade) {
		String[] str = new String[2];
		str[0] = course;
		str[1] = grade;
		al.add(str);
		fireTableDataChanged();
	}
}



Then in my driver I have a simple:
JTable table = new JTable(new MyModel());
		table.setBounds(25, 25, 615, 300);
		Grades.add(table); //panel


Was This Post Helpful? 0
  • +
  • -

#5 Ruben1123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 19-May 12

Posted 29 May 2012 - 03:56 AM

Never mind, just needed a scroll pane.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1