JTableModel
I have a problem with my JTableModel. every time the first query returns no rows, the second query with some values is not able to create a new table model.
If the preceding rows have values, i can run as many queries as possible.
How do i sort this out?
public void getTable(){
//getting a select statement from a function that generates it from the GUI
String whereclause=getCriteria();
try {
model=new JTableModelClass(whereclause,columnNames);
table.setModel(model);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
table.setAutoCreateRowSorter(true);
table.getTableHeader().setReorderingAllowed(true);
if(scrollPane==null){
scrollPane = new JScrollPane();
scrollPane.setViewportView(table);
} else{
scrollPane.setViewportView(table);
scrollPane.setSize(900,400);
scrollPane.setBounds(0,0,900,400);
scrollPane.setWheelScrollingEnabled(true);
scrollPane.createHorizontalScrollBar();
this.jPanel3.add(scrollPane);
catch(Exception eta){
System.out.println("Error in setting a table model : "+eta.getMessage());
public class JTableModelClass extends AbstractTableModel {
Object [][] data;
JTable table;
Vector vectordata,rowdata;
String[] columnNames;
JDataBase db=new JDataBase();
/** Creates a new instance of JTableModelClass */
public JTableModelClass(String query, Vector colnames) {
columnNames=new String[colnames.size()];
String myquery=query;
String conn=db.connection.toString();
vectordata=db.getData(query);
for(int i=0;i<colnames.size();i++){
columnNames=(String)colnames.elementAt(i);
System.out.println("get no of rows");
int rows=db.no_rows;
Object row;
data=new Object[rows][columnNames.length];
if(rows==0){
System.out.println("No Such Data Found");
} else{
System.out.println("Some Data Found");
for(int i=0;i<rows;i++){
rowdata=(Vector)vectordata.elementAt(i);
for(int j=0;j<columnNames.length;j++){
data[i][j]=rowdata.elementAt(j);
System.out.println("making a table done");
public int getColumnCount() {
return columnNames.length;
public int getRowCount() {
return data.length;
public String[] getTableHeader(){
return columnNames;
public void addRow(Object[] row) {
for (int i=0; i<columnNames.length; i++) {
data[data.length+1][i] = row[i];
fireTableRowsUpdated(data.length+1,data.length+1);
public String getColumnName(int col) {
return columnNames[col];
public Object getValueAt(int row, int col) {
return data[row][col];
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
public static void main(String[] args) {
Don't multi-post.
My response in your last posting said "In The Future".
Anyway you where given an answer so there was no need to repost.
The DefaultTableModel does extend AbstractTableModel. So you copy your ResultSet to the DefaultTableModel.
Take time to understand the suggestion given to you before cluttering the forums with multiple postings.
hope everyone knows that the Abstract table model needs a rowData [][], which is a 2D arrayNo it doesn't. An AbstractTableModel does not provide any storage of the data which is why you need to implement all the methods yourself.
Similar Messages
-
Runtime Error in JTable with JTableModel Implementation
Hi,
I tried to do a JTable (named "table) in my program, with an implementation of JTableModel, called DataContent (obj named "dc"). Now if I try to change dc's data and refresh the table in the window by doing a "table.setModel(dc);", my programm gives me just runtime errors.
class MyFrame extends JFrame implements ActionListener{
// This is the class of the JFrame which contains the table
// globally defined vars:
private DataContent dc;
private final JTable table;
// in someMethod(){
public MyFrame(){
// creates, inits and draws the table into the window - this works !
JPanel jpPreview = new JPanel(new GridLayout(1,0));
dc = new DataContent();
table = new JTable(dc.getTableData(), dc.getCol());
table.setPreferredScrollableViewportSize(new Dimension(500, 40));
table.setBorder(borderPanel);
jpPreview.add(table);
jpSeparator.add(jpPreview);
public void actionPerformed(ActionEvent ae) {
// in the same class
if(ae.getSource() == butLoadPath){
// choose a path by clicking on a button "butLoadPath"
szPath = sg.readPath();
labelLoadPath.setText(szPath);
dc.setPath(szPath);
dc.setContent(szToken);
}else if(ae.getSource() == butSeparator){
// choose a different separator token by JRadioButtons
// when someone clicks on the button butSeparator,
// the table should be refreshed, with this function:
setPreview();
}else...
private void setPreview(){
// reads out which option was chosen by the radiobuttons - this works
// refreshes the Object[][] oData in dc - this works, too
dc.setContent(szToken);
// this should refresh the table obj in the JFrame,
// this gives me some Null.pointer.exception - why ?
table.setModel(dc);// ??? P R O B L E M ???
}I have implemented the Interface DataContent like this:
public class DataContent implements TableModel{
// vars
private int iRow,iCol;
private String szInputData = "";
char cToken, cLineLimiter;
private Object[][] oData;
// ctor
public DataContent(){
reset(); // set Elements...
public void setPath( String szPath){
// read line from file obj...
private void reset(){
// set up an epmty set of data in the table...
public void setContent( String szToken){
// separate content of szInputData by szToken and set oData...
public Object[][] getTableData(){
// return oData...
public String[] getCol(){
// gives some name for each column...
////////////////////////////////// automatic generated for the implementation of the interface JTableModel /////////////////
/* (non-Javadoc)
* @see javax.swing.table.TableModel#getRowCount()
public int getRowCount() {
// TODO Auto-generated method stub
return iRow;
/* (non-Javadoc)
* @see javax.swing.table.TableModel#getColumnCount()
public int getColumnCount() {
// TODO Auto-generated method stub
return iCol;
/* (non-Javadoc)
* @see javax.swing.table.TableModel#getColumnName(int)
public String getColumnName(int columnIndex) {
// TODO Auto-generated method stub
String[] szColumnName = getCol();
return szColumnName[columnIndex];
/* (non-Javadoc)
* @see javax.swing.table.TableModel#getColumnClass(int)
public Class getColumnClass(int columnIndex) {
// TODO Auto-generated method stub
return null;
/* (non-Javadoc)
* @see javax.swing.table.TableModel#isCellEditable(int, int)
public boolean isCellEditable(int rowIndex, int columnIndex) {
// TODO Auto-generated method stub
return false;
/* (non-Javadoc)
* @see javax.swing.table.TableModel#getValueAt(int, int)
public Object getValueAt(int rowIndex, int columnIndex) {
// TODO Auto-generated method stub
return oData[rowIndex][columnIndex];
/* (non-Javadoc)
* @see javax.swing.table.TableModel#setValueAt(java.lang.Object, int, int)
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
// TODO Auto-generated method stub
// NO editing !
/* (non-Javadoc)
* @see javax.swing.table.TableModel#addTableModelListener(javax.swing.event.TableModelListener)
public void addTableModelListener(TableModelListener l) {
// TODO Auto-generated method stub
/* (non-Javadoc)
* @see javax.swing.table.TableModel#removeTableModelListener(javax.swing.event.TableModelListener)
public void removeTableModelListener(TableModelListener l) {
// TODO Auto-generated method stub
}I tried to implement some of the automatic generated methods, without success, still the same problem. What can I do, that...
table.setModel(dc);
...works without probs ???
Is there a better way to do this - the table should not even be editable, just to be shown in the window, to give an impression ??
THXWhy are you creating you own TableModel. Use the DefaultTableModel its easier. If you don't want you cells to be editable then you just do this:
JTable table = new JTable(...)
public boolean isCellEditable(int row, int column)
return false;
}; -
Pls help in Refreshing JTableModel
I have defined 3 classes;
JDataBase
JTableModelClass
Expenditure
JDataBase class has the connection to the database and getData(String query) function.
JTableModel has a constructor with 2 parameters (String Query, Vector ColumnNames)
Expenditure is my UI class with JScrollPane and JTable which is being displayed.
*Problem</sOn the interface, i have a provision of the user specifying the columns he wants displayed. In case he wants to change the cols displayed, i have provided some checkboxes where after selecting/deselecting, a button click passes the query to the JTableModelClass which passes it to JDatabase class. The table is adjusted accordingly.
However, if i click on the colunm headers or the data rows, the initial table is displayed.
How cal i kill the first instance of the JTableModel before i run a fresh query? i.e. an equivalent of .dispose() method.
Why does it restore the first instance on table focus?Ok Ok..i get it now. i was giving my questions a logical approach and not a programming one.
1) JDataBase Class
public class JDataBase {
public static Connection connection;
public static Statement statement;
ResultSet resultSet;
int regNo=0;
String[] columnNames = {};
Vector rows = new Vector();
ResultSetMetaData metaData;
public int no_rows;
/** Creates a new instance of JDataBase */
public JDataBase() {
System.out.println("In JDataBase Class");
public boolean connected(String url, String driverName,
String user, String passwd) {
boolean state=false;
try {
Class.forName(driverName).newInstance();
System.out.println("Opening db connection");
connection = DriverManager.getConnection(url, user, passwd);
statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
state=true;
catch (ClassNotFoundException ex) {
state=false;
System.err.println("Cannot find the database driver classes.");
System.err.println(ex);
catch(InstantiationException ins){
System.err.println("Cannot Instantiate the Driver.");
catch(IllegalAccessException iae){
System.err.println("IllegalAccessException.");
catch (SQLException ex) {
state=false;
System.err.println("Cannot connect to this database.");
System.err.println(ex);
return state;
* closes the db connection
public void close() {
try{
System.out.println("Closing db connection");
if(resultSet!=null)
resultSet.close();
if(statement!=null)
statement.close();
if(connection!=null)
connection.close();
}catch(SQLException ex){
System.out.println(ex.getMessage());
* @param query String
* @return Object
* returns a collectionof any values selected from the database
public Vector getData(String query) {
no_rows=0;
if (connection == null || statement == null) {
System.err.println("There is no database to execute the query.");
return new Vector();
try {
resultSet = statement.executeQuery(query);
metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
columnNames = new String[numberOfColumns];
// Get the column names and cache them.
// Then we can close the connection.
for(int column = 0; column < numberOfColumns; column++) {
columnNames[column] = metaData.getColumnLabel(column+1);
// Get all rows.
rows = new Vector();
while (resultSet.next()) {
no_rows++;
Vector newRow = new Vector();
for (int i = 1; i <= numberOfColumns; i++) {
newRow.addElement(resultSet.getObject(i));
rows.addElement(newRow);
// close(); Need to copy the metaData, bug in jdbc:odbc driver.
catch (SQLException ex) {
System.err.println(ex);
return rows;
public static void main(String[] args) {
JDataBase JDataBase1 = new JDataBase();
2) JTableModelClass
public class JTableModelClass extends AbstractTableModel {
Object [][] data;
JTable table;
Vector vectordata,rowdata;
String[] columnNames;
JDataBase db=new JDataBase();
/** Creates a new instance of JTableModelClass */
public JTableModelClass(String query, Vector colnames) {
columnNames=new String[colnames.size()];
String myquery=query;
String conn=db.connection.toString();
vectordata=db.getData(query);
for(int i=0;i<colnames.size();i++){
columnNames=(String)colnames.elementAt(i);
int rows=db.no_rows;
Object row;
data=new Object[rows][columnNames.length];
if(rows==0){
System.out.println("No Such Data Found");
} else{
System.out.println("Some Data Found");
for(int i=0;i<rows;i++){
rowdata=(Vector)vectordata.elementAt(i);
for(int j=0;j<columnNames.length;j++){
//data[i][j]=vectordata.elementAt(i);
data[i][j]=rowdata.elementAt(j);
System.out.println("making a table done");
public int getColumnCount() {
return columnNames.length;
public int getRowCount() {
return data.length;
public String[] getTableHeader(){
return columnNames;
public void addRow(Object[] row) {
for (int i=0; i<columnNames.length; i++) {
data[data.length+1][i] = row[i];
fireTableRowsUpdated(data.length+1,data.length+1);
public String getColumnName(int col) {
return columnNames[col];
public Object getValueAt(int row, int col) {
return data[row][col];
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
3) Expenditure Class
public class Expenditures extends javax.swing.JFrame {
Vector fields;
JTable table;
String columns;
JScrollPane datascrollPane;
private void BtnOkActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayData();
public void displayData(){
String fieldstring=" ";
Vector queryfields=checkFields();
if(fields.size()==0){
JOptionPane.showMessageDialog(this,"No field has been Selected","Select Field", JOptionPane.OK_OPTION);
int j=0;
for(j=0;j<queryfields.size();j++){
if(j==queryfields.size()-1) {
fieldstring +=(String)queryfields.elementAt(j).toString()+" ";
} else{
fieldstring +=(String)queryfields.elementAt(j).toString()+",";
String query="Select "+fieldstring +"from card_balances.balances_alloc";
tablemodel=new JTableModelClass(query, queryfields);
table = new JTable(tablemodel);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
table.setAutoCreateRowSorter(true);
datascrollPane = new JScrollPane(table);
datascrollPane.setBounds(10,300,(int)d.getWidth()-50,360);
this.jPanel1.add(datascrollPane);
public Vector checkFields(){
fields=new Vector();
String field1,field2;
int i=0;
if(this.medicalaidcode.isSelected()){
fields.addElement(medicalaidcode.getActionCommand());
i++;
if(this.Amount_alloc.isSelected()){
fields.addElement(Amount_alloc.getActionCommand());
i++;
if(this.Expenditure.isSelected()){
fields.addElement(Expenditure.getActionCommand());
i++;
if(this.balances_alloc.isSelected()){
fields.addElement(balances_alloc.getActionCommand());
i++;
if(this.Pool_nr.isSelected()){
fields.addElement(Pool_nr.getActionCommand());
i++;
if(this.Familynumber.isSelected()){
fields.addElement(Familynumber.getActionCommand());
i++;
if(this.Scheme_startdate.isSelected()){
fields.addElement(Scheme_startdate.getActionCommand());
i++;
if(this.Scheme_endDate.isSelected()){
fields.addElement(Scheme_endDate.getActionCommand());
i++;
if(this.PrincipleName.isSelected()){
fields.addElement(PrincipleName.getActionCommand());
i++;
if(this.mem_nr.isSelected()){
fields.addElement(mem_nr.getActionCommand());
i++;
if(this.PercentageEx.isSelected()){
fields.addElement(PercentageEx.getActionCommand());
i++;
if(this.EmailedDate.isSelected()){
fields.addElement(EmailedDate.getActionCommand());
i++;
if(this.CounterEmail.isSelected()){
fields.addElement(CounterEmail.getActionCommand());
i++;
return fields;
public String checkParameters(){
String conditions="";
String criteria, selected, startdate, enddate;
selected=this.RadioGroup.getSelection().getActionCommand();
startdate=this.DateFrom.getDate().toString();
enddate=this.DateTo.getDate().toString();
conditions="where ";
if(selected=="RadioPerFamily"){
} else if(selected=="RadioPerClient"){
} else{
return conditions;
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Expenditures().setVisible(true); -
How can i create an event from a cell of JTable ?
Hi , I am having a JTable which has two types of render : checkboxCellRender and DefaultTableCellRenderer
i want to generate an event by clicking the checkbox which will do color changes for other cells . How can i do that ? Can i pass the events ?
code snippet :
class checkboxCellRenderExt extends checkboxCellRender
public checkboxCellRenderExt(){}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column)
JCheckBox c=(JCheckBox)super.getTableCellRendererComponent( table,value,isSelected,hasFocus,row, column);
JTableModel md = (JTableModel)m_TablePan.getTable().getModel();
Vector currentRow = md.getRow(row);
if(isSelected)
boolean m_bavail = ((Boolean)currentRow.get(COLUMN_TCM_STATUS)).booleanValue();
if(!m_bavail)
c.setForeground(Color.BLACK);
c.setBackground(Color.WHITE);
else
c.setForeground(table.getSelectionForeground());
c.setBackground(table.getSelectionBackground());
else
setForeground(table.getForeground());
setBackground(table.getBackground());
return this;
class CustomcellRenderer extends DefaultTableCellRenderer
public CustomcellRenderer()
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column)
checkboxCellRender chkbox =null;
JLabel lb;
Component c = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row, column);
if (value == null)
return c;
if (value instanceof String)
String s = (String) value;
lb = (JLabel)c;
lb.setBorder (noFocusBorder);
lb.setText(s);
JTableModel md = (JTableModel)m_TablePan.getTable().getModel();
Vector currentRow = md.getRow(row);
this.setHorizontalAlignment(JCheckBox.CENTER);
if(isSelected)
boolean m_bavail = ((Boolean)currentRow.get(COLUMN_TCM_STATUS)).booleanValue();
if(!m_bavail)
c.setForeground(Color.BLACK);
c.setBackground(Color.WHITE);
else
c.setForeground(table.getSelectionForeground());
c.setBackground(table.getSelectionBackground());
else
setForeground(table.getForeground());
setBackground(table.getBackground());
return this;
}Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.
Add a TableModelListener to the TableModel. An event is fired when the contents of the cell are changed. -
Updating the particular row and column in a JTable
Hi,
I have a JTable which is having fixed number of columns. When i am trying to update a particular cell in the table
during programm execution i am not able to do it.
I am getting the row number and column number correctly. But when i am going to set the data it is not setting at the same row. It is setting some other row according to the m_index (according to the sorting).
i am doing :
JTableModel model = (JTableModel) m_TablePan.getTableModel();
model.setValueAt(savedData, row, column);See the convertXxxIndexToView and convertXxxIndexToModel methods.
db
Edited by: Darryl.Burke -- wrong methods suggested
Edit2: Evidently lipumama doesn't follow up on many questions posted.
One for the blacklist. -
Hello, I am having a hard time getting my JTable to show up on my panel. There is a fair bit of code to wade through so I have put comments in all CAPS lined with an '*' so it should be easy to find where I am having my problems.
What I would like to do is have a new table row added each time the user enters a service and clicks a button. A service name and an integer for the durration of the service. Additonaly the opposite when the remove service button is clicked.
When running the app, click the employees tab; there is a NullPointerException error right now with the line
return getValueAt(0, c).getClass(); at line 904 once that tab is clicked.
Things to look for in my code are:
-westPanel
-westRight
-table
-MyTableModel
-scrollpane2
-(maybe servicePanel) undecided and it is commented out at this moment.
Any help would be greatly appreciated seeing that I know squat about JTables and the JTableModel.
Thanks in advance.
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.table.AbstractTableModel;
public class Administration extends JFrame implements ActionListener,ListSelectionListener,ItemListener {
private JTabbedPane jtp;
public String[] columnNames;
public Object[][] data;
public static JPanel servicePanel;
public static int checkRow;
private JPanel westPanel;
private JPanel westTop;
private JPanel westCenter;
private JPanel westCenterTop;
private JPanel westCenterBottom;
private JPanel westBottom;
private JPanel westBottomRight;
private JPanel westLeft;
private JPanel westRightTop;
private JPanel westRight;
private JPanel northPanel;
private JPanel centerPanel;
private JPanel centerRight;
private JPanel centerLeft;
private JPanel eastPanel;
private JPanel eastRight;
private JPanel eastLeft;
private JPanel eastBottom;
public static JPanel eastEastTop;
private JPanel eastEastCenter;
private JPanel southPanel;
private JPanel southTop;
private JPanel southLeft;
private JPanel southCenter;
private JPanel southBottom;
private GridBagLayout gbl;
private GridBagConstraints gbc;
//private JComboBox employees;
private JComboBox[] openAmPm = new JComboBox[7];
private JComboBox[] closedAmPm = new JComboBox[7];
private JComboBox startAmPm;
private JComboBox endAmPm;
private JComboBox cmbServices;
private JList employees;
private JList listEmpl;
private JList listServices;
private JList listDays;
private JList listSchedule;
//private Vector nameData;
private JScrollPane scrollpane;
private JScrollPane scrollpane2;
private JScrollPane scrollPane3;
private JScrollPane scrollPane4;
private JLabel lblEmployees;
public static JLabel lblEmployeeName;
public static JLabel lblMonthStat;
public static JLabel lblDay;
public static JLabel lblYear;
public static String service = null;
private JLabel lblLength;
private JLabel lblBizHours;
private JLabel lblServices;
private JLabel lblHoliday;
private JLabel lblOpen;
private JLabel lblClosed;
private JLabel lblsouthHeading;
private JLabel lblStartTime;
private JLabel lblEndTime;
private JLabel lblDayOff;
private JLabel space;
private JLabel space2;
private JLabel space3;
private JLabel space4;
private JLabel space5;
private JLabel blank1;
private JLabel blank2;
private JLabel colon;
private JLabel colon2;
private JLabel lblSelect;
private JLabel[] weekDay =new JLabel[7];
//private String[] fakeName = {"Leon","Mike","Lori","Shannon","Rob"};
private final static String[] dow = {"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"};
public static JTextField[] startHr = new JTextField[7];
public static JTextField[] startMin = new JTextField[7];
public static JTextField[] finishHr = new JTextField[7];
public static JTextField[] finishMin = new JTextField[7];
private JButton[] btnUpdate = new JButton[7];
private JButton btnAddEmployee;
private JButton btnNextDay;
private DefaultListModel nameData;
private DefaultListModel serviceData;
private DefaultListModel dayData;
private DefaultListModel holidayData;
private DefaultListModel scheduleData;
private static final String hireString="Add Employee";
private static final String fireString="Remove Employee";
private static final String addService="Add Service";
private static final String removeService="Remove Service";
private JButton fireButton;
private JButton hireButton;
private JButton addServices;
private JButton removeServices;
private JButton btnAttatch;
private JTextField employeeName;
private JTextField serviceName;
private JTextField txtOpenTime;
private JTextField txtClosedTime;
private int size;
public static String timeText;
private boolean result;
private boolean totalResult;
private String holidayMsg = "Here, you can select and \n schedule off days \n for employees from \n the list";
private String message1 = "Enter a maximum of \n 3 digits";
private String message2 = "Enter numbers only";
private String minutes=" min";
private String name;
private boolean dbRecord=true;
private int serviceSize;
private JCheckBox[] dayOff = new JCheckBox[7];
private int jlistCellWidth =100;
public static final int MAX_CHARS = 1;
private String myMonth;
public static boolean removed=false;
public Administration()
//jtp.setDefaultLookAndFeelDecorated(true);
checkRow = 0;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gbl = new GridBagLayout();
gbc = new GridBagConstraints();
//employees = new JComboBox();
//employees.setEditable(false);
cmbServices = new JComboBox();
startAmPm = new JComboBox();
startAmPm.addItem("AM");
startAmPm.addItem("PM");
startAmPm.setEditable(false);
endAmPm = new JComboBox();
endAmPm.addItem("AM");
endAmPm.addItem("PM");
endAmPm.setEditable(false);
employeeName=new JTextField("",10);
serviceName = new JTextField("",10);
txtOpenTime = new JTextField("",5);
txtClosedTime = new JTextField("",5);
nameData = new DefaultListModel();
holidayData = new DefaultListModel();
/** Eventualy put this into an isItemSelected function that retrieves names from
* the database
/*nameData.addElement("Leon");
nameData.addElement("Brenda");
nameData.addElement("Megumi");
nameData.addElement("jun");
//populate employee combobox with names from nameData
//int listSize = nameData.getSize();
/* for(int i=0;i<fakeName.length;i++)
nameData.addElement(fakeName);
//listEmpl.setSelectedIndex(i);
//String eName =(String)nameData.get(listEmpl.getSelectedIndex());
holidayData.addElement(fakeName[i]);
serviceData = new DefaultListModel();
dayData = new DefaultListModel();
listEmpl=new JList(nameData);
listEmpl.addListSelectionListener(this);
listServices = new JList(serviceData);
employees = new JList(holidayData);
employees.addListSelectionListener(this);
employees.setFixedCellWidth(jlistCellWidth);
listDays = new JList(dayData);
scheduleData = new DefaultListModel();
listSchedule = new JList(scheduleData);
listSchedule.setFixedCellWidth(jlistCellWidth);
dayData.addElement("Sunday");
dayData.addElement("Monday");
dayData.addElement("Tuesday");
dayData.addElement("Wednesday");
dayData.addElement("Thursday");
dayData.addElement("Friday");
dayData.addElement("Saturday");
// listEmpl.setSelectedIndex(0);
listDays.setSelectedIndex(0);
listSchedule.setSelectedIndex(0);
//listEmpl.addListSelectionListener(this);
listEmpl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listDays.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
employees.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
size = nameData.getSize();
//employeeName.setText("size is "+size);
listEmpl.setVisibleRowCount(5);
listDays.setVisibleRowCount(7);
employees.setVisibleRowCount(5);
listSchedule.setVisibleRowCount(5);
gbc.fill=GridBagConstraints.HORIZONTAL;
gbc.anchor=GridBagConstraints.CENTER;
//declare labels
lblLength = new JLabel("SERVICE LENGTH",lblLength.CENTER);
lblSelect=new JLabel("Select a name from the list",lblSelect.CENTER);
lblsouthHeading = new JLabel("EMPLOYEE SCHEDULE",lblsouthHeading.CENTER);
lblEmployees = new JLabel("CURRENT EMPLOYEES",lblEmployees.CENTER);
lblEmployees.setOpaque(true);
//lblEmployees.setBackground(Color.yellow);
lblServices = new JLabel("CURRENT SERVICES",JLabel.LEFT);
lblBizHours= new JLabel("BUSINESS HOURS",lblBizHours.CENTER);
lblStartTime = new JLabel("Open",lblStartTime.LEFT);
lblEndTime = new JLabel("Closed",lblEndTime.LEFT);
blank1 = new JLabel("");
blank2=new JLabel("");
lblHoliday = new JLabel(holidayMsg);
lblEmployeeName = new JLabel("Name");
//lblEmployeeName.setForeground(Color.white);
lblMonthStat = new JLabel("");
lblDay = new JLabel("");
lblYear = new JLabel("");
//check myCalendar method to see if a button has been clicked
lblMonthStat.setForeground(Color.white);
lblDay.setForeground(Color.white);
lblYear.setForeground(Color.white);
//declare buttons
JButton btnAttatch = new JButton("<html>Attatch service<br> to employee</html>");
btnAttatch.setBorder(BorderFactory.createRaisedBevelBorder());
JButton fireButton = new JButton(fireString);
JButton hireButton = new JButton(hireString);
JButton addServices = new JButton(addService);
JButton removeServices = new JButton(removeService);
addServices.addActionListener(this);
addServices.setActionCommand(addService);
removeServices.addActionListener(this);
removeServices.setActionCommand(removeService);
hireButton.addActionListener(this);
fireButton.setActionCommand(fireString);
fireButton.addActionListener(this);
JButton btnAddEmployee = new JButton("Add Employee");
fireButton.setBorder(BorderFactory.createRaisedBevelBorder());
JButton btnServices = new JButton("Add Service");
addServices.setBorder(BorderFactory.createRaisedBevelBorder());
removeServices.setBorder(BorderFactory.createRaisedBevelBorder());
hireButton.setBorder(BorderFactory.createRaisedBevelBorder());
//declare layouts
BorderLayout southBorder = new BorderLayout();
FlowLayout flo = new FlowLayout(FlowLayout.CENTER,30,30);
FlowLayout westFlo = new FlowLayout(FlowLayout.CENTER,10,10);
FlowLayout southFlo = new FlowLayout(FlowLayout.LEFT,10,10);
GridLayout northGrid = new GridLayout(0,4);
GridLayout southGrid = new GridLayout(1,1);
GridLayout westGrid = new GridLayout(1,2);
GridLayout southRow1 = new GridLayout(1,1,10,10);
GridLayout southRow2 = new GridLayout(2,0,10,10);
GridLayout eastGrid = new GridLayout(0,2,10,10);
//declare panels
servicePanel=new JPanel();
servicePanel.setLayout(new GridLayout(0,2));
//servicePanel.setLayout(new FlowLayout(FlowLayout.CENTER,5,5));
servicePanel.setPreferredSize(new Dimension(100,0));
westPanel = new JPanel();
westTop = new JPanel();
westCenter = new JPanel();
westBottomRight= new JPanel();
westCenterBottom = new JPanel();
westBottom = new JPanel();
westLeft = new JPanel();
westRightTop = new JPanel();
westRight = new JPanel();
northPanel = new JPanel();
centerPanel = new JPanel();
centerRight = new JPanel();
centerLeft = new JPanel();
eastPanel=new JPanel();
eastRight = new JPanel();
eastLeft = new JPanel();
eastBottom = new JPanel();
eastEastTop = new JPanel();
eastEastCenter = new JPanel();
southPanel = new JPanel();
southTop = new JPanel();
southLeft = new JPanel();
southCenter = new JPanel();
southBottom = new JPanel();
/////////////////set the panels/////////////////////
//NORTH
northPanel.setLayout(flo);
//northPanel.setBackground(Color.cyan);
//WEST
westPanel.setLayout(westGrid);
westPanel.setBorder(BorderFactory.createEtchedBorder());
westTop.setLayout(new GridLayout(2,1));
westTop.setBorder(BorderFactory.createEtchedBorder());
westCenter.setBorder(BorderFactory.createRaisedBevelBorder());
westCenter.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
westBottom.setLayout(new GridLayout(3,3,10,10));
westLeft.setLayout(new GridLayout(0,1));
//westRightTop.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
westRightTop.setLayout(new GridLayout(0,2));
westRight.setLayout(new GridLayout(1,1));
//westBottom.setLayout(new FlowLayout(FlowLayout.LEFT,5,5));
//westBottom.setLayout(new GridLayout(2,2,20,20));
//CENTER
centerPanel.setLayout(new FlowLayout(FlowLayout.LEFT,10,10));
centerRight.setLayout(gbl);
centerRight.setPreferredSize(new Dimension(500,200));
centerRight.setBorder(BorderFactory.createRaisedBevelBorder());
//EAST
eastPanel.setLayout(eastGrid);
eastRight.setLayout(new GridLayout(1,1));
eastEastTop.setLayout(new FlowLayout(FlowLayout.LEFT));
eastEastCenter.setLayout(new FlowLayout(FlowLayout.CENTER));
eastPanel.setBorder(BorderFactory.createEtchedBorder());
//SOUTH
southPanel.setBorder(BorderFactory.createRaisedBevelBorder());
southPanel.setLayout(southBorder);
southPanel.setPreferredSize(new Dimension(0,227));
southTop.setLayout(westGrid);
southLeft.setLayout(southGrid);
southLeft.setPreferredSize(new Dimension(70,0));
//southLeft.setBorder(BorderFactory.createRaisedBevelBorder());
//southRight.setLayout(westGrid);
southCenter.setLayout(southFlo);
southCenter.setPreferredSize(new Dimension(100,200));
southCenter.setBorder(BorderFactory.createRaisedBevelBorder());
//add to scrolling pane
scrollpane = new JScrollPane(employees);
scrollpane.getViewport().add(employees);
CREATING AN INSTANCE OF JTABLE
JTable table = new JTable(new MyTableModel());
table.setPreferredScrollableViewportSize(new Dimension(200,200));
ADDING THE TABLE TO THE SCROLLPANE2
scrollpane2 = new JScrollPane(table);
//scrollpane2.getViewport().add(servicePanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane3 = new JScrollPane(listEmpl);
scrollPane3.getViewport().add(listEmpl);
scrollPane4 = new JScrollPane(listSchedule);
scrollPane4.getViewport().add(listSchedule);
//get the content pane
Container pane = getContentPane();
JPanel calendars = new JPanel(new GridLayout(0,1));
JScrollPane jsp = new JScrollPane(calendars);
GregorianCalendar gc = new GregorianCalendar();
//gc.set(GregorianCalendar.DAY_OF_YEAR,1);
gc.set(GregorianCalendar.DAY_OF_MONTH,1);
for (int i=0; i<12; i++)
calendars.add(new CalendarPanel(gc,this));
gc.add(GregorianCalendar.MONTH, 1);
cmbServices.setEditable(true);
//add components to the panels
northPanel.add(lblsouthHeading);
westTop.add(lblEmployees);
westTop.add(scrollpane);
westCenter.add(hireButton);
westCenter.add(employeeName);
westCenter.add(fireButton);
westCenter.add(addServices);
westCenter.add(serviceName);
westCenter.add(removeServices);
westLeft.add(westTop);
westLeft.add(westCenter);
ADDING THE SCROLLPANE2 WHICH HOLDS
JTABLE TO THE WESTRIGHT PANEL
THEN FINALY TO THE WESTPANEL
westRight.add(scrollpane2);
westRight.add(new JLabel("TEST"));
westPanel.add(westLeft);
westPanel.add(westRight);
//westPanel.add(westCenter);
//westPanel.add(westBottom,BorderLayout.SOUTH);
westPanel.setBorder(BorderFactory.createRaisedBevelBorder());
eastLeft.add(lblSelect);
eastLeft.add(scrollPane3);
eastRight.add(eastLeft,BorderLayout.CENTER);
eastRight.add(jsp,BorderLayout.EAST);
//eastEastTop.add(lblEmployeeName);
//eastEastTop.setBackground(Color.black);
//eastEastTop.add(lblMonthStat);
eastEastTop.add(lblDay);
eastEastTop.add(lblYear);
eastPanel.add(eastRight,BorderLayout.CENTER);
eastPanel.add(eastEastTop);
//eastPanel.add(eastEastCenter);
//eastPanel.add(eastBottom,BorderLayout.SOUTH);
southTop.add(lblBizHours);
//southLeft.add(scrollpane);
southLeft.add(listDays);
southCenter.add(lblStartTime);
southCenter.add(txtOpenTime);
southCenter.add(startAmPm);
southCenter.add(lblEndTime);
southCenter.add(txtClosedTime);
southBottom.add(btnNextDay = new JButton("Next Day"));
southCenter.add(endAmPm);
southPanel.add(southTop,BorderLayout.NORTH);
southPanel.add(southLeft,BorderLayout.WEST);
southPanel.add(southCenter,BorderLayout.CENTER);
//southPanel.add(jsp,BorderLayout.EAST);
southPanel.add(southBottom,BorderLayout.SOUTH);
int row =1;
lblOpen = new JLabel("Start Time",lblOpen.RIGHT);
lblClosed = new JLabel("Quiting Time",lblClosed.RIGHT);
lblDayOff = new JLabel("Day Off");
space5 = new JLabel();
centerLeft.add(lblEmployeeName);
addComp(centerRight,lblDayOff,gbl,gbc,0,5,1,1,1,1);
for(int i=0;i<dow.length;i++){
weekDay[i]= new JLabel(""+dow[i],weekDay[i].LEFT);
colon = new JLabel(":",colon.CENTER);
colon2 = new JLabel(":",colon2.CENTER);
weekDay[i].setForeground(Color.red);
startHr[i] = new JTextField("",1);
keyListener kl=new keyListener();
startHr[i].addKeyListener(kl);
startMin[i] = new JTextField("",1);
startMin[i].addKeyListener(kl);
finishHr[i] = new JTextField("",1);
finishHr[i].addKeyListener(kl);
finishMin[i] = new JTextField("",1);
finishMin[i].addKeyListener(kl);
btnUpdate[i] = new JButton("Update");
dayOff[i] = new JCheckBox();
dayOff[i].addItemListener(this);
space = new JLabel();
space2 = new JLabel();
space3 = new JLabel();
space4 = new JLabel();
btnUpdate[i].setBorder(BorderFactory.createRaisedBevelBorder());
//lblOpen = new JLabel("Shift Start",lblOpen.RIGHT);
//lblClosed = new JLabel("Shift End",lblClosed.RIGHT);
openAmPm[i] = new JComboBox();
closedAmPm[i] = new JComboBox();
openAmPm[i].addItem("AM");
openAmPm[i].addItem("PM");
closedAmPm[i].addItem("AM");
closedAmPm[i].addItem("PM");
addComp(centerRight,space,gbl,gbc,row,2,1,1,1,1);
addComp(centerRight,weekDay[i],gbl,gbc,row,3,1,1,1,1);
addComp(centerRight,space3,gbl,gbc,row,4,1,1,1,1);
addComp(centerRight,dayOff[i],gbl,gbc,row,5,1,1,1,1);
//addComp(centerRight,lblOpen,gbl,gbc,row,6,1,1,1,1);
addComp(centerRight,startHr[i],gbl,gbc,row,7,1,1,1,1);
addComp(centerRight,colon,gbl,gbc,row,8,1,1,1,1);
addComp(centerRight,startMin[i],gbl,gbc,row,9,1,1,1,1);
addComp(centerRight,openAmPm[i],gbl,gbc,row,10,1,1,1,1);
//addComp(centerRight,lblClosed,gbl,gbc,row,11,1,1,1,1);
addComp(centerRight,finishHr[i],gbl,gbc,row,12,1,1,1,1);
addComp(centerRight,colon2,gbl,gbc,row,13,1,1,1,1);
addComp(centerRight,finishMin[i],gbl,gbc,row,14,1,1,1,1);
addComp(centerRight,closedAmPm[i],gbl,gbc,row,15,1,1,1,1);
addComp(centerRight,space4,gbl,gbc,row,16,1,1,1,1);
addComp(centerRight,btnUpdate[i],gbl,gbc,row,17,1,1,1,1);
addComp(centerRight,space2,gbl,gbc,row,18,1,1,1,1);
row++;
}//end for loop
//add the panels
//pane.add(northPanel,BorderLayout.NORTH);
//pane.add(centerRight,BorderLayout.CENTER);
//pane.add(westPanel,BorderLayout.WEST);
// pane.add(eastPanel,BorderLayout.EAST);
// pane.add(southPanel,BorderLayout.SOUTH);
centerPanel.add(centerLeft);
centerPanel.add(centerRight);
//set up tabbed pane
jtp = new JTabbedPane();
jtp.addTab("Schedule",centerPanel);
jtp.addTab("Employees",westPanel);
jtp.addTab("Holidays",eastPanel);
jtp.addTab("Business Hours",southPanel);
pane.add(jtp,BorderLayout.CENTER);
}//end init
private void addComp(JPanel panel,Component c,GridBagLayout gbl,
GridBagConstraints gbc, int row,
int column, int numRows, int numColumns,
int weightx, int weighty)
gbc.gridy = row;
gbc.gridx = column;
gbc.gridheight = numRows;
gbc.gridwidth = numColumns;
gbc.weightx = weightx;
gbc.weighty = weighty;
//set the constraints in the GridBagLayout
gbl.setConstraints(c,gbc);
panel.add(c);
}//end addcomp
public void actionPerformed(ActionEvent e)
//This method can be called only if
//there's a valid selection
int intLength;
String command=e.getActionCommand();
int listIndex1 = listEmpl.getSelectedIndex();
int listIndex2 = listServices.getSelectedIndex();
String firstName=null;
//String service=null;
if(command.equals("Add Employee"))
firstName = employeeName.getText();
//employeeName.setText(""+index);
//User didn't type in a unique name...
if (firstName.equals("") || alreadyInList(nameData,firstName))
Toolkit.getDefaultToolkit().beep();
employeeName.requestFocusInWindow();
employeeName.selectAll();
return;
}//end if
//int index = listEmpl.getSelectedIndex();
//get selected index
//if (listIndex1 == -1)
//no selection, so insert at beginning
//listIndex1 = 0;
//employeeName.setText("listIndex=-1");
//}//end if
else
//add after the selected item
//promptServices();
nameData.addElement(firstName);
size=nameData.getSize();
//fill the employee combobox
//employees.addItem(firstName);
holidayData.addElement(firstName);
listIndex1++;
employeeName.setText("size is "+size);
//Reset the text field.
employeeName.requestFocusInWindow();
employeeName.setText("");
scrollpane.revalidate();
scrollpane.repaint();
}//end if
if(command.equals("Remove Employee"))
nameData.remove(listIndex1);
holidayData.remove(listIndex1);
//removed item in last position
listIndex1--;
size = nameData.getSize();
employeeName.setText("size is "+size);
if (size==0)
//Nobody's left, disable firing.
fireButton.setEnabled(false);
}//end if
else
//Select an index.
if (listIndex1 == nameData.getSize())
listEmpl.setSelectedIndex(listIndex1);
listEmpl.ensureIndexIsVisible(listIndex1);
}//end if
}//end if
HERE IS WHERE A NEW ROW WITH A SERVICE AND DURRATION SHOULD BE ADDED TO THE JTABLE
EACH TIME THE BUTTON IS CLICKED
if(command.equals("Add Service"))
service=serviceName.getText();
if (service.equals("") || alreadyInList(serviceData,service))
Toolkit.getDefaultToolkit().beep();
serviceName.requestFocusInWindow();
serviceName.selectAll();
return;
}//end if
else
do{
timeText = JOptionPane.showInputDialog(listServices, "Enter the time allowed in minutes for \n a "+service+ " appointment");
totalResult=validateInputBox(timeText);
}while(!totalResult);
repaint();
//add after the selected item
//serviceData.addElement(service+" "+ timeText+ minutes);
//cmbServices.addItem(service);
serviceName.requestFocusInWindow();
serviceName.setText("");
listIndex2++;
//scrollpane.revalidate();
//scrollpane.repaint();
scrollpane2.revalidate();
scrollpane2.repaint();
//int time = Integer.parseInt(timeText);
}//end else
}//end if
/* else if(command.equals("Remove Service"))
System.out.println("Selected:"+CheckServices.selected);
if(CheckServices.selected){
//for(int i=0;i<
servicePanel.remove(CheckServices.newChk);
servicePanel.remove(CheckServices.lengthLbl);
repaint();
int index = listEmpl.getSelectedIndex();
serviceData.remove(listIndex2);
//removed item in last position
listIndex2--;
size = serviceData.getSize();
//employeeName.setText("size is "+size);
if (size == 0)
//Nobody's left, disable firing.
removeServices.setEnabled(false);
}//end if
else
//Select an index.
if (listIndex2 == serviceData.getSize())
listServices.setSelectedIndex(listIndex2);
listServices.ensureIndexIsVisible(listIndex2);
}//end if
}//end if
//Select the new item and make it visible.
//listEmpl.setSelectedIndex(listIndex1);
//listEmpl.ensureIndexIsVisible(listIndex1);
//listServices.ensureIndexIsVisible(listIndex2);
//listServices.setSelectedIndex(listIndex2);
}//end actionperformed
public void itemStateChanged(ItemEvent e)
boolean selected=false;
int status = e.getStateChange();
if(status==ItemEvent.SELECTED)
for(int i=0;i<dayOff.length;i++)
if(dayOff[i].isSelected())
int index = i;
startHr[i].setEditable(false);
startHr[i].setText("DAY OFF");
startMin[i].setEditable(false);
finishHr[i].setEditable(false);
finishMin[i].setEditable(false);
}//end if
}//end for
}//end if
if(status==ItemEvent.DESELECTED)
for(int i = 0;i<dayOff.length;i++)
if(!dayOff[i].isSelected())
startHr[i].setEditable(true);
startMin[i].setEditable(true);
finishHr[i].setEditable(true);
finishMin[i].setEditable(true);
}//end if
}//end for
}//end if
public boolean validateInputBox(String t)
result=false;
int intLength= t.length();
if(intLength <=3)
for(int i = 0;i<intLength;i++)
if(!Character.isDigit(timeText.charAt(i)))
JOptionPane.showMessageDialog(listServices,message2 );
return result;
//break;
result=true;
return result;
}//end if
else{
JOptionPane.showMessageDialog(listServices,message1 );
return result;
}//end validate method
//This method tests for string equality. You could certainly
//get more sophisticated about the algorithm. For example,
//you might want to ignore white space and capitalization.
protected boolean alreadyInList(DefaultListModel myList,String name)
return myList.contains(name);
//handler for list selection changes
public void valueChanged(ListSelectionEvent event)
if(event.getSource()==listEmpl && !event.getValueIsAdjusting())
/**Load up any relating service information from the database
for the selected employee. If there is no record then reset the
serviceData list to empty so new services can be added
if(dbRecord){
serviceData.addElement("Record added");
dbRecord=false;
else
serviceData.clear();
}//end if
if(event.getSource()==employees ||event.getSource()==listEmpl && !event.getValueIsAdjusting()){
System.out.println("value changed");
int index = employees.getSelectedIndex();
Object item =employees.getModel().getElementAt(index);
lblEmployeeName.setText((String)item);
//lblEmployeeName.setText("Changed");
//centerLeft.add(lblEmployeeName);
}//end valueChanged
public void promptServices()
JOptionPane.showMessageDialog(employees,"Enter a service");
HERE IS THE MYTABLEMODEL CLASS. NOTE:ELEMENT INTEGER(5) WILL BE REPLACED
WITH THE VARIABLE TIMETEXT BECAUSE THIS ELEMENT IS USER DEFINED BUT
DOING SO RIGHT NOW THROWS AN ERROR
class MyTableModel extends AbstractTableModel{
String columnNames[] = {"Service", "Minutes", "Select"};
Object data[][] = { {service, new Integer(5), new Boolean(false)} };
public int getColumnCount()
return columnNames.length;
public int getRowCount()
return data.length;
public String getColumnName(int col)
return columnNames[col];
public Object getValueAt(int row, int col)
return data[row][col];
/* * JTable uses this method to determine the default renderer
/ * editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box. */
public Class getColumnClass(int c)
THIS LINE IS THROWING A NULLPOINTEREXCEPTION ERROR
return getValueAt(0, c).getClass();
* Don't need to implement this method unless your table's
* editable.
public boolean isCellEditable(int row, int col) {
System.out.println("hey hey hey");
//Note that the data/cell address is constant
//no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
* Don't need to implement this method unless your table's
* data can change.
//public void setValueAt(Object value, int row, int col) {
// data[row][col] = value;
// fireTableCellUpdated(row, col);
class keyListener extends java.awt.event.KeyAdapter
//key listener class watches character count
public void keyTyped(java.awt.event.KeyEvent event){
Object object = event.getSource();
for(int i =0; i<7;i++)
if (object == startHr[i])
if ( startHr[i].getText().length()>MAX_CHARS && event.getKeyChar()!='\b')
event.consume(); //if over limit, pretend nothing happened..
if(object ==startMin[i])
if ( startMin[i].getText().length()>MAX_CHARS && event.getKeyChar()!='\b')
event.consume();
if(object==finishHr[i])
if ( finishHr[i].getText().length()>MAX_CHARS && event.getKeyChar()!='\b')
event.consume();
if(object==finishMin[i])
if ( finishMin[i].getText().length()>MAX_CHARS && event.getKeyChar(Any help would be greatly appreciated seeing that I know squat about JTables and the JTableModel.So why do you start by writing a 1000 line program. Start with something small. Understand how they work and then incorporate it into your program.
First. Use the DefaultTableModel. It will do everything you need. Why reinvent the wheel by extending AbstractTableModel. This [url http://forum.java.sun.com/thread.jsp?forum=57&thread=418866]posting shows how to create a table and populate it with some data in 5 lines of code or less. It also gives examples of adding new rows of data to the DataModel (something your TableModel can't do) in a couple of lines of code.
Next, we have Basic Debugging 101. If you have a NullPointerException, then you need to determine which variable is null. I simply added the following code before the line that was causing the problem:
System.out.println(getValueAt(0, c) + " : " + c);
return getValueAt(0, c).getClass();
The value in column 0 was null. So where does the value from the first column come from. Well in your TableModel you tried to create it with one default row of data:
Object data[][] = { {service, new Integer(5), new Boolean(false)} };
So it would appear the "service" variable is null.
Don't post 1000 lines programs again. Create simple code that demonstrates the problem. Chances are while your creating this demo program you will resolve your problem. -
Develop a J2dDataVectorOperator
If we have a 1d data array/list, we can use JDK provided tools Arrays and Collections to sort the array/list, and do binary-search on it.
But if we have 2d data vector, which likes:
Vector data2d;
data2d.add(new Vector());
data2d.add(new Vector());
then,
- JTable can take it as input dataset;
- JDK131 samples also provide a 'TableSorter' to sort this data2d;
- this is the most popular way to hold data from a relational database table (comments?)
But what about binary-search, unique, ... and other possible operations?
I dont find any free avalaible Java class/method to do those.
I'd like to develop a Java class 'J2dDataVectorOperator', which
- has methods of sort, binary-search, unque, ...
- only take data2d as the input data, without reference to JTableModel, JTable
And I'd like to put it as a open-source' to others.
I post this question just to double check I m not re-inventing wheel.
THANK YOU in advance for your consideration and comments.Hi, cBoeing and SpinozaQ:
Thank you very much for your replies !!!
In terms of 'Total order', i think it's quite theoretical.
Practically, for a 2d data vector, it has 2 possibilities:
sort by row.
sort by column.
The JDK131 Sample TableSorter implements sort rows by columns. It's easy to copy it and modify it to do sort columns by rows. Practically, it's more common usage to sort rows by columns.
In practice, i load a data table from a relational database engine/driver. The data is 2d. So i put it in a 2d-vector and feed the data-vector to JTable(which is not dataset but a user interface sometimes called 'GRID'). Then i can use TableSorter to sort it.
Factually, i already implemented a binary-search on this 2d-data-vector, after call sort.
Another thing i like to mension is that i went to 'Source-forge' and found a few open-source database engines which implemnts sort/binary-search/... on 2d relational tables. Even though the forms of data-set they work on are little different each other, bu the basic idea is the same.
Thanks again. -
Requerying MS Access table?
Hi,
Ok, I got my insert statement to work now using a preparedstatement. I noticed now that my JTable doesn't reflect the new record unless I stop and restart my application.
I'm using a JTabbedPane and adding a class that extends AbstractTableModel on one tab. On another tab I have a JPanel with my controls for inserting a record.
I setup a ChangeHandler and add it to the listener of the JTabbedPane, this detects when I switch tabs. If the current tab is my table tab I set the tableModel = null and rebuild it. This seemed the best approach. When I do this I get an SQLException from the tableModel.getValueAt() method saying the result set is closed.
Here's what I think is the pertenant code (let me know if you want to see something else):
private class ChangeHandler implements ChangeListener
public void stateChanged( ChangeEvent e )
if ( tabbedPane.getSelectedIndex() == 0 )
tableModel = null;
buildResultTable();
} // end if
} // end method stateChanged
} // end private inner class ChangeHandler
public void buildResultTable()
// create TableModel
tableModel = new MyTableModel( dbConnection );
try
tableModel.setQuery(
"SELECT date, odometer, trip_meter, no_gallons FROM records ORDER BY date desc" );
} // end try
catch ( SQLException sqlException )
JOptionPane.showMessageDialog( null, sqlException.getMessage(),
"Database Error - buildResultTable", JOptionPane.ERROR_MESSAGE );
} // end catch
// create JTable delegate for tableModel
resultTable = new JTable( tableModel );
resultTablePane = new JScrollPane( resultTable );
} // end method buildResultTable
public void setQuery( String query ) throws SQLException, IllegalStateException
// ensure database connection is available
if ( !connectedToDatabase )
throw new IllegalStateException( "Not Connected to Database" );
// specify query and execute it
resultSet = statement.executeQuery( query );
if ( resultSet == null )
System.out.println( "Query didn't work!" );
// obtain meta data for ResultSet
metaData = resultSet.getMetaData();
// determine number of rows in ResultSet
resultSet.last(); // move to last row
numberOfRows = resultSet.getRow(); // get row number
// notify JTable that model has changed
fireTableStructureChanged();
} // end method setQuery
public Object getValueAt( int row, int column ) throws IllegalStateException
if ( !connectedToDatabase )
throw new IllegalStateException( "Not Connected to Database" );
// obtain value at specified REsultSet row and column
try
resultSet.absolute( row + 1 );
return resultSet.getObject( column + 1 );
} // end try
catch ( SQLException sqlException )
JOptionPane.showMessageDialog( null, sqlException.getMessage(),
"Database Error - getValueAt", JOptionPane.ERROR_MESSAGE );
} // end catch
return ""; // if problems, return empty string object
} // end method getValueAt
I'm new to Java so I'm sure there's a better way to do what I'm trying to do. Any ideas where I went wrong or a better way to do it? Any help is greatly appreciated.
Thanks in advance,
LinnOk, I got my insert statement to work now using a
preparedstatement. I noticed now that my JTable
doesn't reflect the new record unless I stop and
restart my application.MS Access? That question is asked every week here.
Here's an instance I picked at random from a forum
search for "access insert":
http://forum.java.sun.com/thread.jspa?forumID=48&threa
dID=348300Yeah, I thought it would be a common issue but I've spent the better part of three days going over google searches for this answer but no luck yet. Probably just haven't found the right combination of search terms yet.
I checked that forum thread you suggest and it, like all the others I've found, don't actually answer the question. They all seem to end with someone asking the original poster for more information and that's the end of the discussion thread.
Maybe if I rephrase the question, here's what I'm doing...
I query Access and build a JTableModel from a resultset.
I insert a new record into Access.
I switch over to Access and see that the record is inserted, Access shows that the insertion worked. (I switch tasks in Windows without quiting out of my Java app.)
I switch back to my Java app. and look at the table and the inserted record is not there yet.
So, what I'm thinking is that I need to "requery" the Access database and the new record should be included. My question is, how do I do that? How do I requery or refresh my resultset?
Oh, let me mention that I open the database connection and setup statement and resultset objects when I launch my app. and close them when I exit the app.
If I simply try to requery the database it throws an sqlException in the getValueAt() method of my TableModel extension class.
sqlException: Result set is closed is the message and is thrown by the line resultSet.absolute( row + 1 ); Here is the getValueAt() method code:
public Object getValueAt( int row, int column ) {
// obtain value at specified ResultSet row and column
try {
resultSet.absolute( row + 1 );
return resultSet.getObject( column + 1 );
catch ( SQLException sqlException ) {
sqlException.printStackTrace();
return ""; // if problems, return empty string object
} // end method getValueAt
Any help is greatly appreciated.
Thanks,
Linn -
Unknown Object in the eyes of the JTable
Hey! :)
Alright, here's my question/situation. I have an object that I made which consists of student data (student number, name, country, etc...) and I want to insert this data into a JTable. The thing is that because it's my own object, the JTable doesn't recognize this data. I was thinking to convert the data to Object datatype, but when I tried doing that, it didn't work. I tried typecasting and that didn't work either. What should I do?JTable will call toString() on any object that you put into it, which probably isn't what you want.
What you need is your own JTableModel class. It's pretty easy to do. Try googling for that. -
Refreshing JTable from JTree?
Hello everyone,
I've created a JTable using my own table model extending AbstractTableModel...
I'm sending data to JTable as Vector through it's constructor...
I have also created a JTree in another class... What i intend to achieve is this:
Whenever i click on a node of the JTree, all the childs
of that node should be displayed in the jtable...
I have solved part of the problem by creating a new instance of JTable whenever the tree node is clicked... obtaining the names of all the childs in a Vector and sending it to the JTable...
The problem with this approach is that a table row is only refreshed when it's clicked upon... or if i minimize and then maximize the app...
Please tell me how to solve this problem... if you have any other comments on the approach i've used, please share it with me...
ThanksHope the folling code snippet will help.
jTableModel.setDataVector(rowVector,tableColumnVector);
//get the table model and pass it in setModel() method or use the global Modal object.
jTable.setModel(jctableModel);
tableModelEvent=new TableModelEvent(jctableModel);
Thanks,
Vikas Karwal
[email protected] -
JTable question regarding Index/ID's from a VB guy
Greets!
So i am coming from VB6 where i use an ActiveX object table to display data from a SQL database table. When populating the table i include the 'ID' field from the database table as a hidden column. So when a user selects a row, i pull the hidden column's ID# and use that to do whatever (bring up another edit form, etc)
So here i am in Java now, i've been playing with jTable for a while now and seem to be getting the hang of the basics, but when i replicated the above scenario, hiding the ID column had weird results (cursor would dissappear when i scroll over with the arrow keys). I also saw another post where another person said that along with populating the jTable i should also have an array that stores the ID that matches the RowIndex from the jTable itself.
This is the table model that i am using:
public class jTableModel extends AbstractTableModel {
private double xTotal;
private int colnum;
private int rownum;
private String[] colNames;
private ArrayList<Object[]> ResultSets;
private Icon zIcon;
/** Creates a new instance of FoodTableModel */
public jTableModel(ResultSet rs,frmMain frm) {
ResultSets=new ArrayList<Object[]>();
Icon icon1 = new ImageIcon(getClass().getResource("/main/images/bullet_ball_glass_blue.png"));
Icon icon2 = new ImageIcon(getClass().getResource("/main/images/bullet_ball_glass_red.png"));
Icon icon3 = new ImageIcon(getClass().getResource("/main/images/bullet_ball_glass_green.png"));
try{
while(rs.next()){
switch (rs.getInt("Type")) {
case 1: zIcon = icon1; break;
case 2: zIcon = icon2; break;
case 3: zIcon = icon3; break;
Object[] row={zIcon,rs.getString("Name"),rs.getString("Description"),rs.getString("ID")};
ResultSets.add(row);
String[] zNames={
"","Name","Description","ID"
colNames = zNames;
colnum=4;
catch(Exception e){
System.out.println("(jTableModel: There was an error: " + e);
public Object getValueAt(int rowindex, int columnindex) {
Object[] row=ResultSets.get(rowindex);
return row[columnindex];
public int getRowCount() {
return ResultSets.size();
public int getColumnCount() {
return colnum;
@Override
public String getColumnName(int param) {
return colNames[param];
public double getTotal() {
return xTotal;
@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}Can anyone give me any tips in this area or point me in the right direction?
Any help would be appreciated.Dear Poster,
As no response has been provided to the thread in some time I must assume the issue is resolved, if the question is still valid please create a new thread rephrasing the query and providing as much data as possible to promote response from the community.
Best Regards,
SDN SRM Moderation Team -
Hi all,
I have a program that fills string values into a JTableModel. I added a TableListener to my table and the appropriate code to handle the adding row event. To do this I invoked the method fireTableRowsInserted(lastrow, firstrow).
The problem is that only one row is displayed. But when I click on a table row then all the recently added rows appear !
Any idea ?Shouldn't it be (swap your arguments):
fireTableRowsInserted(firstrow, lastrow); -
RemoveColumn from TableModel not just JTable
I do something like this to remove a column from my JTable:
JTable.removeColumn(getColumn(columnName));This works great for removing the column from the table...but it doesn't remove the column from the TableModel so if you do a repaint the column come back. There is no
JTableModel.removeColumn()How can I remove my column from the model?
PS...How dumb...why would you still want the column in the TableModel after you remove it!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!I would guess 90% of time people what to removeColumn from both Table and Model so why not accommodate the 90% AND 10%. NOT just the 10%.Then why build the TableModel with the data to begin with? Its much faster to simply remove a column from display on the table then it is to recreate the entire TableModel, especially if you need to do a remote database query. So build the TableModel with all the information and let the users customize the view themselves.
I think you've got your percentages reversed.
Maybe you are looking for
-
Cant get Apple TV to work properly with older flat panel TV.
I have an older flat panel, a 42" philips 42pf9630a. This one: http://www.retrevo.com/support/Phili.../278bh337/t/2/ I plugged my brand new Apple TV into the HDMI and switched input on the TV. I can see the Apple TV main menu but it blips in and out,
-
How do i get my ipod to stop repeating a song
I accidently pressed something while walking and now my ipod nano is repeating the same song over and over. I tried shutting the thing off, but it continues to repeat. How do I get it to play all the songs in the album? Thanks
-
I know lot's of people have asked about this, but they've all had different resolutions. I have tried doing the things they did to no avail. If I try to access google or any of google's pages it eventually times out. If I visit a website that has goo
-
"Open with" finder menu -- how to customize
When I choose "Open with" from the Finder's "File" menu (or from the contextual menu). I get the spinning beachball for 10-20 seconds while the finder searches EVERY hard disk for every possible program a file can be opened with. Isn't there some way
-
ITunes 10.4 crash during sync and update.
A few days ago or so i tried syncing some new songs from iTunes (on my hp laptop with windows 7 64) into my 64gb ipod touch 4g. However, about halfway through the sync itunes displays that it has stopped working and closes soon afterwards. I first