TabelModel

Joined
Jun 13, 2010
Messages
2
Reaction score
0
Hello,

I'm trying to create a Jtabel that will allow the user to alter the cells during runtime in order to edit fields of objects in a database. Unfortunately, I'm unable to get a tabelModel event to fire whenever the tabel is changed by the user during runtime. And, whenever the user edits a cell during runtime, as soon as he/she clicks outside of the cell, it returns to its previous value. So in other words, I need to somehow get the tabelChanged method to be called whenever the user edits or even double clicks on a cell during runtime. Here is the code for the GUI screen:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.TableModel;
import javax.swing.table.TableColumn;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
import javax.swing.table.*;

public class RecordGUI extends JFrame implements ActionListener, TableModelListener
{
//Create GUI objects which will be used by the methods of the class
JTable table;
JonsTableModel model;
JScrollPane scrollPane;
String data [][];
JButton cmdSearch = new JButton("Search");
JRadioButton optPrice = new JRadioButton("Price");
JRadioButton optSalePrice = new JRadioButton("Sale price");
JRadioButton optPurchased = new JRadioButton("Number purchased");
JRadioButton optSold = new JRadioButton("Number sold");
JRadioButton optDate = new JRadioButton("Date");
JTextField txtStart = new JTextField(8);
JTextField txtEnd = new JTextField(8);

//Create an instance of the layout manager
SpringLayout layout = new SpringLayout();

//Constructs an object of the class, takes no parameters
public RecordGUI(String record) throws IOException
{
//Create the table
model = new JonsTableModel(record);
model.addTableModelListener(this);
table = new JTable(model);
table.setSurrendersFocusOnKeystroke(true);
table.setPreferredScrollableViewportSize(new Dimension (753,400));
table.setSelectionMode(1);

//Alter the sizes of the tableColumns
TableColumn column = null;
for (int i = 0; i < 5; i++)
{
column = table.getColumnModel().getColumn(i);
if (i == 3 || i == 4 || i == 5)
{
column.setPreferredWidth(200); //third column is bigger
}
else
{
column.setPreferredWidth(50);
}//End of if
}//End of for

//Add the table to the scrollpane
scrollPane = new JScrollPane(table);
//Cannot be used in JDK5
//table.setFillsViewportHeight(true);

//Create the button group
ButtonGroup group = new ButtonGroup();
group.add(optPrice);
group.add(optSalePrice);
group.add(optPurchased);
group.add(optSold);
group.add(optDate);

//Set the action listeners
cmdSearch.setActionCommand("search");

//Add the actionlisteners
cmdSearch.addActionListener(this);

//Add the components to the frame
getContentPane().add(scrollPane);
getContentPane().add(cmdSearch);
getContentPane().add(optPrice);
getContentPane().add(optSalePrice);
getContentPane().add(optPurchased);
getContentPane().add(optSold);
getContentPane().add(optDate);
getContentPane().add(txtStart);
getContentPane().add(txtEnd);

//Set the layout for the frame
this.getContentPane().setLayout(layout);

//Set the west and north positions of the components on the frame
layout.putConstraint(SpringLayout.WEST, scrollPane, 15, SpringLayout.WEST, getContentPane());
layout.putConstraint(SpringLayout.NORTH, scrollPane, 130, SpringLayout.NORTH, getContentPane());

layout.putConstraint(SpringLayout.WEST, cmdSearch, 15, SpringLayout.WEST, getContentPane());
layout.putConstraint(SpringLayout.NORTH, cmdSearch, 50, SpringLayout.NORTH, getContentPane());

layout.putConstraint(SpringLayout.WEST, optPrice, 95, SpringLayout.WEST, getContentPane());
layout.putConstraint(SpringLayout.NORTH, optPrice, 90, SpringLayout.NORTH, getContentPane());

layout.putConstraint(SpringLayout.WEST, optSold, 95, SpringLayout.WEST, getContentPane());
layout.putConstraint(SpringLayout.NORTH, optSold, 70, SpringLayout.NORTH, getContentPane());

layout.putConstraint(SpringLayout.WEST, optSalePrice, 95, SpringLayout.WEST, getContentPane());
layout.putConstraint(SpringLayout.NORTH, optSalePrice, 50, SpringLayout.NORTH, getContentPane());

layout.putConstraint(SpringLayout.WEST, optPurchased, 95, SpringLayout.WEST, getContentPane());
layout.putConstraint(SpringLayout.NORTH, optPurchased, 30, SpringLayout.NORTH, getContentPane());

layout.putConstraint(SpringLayout.WEST, optDate, 95, SpringLayout.WEST, getContentPane());
layout.putConstraint(SpringLayout.NORTH, optDate, 10, SpringLayout.NORTH, getContentPane());

layout.putConstraint(SpringLayout.WEST, txtStart, 255, SpringLayout.WEST, getContentPane());
layout.putConstraint(SpringLayout.NORTH, txtStart, 80, SpringLayout.NORTH, getContentPane());

layout.putConstraint(SpringLayout.WEST, txtEnd, 355, SpringLayout.WEST, getContentPane());
layout.putConstraint(SpringLayout.NORTH, txtEnd, 80, SpringLayout.NORTH, getContentPane());

//Set the price button as the default selected button
optDate.setSelected(true);

//Set up methods for the frame
this.setSize(800,600);
this.setLocationRelativeTo(null);
this.setTitle("Add, Delete or Modify Produce");
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}//End of constructor

//Check for a button event
public void actionPerformed(ActionEvent evt)
{
//Check which button was clicked
if (evt.getActionCommand().equals("search"))
{
if(optPrice.isSelected() && safeSearch() == true)
model.search("price",txtStart.getText(),txtEnd.getText());
else if(optSalePrice.isSelected() && safeSearch() == true)
model.search("salePrice",txtStart.getText(),txtEnd.getText());
else if(optPurchased.isSelected() && safeSearch() == true)
model.search("purchased",txtStart.getText(),txtEnd.getText());
else if(optSold.isSelected() && safeSearch() == true)
model.search("sold",txtStart.getText(),txtEnd.getText());
else if(optDate.isSelected() && safeSearch() == true)
{
model.search("date",txtStart.getText(),txtEnd.getText());
}
else
JOptionPane.showMessageDialog(this,"No search type selected.","Error",JOptionPane.ERROR_MESSAGE);
}
else if(evt.getActionCommand().equals("delete"))
{
try
{
model.deleteCell(table.getSelectionModel().getLeadSelectionIndex());
}
catch(IOException e){System.out.println("Unable to delete/nError:/t" + e.getMessage());}
}

repaint();
validate();
}//End of actionPerformed method

Method is not called when the user edits the table during runtime. How do I get this method to be called?
public void tableChanged(TableModelEvent evt)
{
System.out.println("TABLE CHANGED");
}

//Make sure the search is safe
private boolean safeSearch()
{
return true;
}//End of boolean
}//End of class



Its for a school project. Any help would be greatly appreciated.
 
Last edited:
Joined
Jun 13, 2010
Messages
2
Reaction score
0
Here is the table model used:



/**

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.TableModel;
import javax.swing.table.TableColumn;
import java.io.*;
import java.util.*;
import javax.swing.table.*;

public class JonsTableModel extends AbstractTableModel
{
private String[] columnNames = {"Purchase price", "Sale price", "Number sold", "Amount purchased from supplier", "Date of record entry"};
private String[][] data;
private String[][] backUpData;
private Record records;

//Only constructor
public JonsTableModel (String records) throws IOException
{
initializeData(records);
backUpData = data;
}//End of constructor

//Intialize the data
private void initializeData(String record) throws IOException
{
records = new Record(record);
data = new String [records.getLength()][];

//Fill the two dimensional arrays with the fields of the things in the records field
for(int x = 0; x < data.length; x++)
{
data [x] = records.getStringArray(x);
}//End of for
}//End of intializeData method

//Restore the table, prior to searching.
public void undoSearch()
{
data = backUpData;
}//End of undoSearch method

//Delete a record from the table
public void deleteCell(int index) throws IOException
{
String [][] tempArray = new String[data.length-1][];

//Copy the array until the specified index
for(int x = 0; x < tempArray.length; x++)
{
if (x == index)
break;
tempArray[x] = data[x];
}//End of for

//Copy the rest of the array, skipping the specified index
for(int x = index; x < tempArray.length; x++ )
tempArray[x] = data[x + 1];

//Load the array back into data
data = tempArray;
backUpData = data;

//Delete the record
records.deleteRecord(index);

tempArray = null;
}//End of deleteRecord method

//Gets the number of columns in a table
public int getColumnCount()
{
return columnNames.length;
}//End of getColumnCount method

//Gets the number of rows in a table
public int getRowCount()
{
return data.length;
}//End of getRowCount method

//Gets the name of the column
public String getColumnName(int col)
{
return columnNames[col];
}//End of getColumnName method

//Gets the value at a specific row/column
public String getValueAt(int row, int col)
{
return data[row][col];
}//End of getValueAt method

//For the table constructor, must be included
public Class getColumnClass(int c)
{
return getValueAt(0, c).getClass();
}//End of getColumnClass method

//Makes the table editable
public boolean isCellEditable(int row, int col)
{
return true;
}//End of isCellEditable method

//Change the cell
private void setValueAt(String value, int row, int col)
{
data[row][col] = value;
}//End of setValueAt method

//Clear the table
public void clearTable()
{
String temp [][] = new String [0][columnNames.length];

data = temp;

temp = null;
}//End of clearTable method

//Invoke the search method within the records class and update the data with the new search information
public void search(String searchType, String start, String end)
{
ArrayList<Record> temp = new ArrayList<Record>();
String [] tempStringArray;
String tempString;
ArrayList <String> tempData = new ArrayList <String>();
String data2 [][];

clearTable();

temp = records.search(searchType, start, end);

//Fill the two dimensional arrays with the fields of the things in the records field
for(int x = 0; x < temp.size(); x++)
{
tempData.add(String.valueOf(temp.get(x)));
}//End of for

data2 = new String [tempData.size()][];

for(int x = 0; x < tempData.size(); x++)
data2[x] = tempData.get(x).split(",");

data = data2;

temp = null;
}//End of search method

//Add to the data
public void addRow(String [] aStringArray)
{
String [][] temp = new String [data.length+1][];

temp[data.length] = aStringArray;

data = temp;

temp = null;
}//End of addRow method
}//End of JonsTableModel class
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top