Table Model Internal Implementation
Developers,
As written in the API when constructing a Table you can set CONSTANTS which determine when the Table is resized what behaviour will apply. - eg AUTO_RESIZE_COLUMN.
Can anybody tell me, in view of there being 5 different options, how this is most likely implemented internally. I dont believe there are subclasses which handle drawing based on this constant. I also dont believe that there is a big if - else block.
The reason i want to know this is i have to do something similar and i want to borrow the design ideas used in Table. Obviously i have researched using Tables but i want to know how layout gets done internally.
Thanks.
i doubt very much they would let you see the source.Why would I suggest this if I wasn't able to look at the source code?
I using Apple Mac OS X The JDK source belongs to Sun, not Apple. I have the complete source for the Windows JDK, so I don't see any reason why you don't have it with the Apple JDK.
The code is not located in a single place or method in the JTable class. The code uses a combination of if/else and switch statements.
Similar Messages
-
Use ComboBox TableCellEditor - values are not saved to the table model
Hi,
I got a combobox cell editor that uses to edit one of the columns.
And i got an ok button that uses to collect the data from the table and save it to the db.
In case i started editing of a cell and the editor is still displayed- if i will click on the button the data that will be colected from the table model will not contained the updated value in the cell editor.
In this case the user think his changes were saved but the last updated field is not updated.
Is this a bug i got in the cell editor or this is the normal behaviour?
Can it be fixed? (So that if the cell is in the middle of editing the value that will be saved is the last value that was selected).
public class PriorityCellEditor extends StandardComboBox implements TableCellEditor {
private boolean isEditMode=false;
* A list of eventlisteners to call when an event is fired
private EventListenerList listenerList = new EventListenerList();
* the table model
public StbAreaClusterPriorityCellEditor(boolean isEditMode) {
super(StbAreaMapper.clustersPriorities);
setEditMode(isEditMode);
setEditable(false);
this.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
setAlignmentX(Component.LEFT_ALIGNMENT);
public boolean isEditMode() {
return isEditMode;
public void setEditMode(boolean editMode) {
isEditMode = editMode;
setEnabled(editMode);
public Component getTableCellEditorComponent(JTable table, Object value,boolean isSelecte, int row, int column) {
int selectedIndex;
if (isSelecte) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
if(value instanceof String){
selectedIndex=StbAreaMapper.mapGuiPriorityDescToGuiCode((String)value);
setSelectedIndex(selectedIndex);
return this;
public void cancelCellEditing() {
fireEditingCanceled();
public Object getCellEditorValue() {
return getSelectedItem();
public boolean isCellEditable(EventObject anEvent) {
return isEditMode;
public boolean shouldSelectCell(EventObject anEvent) {
return false;
public boolean stopCellEditing() {
fireEditingStopped();
return true;
* Adds a new cellEditorListener to this cellEditor
public void addCellEditorListener(CellEditorListener l) {
listenerList.add(CellEditorListener.class, l);
* Removes a cellEditorListener from this cellEditor
public void removeCellEditorListener(CellEditorListener l) {
listenerList.remove(CellEditorListener.class, l);
* Notify all listeners that have registered interest for notification on
* this event type.
* @see javax.swing.event.EventListenerList
protected void fireEditingStopped() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == CellEditorListener.class) {
((CellEditorListener) listeners[i + 1]).editingStopped(
new ChangeEvent(this));
* Notify all listeners that have registered interest for notification on
* this event type.
* @see javax.swing.event.EventListenerList
protected void fireEditingCanceled() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying those that are interested in this event
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == CellEditorListener.class) {
((CellEditorListener) listeners[i + 1]).editingCanceled(new ChangeEvent(this));
}Try this
yourTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); -
Hi,
i m leaning JTable recently, following is an experimental code which i wrote, it has a custom table model and custom tablecellrenderer, the custom tablecellrender determine the column of # of Years greater or equal than 5 should display color green, less than 5 should display color red, it works well, however, the custom table model should be smart enough to know that the # of Years column contains numbers (which should generally be right aligned and have a particular format), it also should know that the Vegetarian column contains boolean values, which can be represented by check boxes, but it didn't, i don't know why, i have implement a getColumnClass method,
but it seems not work, have i make any mistakes? Any idea? Thanks
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import java.awt.Color;
import java.util.Vector;
public class CellRenderTestVector extends JFrame {
protected JTable table;
protected int width = 100;
protected MyCustomTableModel model;
public CellRenderTestVector() {
JPanel pan0 = new JPanel(new BorderLayout());
Container contentPane = getContentPane();
pan0.setPreferredSize(new Dimension(500,200));
model = new MyCustomTableModel();
table = new JTable();
table.setAutoCreateColumnsFromModel(false);
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumn column = null;
for (int i = 0; i < model.getColumnCount(); i++) {
DefaultTableCellRenderer renderer = new
ColoredTableCellRenderer();
column = new TableColumn(i,
width, renderer, null);
table.addColumn(column);
TableColumn t_column = table.getColumnModel().getColumn(2);
System.out.println(table.getColumnModel());
JScrollPane scrollPane = new JScrollPane(table);
pan0.add(scrollPane, BorderLayout.CENTER);
contentPane.add(pan0);
public class ColoredTableCellRenderer extends DefaultTableCellRenderer {
public void setValue(Object value) {
Color m_color;
Color GREEN = new Color(0, 128, 0);
Color RED = Color.red;
if (value instanceof Integer) {
Integer m_data = (Integer)value;
m_color = m_data.intValue() >= 5 ? GREEN : RED;
setForeground(m_color);
setText(m_data.toString());
else {
super.setValue(value);
public class Columndata {
protected String m_title;
public Columndata(String title) {
m_title = title;
public class Rowdata {
protected String fname;
protected String lname;
protected String sport_type;
protected Integer no_year;
protected Boolean vegetarian;
public Rowdata(String fn, String ln,
String sp, int ny, boolean vg) {
fname = fn;
lname = ln;
sport_type = sp;
no_year = new Integer(ny);
vegetarian = new Boolean(vg);
public class MyCustomTableModel extends AbstractTableModel {
protected final Columndata m_column[] =
{new Columndata("First Name"),
new Columndata("Last Name"),
new Columndata("Sport"),
new Columndata("# of Years"),
new Columndata("Vegetarian")
protected Vector m_vector;
public MyCustomTableModel() {
m_vector = new Vector();
setDefaultData();
public void setDefaultData() {
m_vector.removeAllElements();
m_vector.addElement(new Rowdata("Mary", "Campione",
"Snowboarding", 5, false));
m_vector.addElement(new Rowdata("Alison", "Huml",
"Rowing",3,true));
m_vector.addElement(new Rowdata("Kathy", "Walrath",
"Knitting",2, false));
m_vector.addElement(new Rowdata("Sharon", "Zakhour",
"Speed reading",20,true));
m_vector.addElement(new Rowdata("Philip", "Milne",
"Pool",10,false));
public int getColumnCount() {
return m_column.length;
public int getRowCount() {
return m_vector==null ? 0 : m_vector.size();
public String getColumnName(int col) {
return m_column[col].m_title;
public Object getValueAt(int nRow, int nCol) {
if (nRow < 0 || nRow>=getRowCount()) return "";
Rowdata row = (Rowdata)m_vector.elementAt(nRow);
switch (nCol) {
case 0: return row.fname;
case 1: return row.lname;
case 2: return row.sport_type;
case 3: return row.no_year;
case 4: return row.vegetarian;
return "";
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception evt) {}
JFrame f = new CellRenderTestVector();
f.setTitle("TableTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}You need to write your custom TableCellRenderes/Editors for each type. And don't forget to register your custom renderes via myTable.setDefaultRendere().
-
JTable with custom column model and table model not showing table header
Hello,
I am creating a JTable with a custom table model and a custom column model. However the table header is not being displayed (yes, it is in a JScrollPane). I've shrunk the problem down into a single compileable example:
Thanks for your help.
import javax.swing.*;
import javax.swing.table.*;
public class Test1 extends JFrame
public static void main(String args[])
JTable table;
TableColumnModel colModel=createTestColumnModel();
TestTableModel tableModel=new TestTableModel();
Test1 frame=new Test1();
table=new JTable(tableModel, colModel);
frame.getContentPane().add(new JScrollPane(table));
frame.setSize(200,200);
frame.setVisible(true);
private static DefaultTableColumnModel createTestColumnModel()
DefaultTableColumnModel columnModel=new DefaultTableColumnModel();
columnModel.addColumn(new TableColumn(0));
return columnModel;
static class TestTableModel extends AbstractTableModel
public int getColumnCount()
return 1;
public Class<?> getColumnClass(int columnIndex)
return String.class;
public String getColumnName(int column)
return "col";
public int getRowCount()
return 1;
public Object getValueAt(int row, int col)
return "test";
public void setValueAt(Object aValue, int rowIndex, int columnIndex)
}Edited by: 802416 on 14-Oct-2010 04:29
addedKleopatra wrote:
jduprez wrote:
See http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setHeaderValue(java.lang.Object)
When the TableColumn is created, the default headerValue is null
So, the header ends up rendered as an empty label (probably of size 0 if the JTable computes its header size based on the renderer's preferred size).nitpicking (can't resist - the alternative is a cleanup round in some not so nice code I produced recently <g>):
- it's not the JTable's business to compute its headers size (and it doesn't, the header's the culprit.) *> - the header should never come up with a zero (or near-to) height: even if there is no title shown, it's still needed as grab to resize/move the columns. So I would consider this sizing behaviour a bug.*
- furthermore, the "really zero" height is a longstanding issue with MetalBorder.TableHeaderBorder (other LAFs size with the top/bottom of their default header cell border) which extends AbstractBorder incorrectly. That's easy to do because AbstractBorder itself is badly implemented
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459419
Thanks for the opportunity to have some fun :-)
JeanetteNo problem, thanks for the insight :) -
JButton in JTable with custom table model
Hi!
I want to include a JButton into a field of a JTable. I do not know why Java does not provide a standard renderer for JButton like it does for JCheckBox, JComboBox and JTextField. I found some previous postings on how to implement custom CellRenderer and CellEditor in order to be able to integrate a button into the table. In my case I am also using a custom table model and I was not able to create a clickable button with any of the resources that I have found. The most comprehensive resource that I have found is this one: http://www.java2s.com/Code/Java/Swing-Components/ButtonTableExample.htm.
It works fine (rendering and clicking) when I start it. However, as soon as I incorporate it into my code, the clicking does not work anymore (but the buttons are displayed). If I then use a DefaultTableModel instead of my custom one, rendering and clicking works again. Does anyone know how to deal with this issue? Or does anyone have a good pointer to a resource for including buttons into tables? Or does anyone have a pointer to a resource that explains how CellRenderer and CellEditor work and which methods have to be overwritten in order to trigger certain actions (like a button click)?
thanksYes, you were right, the TableModel was causing the trouble, everything else worked fine. Somehow I had this code (probably copy and pasted from a tutorial - damn copy and pasting) in my TableModel:
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 3) {
return false;
} else {
return true;
}A pretty stupid thing when you want to edit the 3rd column... -
JTable: Custom Table Model (pII)
As was explained in pI, I'm creating a custom table model to overcome a few pitfalls I came across using the DefaultTableModel class, such as aligning cells, and getting certain columns to return only numeric type data. However, I've come upon a few roadblocks myself.
How do I create each of the following methods:
insertRow(int ow, int column)
remove row(int row)
addRow(Object[] rowData)Assuming that I decide to allow the user to add a column to the table, how would I create the methodaddColumn(Object columnName, Object[] columnData)And also, as I'm creating a custom table model, would I need to replicate DefaultTableModel's methods that inform the listeners that a change has been made to the table?
Thanks!Thanks!
I just got this response. Anyways, I found another solution that was, interestingly, from one of your threads written in 2005.
This is what I did:
// Letting the JTable know what each column stores and should return by
// overloading the getColumnClass() method
public Class getColumnClass(int column)
if(recordsTable.getColumnName(column) == "Ranking")
return Integer.class;
/* Why do I keep ketting an IllegalArgumentException here? *
* It keeps saying it cannot format given object as a Number */
else if(recordsTable.getColumnName(column) == "Price (�) ")
return Float.class;
else
return getValueAt(0, column).getClass();
}However, another problem has arisen.
The if method for the int column (Ranking column) works okay, and is even right-aligned. The else if arguments for the Price (�) column however is returning an IllegalArgumentException. This I just cannot figure out.
Here's the code:package Practice;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.MenuShortcut;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent; // for MenuItem shortcuts
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane; // JTable added to it, aiding flexibility
import javax.swing.JTable; // The personally preferred GUI for this purpose
// Provides a basic implementation of TableModel
import javax.swing.table.DefaultTableModel;
// This class uses Vector to store the rows and columns of data, though
// programmer will be using LinkedLists
import java.util.LinkedList;
// User-defined classes
import Practice.MusicDatabase;
public class MusicBank extends Frame implements ActionListener
MusicDatabase mDBase;
Frame frame;
String title = "", // Frame's title
file = ""; // pathname of the file to be opened
// Declaring Menu and MenuItem variables
Menu recordM; // ...
// recordM
MenuItem newRecordR_MI, deleteRecordR_MI;
// Other irrelevant menus and sub items
DefaultTableModel recordDetails;
JTable recordsTable;
LinkedList musicList;
public MusicBank()
musicList = new LinkedList();
frame = new Frame(title);
frame.setMenuBar(menuSystem());
// Should user seek to close window externally
frame.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent we)
frame.dispose();
System.exit(0);
recordDetails = new DefaultTableModel();
// Creating the relevant columns
recordDetails.addColumn("Title");
recordDetails.addColumn("Identity");
recordDetails.addColumn("Music Company");
recordDetails.addColumn("Ranking");
recordDetails.addColumn("Price (�) ");
// Ensuring the table has at least one visible record (empty)
recordDetails.addRow(populateRow("", "", "", 0, 0.00f));
// Creating the table to display the data files (music record details)
recordsTable = new JTable(recordDetails)
// Letting the JTable know what each column stores and should return by
// overloading the getColumnClass() method
public Class getColumnClass(int column)
if(recordsTable.getColumnName(column) == "Ranking")
return Integer.class;
/* Why do I keep ketting an IllegalArgumentException here? *
* It keeps saying it cannot format given object as a Number */
else if(recordsTable.getColumnName(column) == "Price (�) ")
return Float.class;
else
return getValueAt(0, column).getClass();
// Creating the menus
public MenuBar menuSystem()
MenuBar bar = new MenuBar();
// Record menu and related items
recordM = new Menu("Record");
recordM.setShortcut(new MenuShortcut(KeyEvent.VK_R, false));
newRecordR_MI = new MenuItem("New record");
newRecordR_MI.setShortcut(new MenuShortcut(KeyEvent.VK_N, false));
deleteRecordR_MI = new MenuItem("Delete record");
deleteRecordR_MI.setShortcut(new MenuShortcut(KeyEvent.VK_D, false));
recordM.add(newRecordR_MI);
recordM.addSeparator();
recordM.add(deleteRecordR_MI);
// Enabling menus with functionality
newRecordR_MI.addActionListener(this);
deleteRecordR_MI.addActionListener(this);
// Adding menus and items to menu bar
bar.add(recordM);
return bar;
public void actionPerformed(ActionEvent ae)
if(ae.getSource() == newRecordR_MI)
newRecord();
else if(ae.getSource() == deleteRecordR_MI)
deleteRecord();
// Object that will be used, in conjunction with MusicDatabase's, to
// populate the JTable
// A record in a JTable is equivalent to an element in a LinkedList
public Object[] populateRow(String title, String name, String comp, int rank, float price)
// First, update the LinkedList
mDBase = new MusicDatabase(title, name, comp, rank, price);
musicList.add(mDBase);
// Then, update the table
// As the parameters of Object tableDetails can only take a String or
// object, rank and price will have to be cast as a String and later
// parsed to their original form before use.
String rankPT = ""+rank, pricePT = ""+price;
Object rowDetails[] = {title, name, comp, rankPT, pricePT};
return rowDetails;
public static void main(String args[])
MusicBank app = new MusicBank();
// Using the platform's L&F (if Win32, Windows L&F; Mac OS, Mac OS L&F,
// Sun, CDE/Motif L&F)
// For more on this, refer to the WinHelp Java tutorial by F. Allimont
try
UIManager.getSystemLookAndFeelClassName();
catch(Exception e)
JOptionPane.showMessageDialog(app,
"Failed to create the Windows Look and Feel for this program",
"Look and Feel (L&F) error",
JOptionPane.ERROR_MESSAGE);
app.frame.setSize(500, 500);
app.frame.setVisible(true);
// Placing frame in the centre of the screen on-loading
app.frame.setLocationRelativeTo(null);
// action methods per menu items
// Also, why do I keep getting an ArrayIndexOutOfBoundsException
// here? I do know what this exception is, and how it works, but just cannot
// understand what is causing it
public void newRecord()
// Before adding a new record, check if previous record has complete
// entries. If not, either display a message (JOptionPane) or disallow
// request (simply do nothing)
// Proceed based on assesment
if(queryState() == true)
// Inform user that all entries need to be filled in before a new
// record can be created
JOptionPane.showMessageDialog(this, // current frame
"There are incomplete cells in the table."+
"\nPlease fill these in before proceeding", // Message to user
"Incomplete entries", // Title
JOptionPane.ERROR_MESSAGE); // Relevant icon
else
// To ensure that both the linked list & the table are simultaneously
// updated, JOptionPane's input dialogs are used to temporarily store
// the data which is then inputted into both (linked list and JTable)
String titleN, identityN, companyN; int rankN; float priceN;
titleN = JOptionPane.showInputDialog(this, "Enter song title");
identityN = JOptionPane.showInputDialog(this, "Enter name of singer/band");
companyN = JOptionPane.showInputDialog(this, "Enter signed/unsigned company");
rankN = Integer.parseInt( JOptionPane.showInputDialog(this,
"Enter rank (a number)") );
System.out.println("\n JTable rows = "+recordDetails.getRowCount());
// Ensuring that the chosen rank is not already entered
/* Problem lies here */
for(int row = 1; row <= recordDetails.getRowCount(); ++row)
if((recordDetails.getValueAt(row, 4)).equals(""+rankN))
rankN = Integer.parseInt( JOptionPane.showInputDialog(this,
"That number's already chosen.\nPlease enter a rank ") );
priceN = Float.parseFloat( JOptionPane.showInputDialog(this, "Finally, enter price �") );
mDBase = new MusicDatabase(titleN, identityN, companyN, rankN, priceN);
musicList.add(mDBase);
recordDetails.addRow(populateRow(titleN, identityN, companyN, rankN,
priceN));
System.out.println("JTable rows after creation = "+
recordDetails.getRowCount());
// Enabling the delete record menu item (as necessary)
if((recordsTable.getRowCount()) > 0)
deleteRecordR_MI.setEnabled(true);
} // newRecord()
public void deleteRecord()
int selectedRow = recordsTable.getSelectedRow();
recordDetails.removeRow(selectedRow);
// Removing the element from the LinkedList's corresponding index
musicList.remove(selectedRow);
System.out.println("Existing rows = "+recordsTable.getRowCount());
// If there are no more rows, disallow user from trying to delete rows
if(selectedRow <= 0)
deleteRecordR_MI.setEnabled(false);
} // deleteRecord()
// Method to query if all cells have changed their states (empty or not)
public boolean queryState()
// Obtaining number of rows
int rows = recordDetails.getRowCount();
int columns = recordDetails.getColumnCount();
boolean isEmpty = false; // cell
System.out.println("Rows = "+rows);
System.out.println("Columns = "+columns);
try{
// Assessing all cells for complete entries
// This approach is flexible, rather than hardcoding the rows available,
// making it more reusable (assuming it will always be 5 columns)
for (int rowIndex = 0; rowIndex<=rows; ++rowIndex)
if((recordDetails.getValueAt(rowIndex, 1)).equals(""))
isEmpty = true;
else if((recordDetails.getValueAt(rowIndex, 2)).equals(""))
isEmpty = true;
else if((recordDetails.getValueAt(rowIndex, 3)).equals(""))
isEmpty = true;
else if((recordDetails.getValueAt(rowIndex, 4)).equals("0"))
isEmpty = true;
else if((recordDetails.getValueAt(rowIndex, 5)).equals("0.00"))
isEmpty = true;
catch(Exception e)
System.out.println(e.getMessage());
return isEmpty;
Now here is the code for the MusicDatabase class
package Practice;
class MusicDatabase
private String songTitle, identity, musicCompany;
private int rank;
private float priceF;
// Defining the constructor
public MusicDatabase(String title, String name, String company, int rankingInt, float price)
songTitle = title;
identity = name;
musicCompany = company;
rank = rankingInt;
priceF = price;
} // constructor
// Other methods
} // class MusicDatabaseSorry, but am not sure if these codes are executable, as where I am (a general library), JVM is not on the machine I am using. (Remember, i don't have ready acess to the Internet, so I could not use my machine, nor the facilities that had the JVM - unavailable to me at the time).
Thanks!
Reformer...
PS I do hope the code pasted was not too much. Kind regards.... -
Can we access tables created internally for Business objects in CAF
Hi,
When we create and Deploying Business objects in CAF then internally it creates tables in Oracle/Maxdb database. Can we access those tables through CAF.
Or is it possible for Oracle to access the Business objects tables which are deployed on SAP Web Application server?
We can configure the Oracle driver in the SAP Web App Server. But how can we use it?Hi Rohit!
Can we access the tables created internally for BO's without the use of CRUD methods provided by them.?
Or
Can we fire queries on these tables through Oracle.? As the tables are created along with BO's in the database.
Maybe, you can do that, but why do you want to do that?
Based on the Entity Services (i.e., CRUD and find operations) that are generated for your BOs, you can implement Application Services which contain any business operation that you want to perform. Furthermore, you can expose your Application Services as Web Services. That's the designated way to do that.
Manually manipulating the underlying database tables does not sound like a good idea.
Best regards
Alexander -
Physical/Logical model that implement oracle database
Dear Forum's member,
I need documentation where I can see a grafical or a figure of the Physical/Logical relationship model that implement the Oracle object internally. It's not an specific example. It's about how oracle store the objects that it manage and are they related to the others.
Best regards,
José GuillénI once used Erwin Design tool which can help in your task. I do not know if this is still around, since I used it in 2005.
-
Using Table Model as a Grid?
Would it be possible to add JButtons(or JPanels) to create cells in a Table Model implementation? How would I go about this? Would I then be able to listen for events from these JButtons using the methods native to table model such as getValueAt(int row, int col) etc.
What I am trying to do is to implement a grid of 10X10 cells for a battleship game so that the user can click on cells on the grid and that this will trigger an event specifying to user whether it was a hit or miss etc. and change the color of cell (JButton) based on hit/miss etc.
Any help would be appreciated.
Thanks.Well you need:
1) a custom cell renderer class that is able to manage the change of background and the contents of the cell by itself
2) a custom cell event listener that allows you to get and process the messages.
You can find a full-featured example at the address: http://www.java2s.com/Code/Java/Swing-JFC/TableEditorEditableColorColumn.htm -
Custom Table Model from Default Table Model
I'm creating a customised table model to create a table with column header and empty rows.But it is throwing Component paint_imediatly error.If i pass in empty string to the row vector then setNumRows then no problem. If i do like this later it throws me error in my addNewRow method which was working fine before.Can anyone help?I would realy apreaciate it.Thank you.
KavithaThis must be your lucky day :)
Here is my version of an EditableTableModel which displays an emptyline as the last line
import java.io.*;
import java.util.*;
import javax.swing.table.*;
import javax.swing.event.*;
* Custom TableModel, allows addition and removal of records/rows and editting of existing values.
* it also keeps track over which rows have been altered.
* column 0 is a boolean indicating wheter or not to keep this row/record
* @author Maurice Marrink
* @version 1.0
public class EditableTableModel extends AbstractTableModel implements Serializable, TableModelListener
protected ArrayList keep,changed; //houden bij of een rij gedel moet worden en of ie is veranderd (false = delete)
protected ArrayList[] DATA;
protected int emptyLineIndex;
protected String[] kolomNamen;
protected Object[] kolomTypen; // bevat een object van dezelfde class als die kolom
protected int newRowsIndex; // houd bij vanaf welke rij niewe regels zijn toegevoegd ivm het opslaan in de db
protected int[]primecolumns; //houd bij welke kolommen ingevuld moeten worden voordat de volgende regel getoond wordt (default= kolom 1)
public EditableTableModel()
keep = new ArrayList(); //visible
changed=new ArrayList(); // not visisble
primecolumns=new int[0];
DATA=new ArrayList[0];
kolomNamen =new String[0];
kolomTypen=new Object[0];
emptyLineIndex=-1;
newRowsIndex=-1;
* the constructor, creates a new EditableTableModel
*@param data an array of ArrayLists each arrayList contains the values of an entire column
*@param names an array containg the names of the columns
*@param type an array containing Objects which correspond to the objects in the columns
public EditableTableModel(ArrayList[] data, String[] names, Object[] type)
keep = new ArrayList(); //visible
changed=new ArrayList(); // not visisble
primecolumns=new int[1];
primecolumns[0]=1;
DATA=data;
for(int i=0;i<getRowCount();i++)
keep.add(new Boolean(true));
changed.add(new Boolean(false));
kolomNamen=names;
kolomTypen=type;
emptyLineIndex=getRowCount()-1;
addNewLine();
newRowsIndex=emptyLineIndex; // nieuwe regels beginnen op de lege regel
addTableModelListener(this);
* @return the number of rows/records
public int getRowCount()
return DATA[0].size();
*@return the number of columns
public int getColumnCount()
return DATA.length+1;
* returns the object containing the value for this cell
* indexes start at 0 (wheter or not to keep this row), but the actual data starts at 1
*@param row the row in which the cell resides
*@param column the column in which the cell resides
*@return the value of the cell wrapped in the appropiate Object
public Object getValueAt(int row, int column)
if(column==0)
return keep.get(row);
else
return DATA[column-1].get(row);
* allows editing of an existing value
*@param value the new value, should be of the same Object Type as the existing one
*@param row the row nr of the cell
*@param col the column nr of the cell
public void setValueAt(Object value, int row, int col)
if(col==0)
keep.set(row,value);
else
DATA[col-1].set(row,value);
changed.set(row, new Boolean(true));
fireTableCellUpdated(row, col);
* adds a new "empty" row after all the PrimeColums of the last row have been filled with an acceptable value
*@see setPrimeColumns
protected void addNewLine()
try
for(int i=0;i<DATA.length;i++)
if(kolomTypen[i] instanceof Integer)
DATA.add(new Integer(-1));
else
if(kolomTypen[i] instanceof Boolean)
DATA[i].add(new Boolean(false));
else
if(kolomTypen[i] instanceof Long)
DATA[i].add(new Long(-1)); //displayed as "" by cellrenderer
else
DATA[i].add(kolomTypen[i].getClass().newInstance()); //nieuw object aanmaken van het type dat gespecificeerd is, Integers en Booleans moet een waarde meegegeven worden
keep.add(new Boolean(true));
changed.add(new Boolean(false));
emptyLineIndex++;
catch(Exception e)
e.printStackTrace();
public void tableChanged(TableModelEvent e)
if(e.getFirstRow()==emptyLineIndex)//alleen als de emptyLine ge?dit wordt een regel toevoegen
boolean primesfilled=true;
for(int i=0;i<primecolumns.length;i++)
if(getValueAt(emptyLineIndex,primecolumns[i]).equals(null) || getValueAt(emptyLineIndex,primecolumns[i]).toString().equals("")|| getValueAt(emptyLineIndex,primecolumns[i]).toString().equals("-1"))
primesfilled=false;
break;
if(primesfilled) //alleen als de primaire sleutel kolommen ingevuld zijn
addNewLine();
* returns the Class type of the Objects representing the column type
*@param c the column nr
public Class getColumnClass(int c)
if(c==0)
return new Boolean(true).getClass();
else
return kolomTypen[c-1].getClass();
*@param rowIndex the index of the row
*@param columnIndex the index of the column
*@return true if a cell is Editable,false otherwise (all cells are Editable)
public boolean isCellEditable(int rowIndex, int columnIndex)
return true;
* returns the name of the column
*@param column the column index
*@return a String containing the name of the column
public String getColumnName(int column)
if(column==0)
return "";
else
return kolomNamen[column-1];
*@return wheter or not 1 or rows is marked for deletion
public boolean deletionNeeded()
Boolean B;
for(int i=0;i<emptyLineIndex;i++)
B=(Boolean)keep.get(i);
if(!B.booleanValue())
return true;
return false;
* Deletes all rows which are marked for deletion
*@return the number of rows that have been deleted
public int deleteMarkedRows() // zou niets uit moeten maken of je eerst deleteMarkedRows() of isSavedToDB(true) aanroept
int aantalRows=0;
Boolean B;
for(int i=0;i<emptyLineIndex;i++)
B=(Boolean)keep.get(i);
if(!B.booleanValue())
if(deleteRow(i))
aantalRows++;
i--;
return aantalRows;
* deletes a single row
*@param row the row index
*@return true if the row was deleted, false otherwise
protected boolean deleteRow(int row)
boolean result=false;
if(row==emptyLineIndex) // emptyline kan niet gedelete worden
return result;
try
for(int j=0;j<DATA.length;j++)
DATA[j].remove(row);
changed.remove(row);
keep.remove(row);
emptyLineIndex--;
if(row < newRowsIndex)
newRowsIndex--;
result=true;
catch(Exception e)
e.printStackTrace();
return result;
* returns if the row has changed or not
*@param row the row index
*@return true if 1 or more cells in this row had their value changed or if 1 or more rows were added, false otherwise
public boolean hasChanged(int row)
Boolean B=(Boolean)changed.get(row);
return B.booleanValue();
* Methode waarmee men kan bepalen of 1 van de originele waarden ook veranderd is.
* Het geeft dus niet aan of er ook nieuwe rijen zijn toegevoegd.
public boolean hasChanged()
Boolean B;
for(int i=0;i<newRowsIndex;i++)
B=(Boolean)changed.get(i);
if(B.booleanValue())
return true;
return false;
* if true it sets all flags indicating a change to false, else nothing
*@param saved boolean indicating all changes are now to be considerd to be the original values, or not
public void isSavedToDB(boolean saved)
if(saved)
for(int i=0; i<changed.size();i++)
changed.set(i,new Boolean(false));
newRowsIndex=emptyLineIndex;
* @return the row nr. at which newly added entrys begin, updated after isSavedToDB(true) is called
public int getNewRowsIndex()
return newRowsIndex;
* allows the specification of certain columns that need to be filled in, if not a new row will not be made vissible
*@param columns an array containing the column indexes which must be set to a valid value
public void setPrimeColumns(int[] columns)
primecolumns=columns;
* allows retrieval of the PrimeColumns
*@return an arrayof int containing the column indexes
public int[] getPrimeColumns()
return primecolumns;
Ok some of the comments are in dutch go ahead an blame me :(
if you have any questions, just ask.
i also have a TableModel which can use automatic numbering
Oh numbers (currently only Integer and Long) are initiated wth a value of -1 if you want to display them as blank cells like i wanted to you modify a cellrenderer (or use mine)
Mr Mean -
Forgive me if this question has been asked before, but I was wondering if anyone else is experiencing problems with Matisse and Table Models?
After years of building GUIs by hand, I have begun to experiment with Matisse. One of the simple forms I am building contains a couple of JTables; the data for each provided by an instance of a subclass of AbstractTableModel that I already use successfully in an existing application. Running the form sees the model(s) supplying the data correctly but I cannot edit anything. The isCellEditable() method has been overloaded to return true all of the time but it is simply never being called when the user interacts with the form.
Does anyone know if there is an easy - obvious - solution to this that will leave me feeling silly but help no end? Thanks in advance.Hello Zadok and thanks for the reply.
Yes, it would be easier but I have tried doing that and still experience the same problem. It seems as though the edits are not being posted through the the table model. Does anyone know if I have to explicitly implement editors for each cell? Is there a setting in the list of properties that I should be using - by the way, I have layed around with these options a bit to no effect. -
hi all
i have a list of doubts
im designing an appln which displays a JTable , the data for the table is got from the database server, im using the Abstracttable model
i went for abstract table model since in my application the contents of the table very frequently , so i can handle it using the
firetabledatachanged or some fire functions
1)my doubt is where and when we have to use the abstracttable model and when we have to go for default table model
2) Now im keeping a button in my application if i press that ,a new row
have to be added at the end of that table , how i can carry it on using abstract table model(i think ,In default table model we can do it using
addrow ( )or insert row())
thnks in advance
keonHi,
You can use DefaultTableModel in place of AbstractTableModel, coz the method fireDataChanged() which you need is present in DefaultTableModel also(inherited from AbstractTableModel , since it is its parent model), apart from that DefaultTableModel gives you convenience methods such as addRow(), insertRow(), removeRow(), which you can override to your convenience.
However the only constraint is that the DefaultTableModel uses a Vector of Vectors to hold its Model/Data, if you want a different datastructure to be used as underlying model then you should be careful enough to implement all the methods that you are going to call on that instance of DefaultTableModel, this is becuase all the default implementations of the methods of DefaultTableModel assume that the underlying datastructure is a Vector, so if you replace it with a Map or a List then you should provide appropriate implementation to all its methods that manipulate the underlying datastructure -
Can not insert or update [TABLE] from internal table in method
I've faced a problem with OO abap. I've tried to insert into [ TABLE ] from internal table, but i've got error msg after i compiled.
"An explicit work area is necessary in the OO context. Use "INSERT wa INTO [TABLE] itab""
After i changed to loop in work area and INSERT INTO [TABLE] VALUES gw_data., everything is fine, can compile and run.
This is error code.
METHOD set_data_to_table.
REFRESH gi_data.
CLEAR gi_data.
IF gi_file[] IS NOT INITIAL.
* Set data for modify table
LOOP AT gi_file INTO gw_file.
MOVE-CORRESPONDING gw_file TO gw_data.
me->conversion_input( EXPORTING im_vendor = gw_data-vendor
CHANGING ch_vendor = gw_data-vendor ).
APPEND gw_data TO gi_data.
ENDLOOP.
INSERT [TABLE] FROM TABLE gi_data.
* LOOP AT gi_data INTO gw_data.
* INSERT INTO [TABLE] VALUES gw_data.
* IF sy-subrc = 0.
* COMMIT WORK.
* ELSE.
* ROLLBACK WORK.
* ENDIF.
* ENDLOOP.
ELSE.
MESSAGE 'No data found' TYPE 'I'.
ENDIF.
ENDMETHOD. "set_data_to_tableHi Matthew,
I think there is no difference in database insert between OO and non-OO.
The correct syntax according to ECC600 online documentation is
[Inserting Several Lines|http://help.sap.com/saphelp_erp2005vp/helpdata/en/fc/eb3a6d358411d1829f0000e829fbfe/content.htm]
To insert several lines into a database table, use the following:
INSERT target FROM TABLE itab \[ACCEPTING DUPLICATE KEYS].
This writes all lines of the internal table itabto the database table in one single operation. If one or more lines cannot be inserted because the database already contains a line with the same primary key, a runtime error occurs. You can prevent the runtime error occurring by using the addition ACCEPTING DUPLICATE KEYS.
Whenever you want to insert more than one line into a database table, it is more efficient to work with an internal table than to insert the lines one by one.
I think the syntax
INSERT my_dbtable FROM TABLE gi_data.
should work, your suggestion may lead to syntax error.
Regards,
Clemens -
Adding data to a table model at run time
hiii
i want to add data to the table model at runtime.
i have used TableModel.My code looks like this
public class CaptureTableModel extends AbstractTableModel {
private String[] columnNames = { "No", "Source", "Destination", "Protocol",
"Flags" };
private TCPPacket tcpPacket;
private List data;
private static int counter = 0;
private int columnCount = columnNames.length;
public CaptureTableModel(){}
public CaptureTableModel(TCPPacket tcp) {
try{
tcpPacket=tcp;
counter++;
byte[] tcpdata = tcpPacket.getData();
String srcHost = tcpPacket.getSourceAddress();
String dstHost = tcpPacket.getDestinationAddress();
String tcpPacketData = new String(tcpdata, "ISO-8859-1");
if (tcpPacketData == null)
tcpPacketData = "";
int protocol = tcpPacket.getProtocol();
String proto = null;
if (protocol == 6)
proto = "TCP";
long sequenceNumber = tcpPacket.getSequenceNumber();
data = new ArrayList();
String[] info = {
Integer.toString(counter),
srcHost,
dstHost,
proto,
"[ACK " + tcpPacket.isAck() + " ; FIN " + tcpPacket.isFin()
+ " ; PUSH " + tcpPacket.isPsh() + " ; RESET "
+ tcpPacket.isRst() + " ; SYN " + tcpPacket.isSyn()
+ " ; URGENT " + tcpPacket.isUrg() };
data.add(info);
} catch (Exception e) {
e.printStackTrace();//return null;
public int getRowCount() {
return counter;
public int getColumnCount() {
return columnCount;
public String getColumnName(int column) {
return columnNames[column];
public Object getValueAt(int rowIndex, int columnIndex) {
System.out.println("the value in getValueAt"+((Object[])data.get(rowIndex))[columnIndex]);
return ((Object[])data.get(columnIndex))[rowIndex];
//return null;
the method getValueAt is not bieng called..where am i going wrong.
can anyone help me??Use the "code" formatting tags when posting code so the code retains its original formatting.
i want to add data to the table model at runtime.Use the DefaultTableModel it supports dynamic methods like addRow(...), removeRow(). -
Copyig Data from a TABLE MODEL (TABLE) TO A FILE
Hi guys,
I wont to copy data from a Default Table Model to a File can someone write a pease of code that will do that for me.
DefaultTableModel model = new DefaultTableModel();
JTable table;
public basic()
super();
model.addColumn("Full Name");
model.addColumn("House No");
model.addColumn("Address");
model.addColumn("Town/County");
model.addColumn("Postcode");
model.addColumn("Telephone Number");
model.addColumn("Email Address");
String[] socrates = { "Example", "33", "York RD", "Poole", "BH18 9RE", "01202776655", "[email protected]" };
model.addRow(socrates);
/**This is the main setup for the Address Book
*This has the main settings for the size, title
*And main features of the Address book.
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(new Dimension(800, 600));
this.setTitle("Large Print Address Book");
this.setLayout(new FlowLayout ());
//Main Application Parts
JLabel welcome = new JLabel("Welcome to Thomas's Address Book v2.0.1");
welcome.setFont(arial20);
this.add(welcome);
//Menu Bar
JMenuBar mb = new JMenuBar();
this.setJMenuBar(mb);
//Table
table = new JTable(model);
this.add(table);
JMenu fm = new JMenu("File");
fm.setFont(arial20);
mb.add(fm);
//Menu Items
JMenuItem Add = new JMenuItem("Add Record");
Add.setFont(arial20);
Add.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
addw a = new addw();
fm.add(Add);
//Import from a file
JMenuItem inp = new JMenuItem("Import Records");
inp.setFont(arial20);
inp.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
//Opens Import Window.
inportw i = new inportw();
fm.add(inp);
JMenuItem quit = new JMenuItem("Exit");
quit.setFont(arial20);
fm.add(quit);
quit.addActionListener(this);
class inportw extends JFrame
//*Add Window Properties and Settings
public inportw ()
this.setSize(new Dimension(400, 150));
this.setTitle("Inport Records");
this.setLayout(new FlowLayout ());
this.setVisible(true);
//Nmae
JLabel error_note = new JLabel("Error Here - Need to make table final!?");
error_note.setFont(arial20);
this.add(error_note);
//Add Button
JButton binport = new JButton("Inport");
binport.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
ArrayList data = new ArrayList();
this.add(binport);
public void actionPerformed(ActionEvent e)
System.out.println("Application Exit");
System.exit(0);
public static void main(String[] args)
basic b = new basic();
The information from the atable needs to go into a .txt file with each row on a new line. It also needs to be in the inport/export window that is in a class on its own when someone clicks export.
A complete peace of code would be helpfull that would do this for me. Thankyou guys.Rite then,
In answer to both post yes i have done my own homework if thats what you wont to call it.
And to the second post yes i have put in a File to export to. the code has not be pasted on my origanal post.
//Export Button - Export Window
JButton bexport = new JButton("Export (BUAB)");
bexport.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
System.out.println("Export Pressed ");
try
FileWriter file = new FileWriter("AddressData.txt");
BufferedWriter out = new BufferedWriter(file);
out.write("AddressBook data File");
out.close();
catch (Exception ei)
System.err.println("Error: " + ei.getMessage());
this.add(bexport);This is the export button,
I think the code for the table model should be something like this:
I wont to do something like this
model.getModel().getValueAt(0, 0);
Arrylist data = new arrylist();
try
FileWriter ffile = new FileWriter("AddressData.txt");
BufferedWriter out = new BufferedWriter(file);
out.write(data);
out.close();
catch (Exception ei)
System.err.println("Error: " + ei.getMessage());
} Im not 100% sure how to get the information from the model into the arrylist, though a loop.
If there is a section of a webpage that may help could someone please post it for me.
Unfortunatly for me Im visualy impaired and find some of this hard. I learn though looking at examples and creating my own programs that do something similar.
If no one wonts to help then that fine with me !
Maybe you are looking for
-
Multiple logical disks as custom objects
Hello All, I have been working with PowerShell for a few months now and my goal is to help my colleagues perform the same tasks a little faster. As such I took on the responsibility of creating a little GUI tool to find some details about a remote co
-
Does any Implemented SAP FIORI in ECC + Gateway Server
Hi Folks, Does any one implemented SAP FIORI Apps in below scenario where ECC (ODdata components) in Sand box and Gatewayserver (UI Components) Sand box as separate machines? We have configured Odata component (gbapp_poapproval) in ECC, and UI Compon
-
Bringing out colors on a black and white photos
I just got Photoshop elements 11 for Xmas. I've been attempting to have a single color or object colored in a black and white picture. I have gotten as far as making a duplicate layer and then creating a mask but don't know where to go from here. How
-
N86 8MP, Nokia Email 2.1.0, Access point troubles
I know that his has been an never ending saga. I just don't seem to be able to give it up. There is a well known issue about Nokia Email 2.1.0 not being able to define group access points. When I try to do that I am offered only particular access poi
-
Not urgent, just simple question.
Okay, just a curiosity, why will not the Goto login(); and similar sections of the code not work? Am I using a non-existant command? VB6 has ruined me.. import cs1.Keyboard; import java.io.*; public class Game public static void main (String[] a