Java Swing | extend AbstractTableModel and use it with JTable | several questions - java

I followed Oracle's model for implementing an AbstractTableModel
http://download.oracle.com/javase/tutorial/uiswing/examples/components/TableDemoProject/src/components/TableDemo.java
I did this because my table has to contain 3 columns, and the first has to be a JCheckBox.
Here's my code:
public class FestplattenreinigerGraphicalUserInterfaceHomePagePanelTableModel extends AbstractTableModel {
private String[] columnNames = {"Auswahl",
"Dateiname",
"Pfad"};
private Object[][] data = {
{new Boolean(true), "datei.tmp",
"/home/user/tmp"}
};
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];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public boolean isCellEditable(int row, int col) {
if (col == 0) {
return true;
} else {
return false;
}
}
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
}
}
Here are my questions:
How does JTable (new JTable(FestplattenreinigerGraphicalUserInterfaceHomePagePanelTableModel)) know what the column names are and their values are? Since there's no contructor in my AbstractTableModel?! Is it becaue columnNames and data must be named like they are and JTable accesses them?
How can i put new Values in my JTable? Since columnNames and data are arrays. Can i replace them with vectors? If so, how do I init these vectors? In a constructor in myAbsTableModel?
I think it's very easy to get a solution but this Table handling isn't trivial to me, so thank u very much!

All Swing components come with default model implementations. I suggest you understand how to use them first before trying to create your own. For a JTable its called the DefaultTableModel. Read the API for methods to dynamically add/remove rows of data from the model. Here is a simple example to get you started:
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableBasic extends JPanel
{
public TableBasic()
{
String[] columnNames = {"Date", "String", "Integer", "Boolean"};
Object[][] data =
{
{new Date(), "A", new Double(1), Boolean.TRUE },
{new Date(), "B", new Double(2), Boolean.FALSE},
{new Date(), "C", new Double(9), Boolean.TRUE },
{new Date(), "D", new Double(4), Boolean.FALSE}
};
JTable table = new JTable(data, columnNames)
{
// Returning the Class of each column will allow different
// renderers and editors to be used based on Class
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
return o.getClass();
}
return Object.class;
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
add( scrollPane );
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("TableBasic");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new TableBasic() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

First, I think you need to learn a bit more about Java, especially inheritance (I'm referencing your constructor problem.
Answers to your questions :
define your column names via a private final static attribute, assuming your column names don't change.
since your class extends AbstractTableModel, you can define a constructor for it, where you'll pass the data. Redefine the getValueAt method to allow the model to use the data you're passing.
Some more advice :
don't do what you're doing in getColumnClass. Normally, all elements in a column will have the same class, so do a switch on the column index to get the classes.
to add a JCheckBox in one of your columns, you'll have to use a custom TableCellRenderer

The JTable determines how many columns by calling getColumnCount() on your column model. It then iterates and calls getColumnName(idx) for each column. Your class tells it the column name -- look at your implementation of those methods.
You can store your data in whatever format you want. The JTable calls methods on your table model to retrieve that data. If you want to add new items to your model, you can implement an addItem(Object o) method to your model; just be sure to call fireTableRowsInserted() for each new item.

Related

Why I can't set up JTable with Table columns

I use my JTable, my JTableModel for my project. I can not start the table with my column headers and empty data. May you help me? Thank you.
Here is my code
MainCode class
public class MainCode extends JFrame{
public MainCode(){
...........other codes here........
MyTableModel tm= new MyTableModel();
MyTable table=new MyTable(tm);
//JTable table=new JTable(tm); if I write this line,I see column names.
table.setPreferredScrollableViewportSize(new Dimension(480,80));
table.setFillsViewportHeight(true);
JScrollPane scrollPanetable=new JScrollPane(table);
frame.getContentPane().add(scrollPanetable)
........another codes...........
}
}
MyTable class
public class MyTable extends JTable{
public MyTable(){
}
public MyTable(int row,int col){
super(row,col);
}
#Override
public void tableChanged(TableModelEvent e){
super.tableChanged(e);
repaint();
System.out.println("public void tableChanged(TableModelEvent e)");
}
}
MyTableModel class
public class MyTableModel extends AbstractTableModel{
private String[] columnNames;
private Object[][] data;
public MyTableModel(){
super();
columnNames=new String[]{"A","B","C"};
data=new Object[][]{ {null,null,null}};
}
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];
}
}
it is not started with column names. What is wrong with this code.I see below image.
Because you do not have constructor in MyTable which takes parameter MyTableModel.
You are creating table like this:
MyTable table=new MyTable(tm);
So you must have constructor in MyTable like this:
class MyTable extends JTable {
public MyTable(MyTableModel tm){
super(tm);
}
}
If you have MyTable code that you posted here, your code will not compile!
Why are you overriding JTable?
Your own comment, if I write this line,I see column names suggests that your overriding of JTable is the problem. You have an overridden implementation of tableChanged(...), which the docs say Application code will not use these explicitly, they are used internally by JTable. Otherwise, your subclassed JTable isn't doing anything special to warrant subclassing.
If you must subclass, you have to tell the subclass how to use your model, which you haven't done (either via a constructor or setModel(...)).
More than likely you have not added the JTable in a JScrollPane which will cause the column names to be hidden
add(new JScrollPane(table));

Java. Swing JTable. Changing data in a JTable and calling custom methods in the Table Model

I've learned how to display a JTable in a Frame, but I can't figure out how to actually change the data. I've read a ton of tutorials on the subject, but nothing seems to click. Can you answer some questions about the code below?
1) In the actionListener, I call tab.getModel().getValueAt(1,1) and tab.getValueAt(1,1). I get the same data, "Petty." Is the "getModel()" necessary if it delivers the same data?
I figured that "getModel()" allowed me to access any custom methods I wrote in the CustomTable.java class, but that doesn't seem to be true.
The command tab.getModel().setValueAt(pane, 1, 2); does nothing. It doesn't even run the System.out.println command in the method. So the method isn't even getting called.
2) Why can I call "getValueAt" but not "setValueAt"?
I wrote a new method called "test()". If I call it in the actionPerformed method, it's produces a compile error. It's as if the method doesn't exist.
3) So how do I call these custom methods in AbstractTable Model?
In the program I'm working now, the table is populated by the results of a SQL query. I have a method in a Service class that populates the ArrayList below with custom objects built from the query. It displays the data just fine.
I wrote a method "reQuery" in the AbstractTableModel class, which calls a method in the Service and repopulates the ArrayList with data from a fresh query. This method works properly, but I can't call it (much less update the table data).
What am I missing here?
The main method is just "new MainFrame();" THe MainFrame and CustomTable classes are below.
package scratchpad3;
import javax.swing.*;
import java.awt.event.*;
public class MainFrame extends JFrame implements ActionListener {
JPanel pane = new JPanel();
JButton butt = new JButton("Push Me To Update The Table");
JTable tab = new JTable(new CustomTable());
MainFrame(){
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(1000,200,1000,1000);
pane.setLayout(null);
add(pane);
butt.setBounds(20,10,200,100);
butt.addActionListener(this);
pane.add(butt);
tab.setBounds(20,125,500,500);
pane.add(tab);
tab.setValueAt(pane, 1, 2);
}
public void actionPerformed(ActionEvent e){
System.out.println("With getModel() " + tab.getModel().getValueAt(1, 1) );
System.out.println("Without getModel() " + tab.getValueAt(1, 1) );
tab.getModel().setValueAt("Tampa", 1, 2);
tab.getModel().test();
}
}
CustomTable.java
package scratchpad3;
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
public class CustomTable extends AbstractTableModel {
String[] colName = {"First Name", "Last Name", "City", "State"};
ArrayList<String[]> rows = new ArrayList<String[]>();
public String getColumnName(int col){
return colName[col];
}
public int getColumnCount(){
return colName.length;
}
public int getRowCount(){
return rows.size();
}
public String getValueAt(int row, int col){
System.out.println("getValueAt method was called."); //To verify the method was called
String[] s = rows.get(row);
return s[col];
}
public boolean isCellEditable(int col, int row){
return true;
}
public void setValueAt(String s, int row, int col){
System.out.println("setValueAt method was called"); //To verify the method was called
rows.get(row)[col] = s;
fireTableDataChanged();
}
public void test(){
System.out.println("Test");
}
CustomTable(){
rows.add(new String[]{"Bob", "Barker", "Glendale", "CA"});
rows.add(new String[]{"Tom", "Petty", "Jacksonville", "FL"});
}
}
You don't override the AbstractTableModel.setValueAt method, because you use incorrect signature. It should be public void setValueAt(Object s, int row, int col) instead of public void setValueAt(String s, int row, int col).

JTable row sorter - IllegalArgumentException: Invalid SortKey

Can someone help me with this?
It was working until I changed something trying to optimaze it... damn!
This is my table model:
class MyTableModel extends DefaultTableModel {
private String[] columnNames = {"Last Name","First Name","Next Visit"}; //column header labels
Object[][] data = new Object[100][3];
public void reloadJTable(List<Customer> list) {
for(int i=0; i< list.size(); i++){
data[i][0] = list.get(i).getLastName();
data[i][1] = list.get(i).getFirstName();
if (list.get(i).getNextVisit()==null) {
data[i][2] = "NOT SET";
} else {
String date = displayDateFormat.format(list.get(i).getNextVisit().getTime());
data[i][2] = date;
}
model.addRow(data);
}
}
public void clearJTable() {
model.setRowCount(0);
}
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) {
return getValueAt(0, c).getClass();
}
/*
* Don't need to implement this method unless your table's
* editable.
*/
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
}
}
}
and this is how I implement the JTable:
// these declarations are all private shared across the model
JTable customerTbl;
MyTableModel model;
List<Customer> customers = new ArrayList<Customer>();
SimpleDateFormat displayDateFormat = new SimpleDateFormat ("EEE dd-MM-yyyy 'at' hh:mm");
//JTable configuration
model = new MyTableModel();
customerTbl = new JTable(model);
model.reloadJTable(customers);
customerTbl.setAutoCreateRowSorter(true); //enable row sorters
DefaultRowSorter sorter = ((DefaultRowSorter)customerTbl.getRowSorter()); //default sort by Last Name
ArrayList list = new ArrayList();
list.add( new RowSorter.SortKey(0, SortOrder.ASCENDING));
sorter.setSortKeys(list); //EXCEPTION HERE
sorter.sort();
customerTbl.getColumnModel().getColumn(0).setPreferredWidth(100); //set Last Name column preferred width
customerTbl.getColumnModel().getColumn(1).setPreferredWidth(80); //set First Name column preferred width
customerTbl.getColumnModel().getColumn(2).setPreferredWidth(150); //set Last Visit column preferred width
I'm getting the following exception triggered on:
sorter.setSortKeys(list);
Exception in thread "main" java.lang.IllegalArgumentException: Invalid SortKey
at javax.swing.DefaultRowSorter.setSortKeys(Unknown Source)
at com.vetapp.customer.CustomersGUI.<init>(CustomersGUI.java:128)
at com.vetapp.main.VetApp.main(VetApp.java:31)
I believe it has to do with the TableColumnModel which is not created correctly...
The main problem is that the column count is returning 0 from the TableModel's super class DefaultTableModel. You need to override this method
#Override
public int getColumnCount() {
return columnNames.length;
}
Another side but potentially fatal issue is the fact that getColumnClass is returning the class of elements within the TableModel. This will throw a NullPointerException if the table is empty. Use a class literal instead such as String.class.
Maintaining a separate backing data array is unnecessary for DefaultTableModel. It has already has its own data vector. This approach is used when extending AbstractTableModel.

Making an addRows() method for a Custom JTable TableModel

My explanation below rambles, boiling down, is there a way I can add a Row without firing off an event, such that I can add multiple rows and fire an event to update all of them at once? Without having to add code to contain the table data in the custom model?
I have a custom TableModel which extends from DefaultTableModel so that I can use DefaultTableModel to keep track of data for me, whilst still having some custom methods of my own.
The issue is, I was thinking it might be faster for me to have an "addRows(String[][] val)" method, when I wish to add multiple rows. I could then fire a single event, probably fireTableDataChanged() to update the rows all at once. For example, my current method:
JTable table1 = new JTable(new dgvTableModel(new String[] {<values>},0, new String[] {<values>}));
table1.addRow(new String[] {<values here>});
table1.addRow(new String[] {<values here>});
table1.addRow(new String[] {<values here>});
I would then repeat the above as many times as necessary. The issue is, each of those will fire off a seperate event. It would be much faster (I think), if I could do this using my custom table model:
JTable table1 = new JTable(new dgvTableModel(new String[] {<values>},0, new String[] {<values>}));
table1.addRows(new String[][] {{<values1 here}, {values2 here}, . . .}});
and then in the table model:
public void addRows(String[][] values) {
for (String[] vals : values)
super.addRow(vals);
}
fireTableDataChanged();
}
I can code this in easily. The issue is again, that "super.addRow(vals);" line will fire an event each time through. Is there a way, without adding code to have my model contain the table data itself, to prevent that event being fired each time I add a row? Such that it waits for the fireTableDataChanged() call in the addRows method?
For reference, the code for my custom table model:
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
public class dgvTableModel extends DefaultTableModel {
//private DataTable tableVals = new DataTable();
private ArrayList<Color> rowColors;
//private ArrayList<Object[]> data = new ArrayList<>();
//default constructor has no data to begin with.
private int[] editableColumnNames;
public dgvTableModel(String[] colNames, int rowCount)
{
super(colNames, rowCount);
}
public dgvTableModel(String[] colNames, int rowCount, String[] editableColNames)
{
super(colNames, rowCount);
//this.tableVals.setColNames(colNames);
if (editableColNames!=null && editableColNames.length >0)
{
editableColumnNames = new int[editableColNames.length];
int count = 0;
for (int i =0; i< editableColNames.length;i++)
{
for (String val : colNames)
{
if (val.equalsIgnoreCase(editableColNames[i]))
{
editableColumnNames[count] = i;
count+=1;
break;
}
}
}
}
}
public dgvTableModel(String[] colNames, int rowCount, String[] editableColNames, boolean colorChanges)
{
super(colNames, rowCount);
Color defColor = UIManager.getDefaults().getColor("Table.background");
if (editableColNames!=null && editableColNames.length >0)
{
editableColumnNames = new int[editableColNames.length];
int count = 0;
if (colorChanges)
{
rowColors = new ArrayList<>();
}
for (int i =0; i< colNames.length;i++)
{
if (colorChanges)
{
rowColors.add(defColor);
}
for (String val : editableColNames)
{
if (val.equalsIgnoreCase(colNames[i]))
{
editableColumnNames[count] = i;
count+=1;
break;
}
}
}
}
else if (colorChanges)
{
rowColors = new ArrayList<>();
for (String val : colNames)
{
rowColors.add(defColor);
}
}
}
#Override
public boolean isCellEditable(int row, int column)
{
if(editableColumnNames!=null && editableColumnNames.length >0)
{
for (int colID : editableColumnNames)
{
if (column==colID)
return true;
}
}
return false;
}
public void setRowColor(int row, Color c)
{
rowColors.set(row, c);
fireTableRowsUpdated(row,row);
}
public Color getRowColor(int row)
{
return rowColors.get(row);
}
#Override
public Class getColumnClass(int column)
{
return String.class;
}
#Override
public String getValueAt(int row, int column)
{
return super.getValueAt(row, column).toString();
}
}
Surely firing one event to display every row, is faster than firing one event for each row?
'AbstractTableModel.fireTableDataChanged()' is used to indicate to the model (and the JTable UI which is notified by the model) that all possible data in the table may have changed and needs to be checked. This can (with emphasis on can) be an expensive operation. If you know which rows have been added, just use the 'AbstractTableModel.fireTableRowsInserted(int firstRow, int lastRow)' method instead. This will ensure only the effect rows are seen as changed. Take a look at all the fire* methods in AbstractTableModel. You can really exercise fine grained control over which rows, cells, etc are seen as dirty.
Then again what your doing might be premature optimalization. Unless you have fiftythousand records in your JTable this is probably not going to be noticable. But if you have a massive amount of records in your JTable you might be beter of lazy loading them anyway.

Dependent columns in a JTable

Hie!
I have a JTable. Columns of this JTable are rendered by JComboBox.
I would like to be able to change items of column 2 on the basis of values selected in column 1.
For example if the user selects Microsoft in column 1, then in column 2 he/she can select ado, wpf, etc.
Is it possible ?
If it is possible, than which events should be listened to do it ?
The Combo Box Table Editor provides one possible solution for this.
Maybe you can base you on this code;
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
}
}
);
This is an intresting page: click
Just make your own TableCellEditor that preps the JComboBox's model on the call to getTableCellEditorComponent. Something like this:
class MyEditor extends DefaultCellEditor{
public MyEditor() {
super(new JComboBox());
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
JComboBox combo = (JComboBox)editorComponent;
Object column1Value = table.getValueAt(row, column-1);
Object[] options = ... create options based on other value
combo.setModel(new DefaultComboBoxModel(options));
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
}
What are you using as values in your TableModel?
One solution would be to define a class, say CategoryValue, that represents a list of possible items and a selected item, and use that; then listen for TableModelEvents and when a value in column 0 changes, set the corresponding value in column 1. A simple example is below.
First, the TableModelListener:
model.addTableModelListener(new TableModelListener() {
#Override
public void tableChanged(TableModelEvent e) {
if (e.getColumn() == 0) {
int firstRow = e.getFirstRow();
int lastRow = e.getLastRow();
for (int row = firstRow; row <= lastRow; row++) { // note <=, not <
CategoryValue parentValue = ((CategoryValue) model.getValueAt(row, 0));
String parentSelection = parentValue.getSelection();
List<String> childCategories = getChildCategories(parentSelection);
CategoryValue newChildValue = new CategoryValue(childCategories);
model.setValueAt(newChildValue , row, 1);
}
}
}
});
(Implementing getChildCategories(String) depends on where your data is coming from, but it could be as simple as a Map<String, List<String>>.)
Next, the value class:
public class CategoryValue {
private final String selection;
private final List<String> categories;
public CategoryValue(List<String> categories) {
this(categories, categories.get(0));
}
public CategoryValue(List<String> categories, String selection) {
assert categories.contains(selection);
this.categories = categories;
this.selection = selection;
}
public String getSelection() {
return selection;
}
public List<String> getCategories() {
return categories;
}
#Override
public String toString() {
return selection;
}
}
Finally, a custom cell editor for the value class:
public class CategoryCellEditor extends DefaultCellEditor {
public CategoryCellEditor() {
super(new JComboBox());
}
static List<CategoryValue> allValues(List<String> categories) {
List<CategoryValue> allValues = new ArrayList<CategoryValue>();
for (String value: categories) {
allValues.add(new CategoryValue(categories, value));
}
return Collections.unmodifiableList(allValues);
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
CategoryValue categoryValue = (CategoryValue) value;
List<String> categories = categoryValue.getCategories();
List<CategoryValue> allValues = CategoryValue.allValues(categories);
ComboBoxModel cbModel = new DefaultComboBoxModel(allValues.toArray());
((JComboBox)editorComponent).setModel(cbModel);
return super.getTableCellEditorComponent(table, categoryValue,
isSelected, row, column);
}
}
All done with one event listener, and a nice bonus is that that event listener doesn't care how the table is edited/updated, or where the edits/updates come from.
Edited to add: Alternatively, represent each row of the table with some business object that captures all the choices made for a particular row, and have the CellEditor get the available choices from the business object (using the row argument to getTableCellEditorComponent() to get the business object). The event mechanism would remain the same. This has the advantage that it's probably easier to read the selected values from the business object than to scrape the table.

Categories