making Jtable with add,delete,reset and sorting - java

Hey does anyone know how to make program using JTable with some function with the column that contain variable type: String, Double,Int so it will contain 3 column with different variable
add Row in table (JButton)
Delete Row in table (JButton)
Reset the Table(JButton)
Sorting function

Object obj[][]=null;
Table.setModel(obj);
Add row but updating 'obj' and again call Table.setModel(obj);
Delete row same as above.
for reset table
table.setModel(new DefaultTableModel(
new Object[][]
{
{null, null},
}
) {
Class[] columnTypes = new Class[] {
public Class getColumnClass(int columnIndex) {
boolean[] columnEditables = new boolean[] {
public boolean isCellEditable(int row, int column) {
});
Sorting ::
I don't know what are you trying to sort but values can be extraxted via getModel()
TableModel Model= T.getModel();
After that you may sort the values and then reinsert into the table by
Model.setValueAt(value,int row,int column);

Related

JTable, get data from another method an sort it?

Normally i get the Data from my Tablemodel
table.setModel(new DefaultTableModel(
new Object[][] {
{"xxx", new Integer(10)},
{"xx", new Integer(40)},
{"x", new Integer(20)},
{"xxxxxx", new Integer(50)},
{"xxxxx", new Integer(30)},
},
new String[] {
"name", "tel"
}
But now i would get the Data from the "name" and "tel" from other Methods. The first method returns a String, who i would put in the "name".
The second method returns a Integer, who i would put in the "tel".
Then i would sort it, that the lowest integer is the first. Any name has his own telephonenumber.
My method Sorter:
public void sort()
{
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>();
table.setRowSorter( sorter );
sorter.setModel( model );
}
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {}
But it doesn't sort, i don't know what i should do.
Check this you should get your answer
Sort Java Collection
Sorting is best when you hava made a collection. I preffer to make a collection than sort it and than display it on JTable.
https://docs.oracle.com/javase/tutorial/collections/algorithms/

Implementing few excel functionality using JTable

I am trying to implement Summation function of MS EXCEL but not getting a way to get the values from the JTable cells. Can you suggest me some way to get the values from the cells and use it for my function?
For example, how can you get the value -
String data[][] = {{"Value1", "Value2", "Value3"},{"Value4", "Value5", "Value6"},
{"Value7", "Value8", "Value9"},{"Value10", "Value11", "Value12"}};
String col[] = {"Column1", "Column2", "Column3"};
DefaultTableModel model = new DefaultTableModel(data, col);
JTable table = new JTable(model);
...
System.out.println(table.getModel().getValueAt(2, 2)); // row index and column index
...
it gives -
Value9
To get the values ​​from the table, you can implement the interface MouseListener in the anonymous inner class, for example -
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
JTable target = (JTable) e.getSource();
int rowIndex = target.getSelectedRow();
int columnIndex = target.getSelectedColumn();
System.out.println(target.getModel().getValueAt(rowIndex, columnIndex));
}
});
See also:
How to Write a Mouse Listener
How to Write a List Selection Listener

How to Retrieve JTable Data as an Array

I've populated a JTable through a DefaultTableModel with the (Object[][] data, String[] headers) constructor. Users can edit the table, and I want to be able to load the new data back into an array (Object[][]). Note that I'd rather not just update the array bit by bit, but be able to just completely load a new array from the table. How can this be done?
I take that back, on 2nd thoughts, you dont need any typecasting - TableModel is an interface that has all the 3 method calls you need. :)
Summary: Get the model for the table, check its class and typecast it to appropriate class (Abstract or Default TableModel), and use its methods to load a newly created array. Some psuedoCode:
public Object[][] getTableData (JTable table) {
DefaultTableModel dtm = (DefaultTableModel) table.getModel();
int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
Object[][] tableData = new Object[nRow][nCol];
for (int i = 0 ; i < nRow ; i++)
for (int j = 0 ; j < nCol ; j++)
tableData[i][j] = dtm.getValueAt(i,j);
return tableData;
}
Your headers should not have changed by user-edits. Hope that helps. Regards, - M.S.
I'd like to suggest a small improvement on Manidip Sengupta's answer. Rather than casting table.getModel() to the appropriate class, it is better to simply work with TableModel. This makes the code more re-usable too (it doesn't matter which implementation of TableModel is actually being worked with).
public Object[][] getTableData (JTable table) {
TableModel dtm = table.getModel();
int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
Object[][] tableData = new Object[nRow][nCol];
for (int i = 0 ; i < nRow ; i++)
for (int j = 0 ; j < nCol ; j++)
tableData[i][j] = dtm.getValueAt(i,j);
return tableData;
}
I've populated a JTable through a DefaultTableModel with the (Object[][] data, String[] headers)
The DefaultTableModel is a dynamic model, which means rows and columns can be added dynamically. Arrays are not dynamic so when you create a DefaultTableModel using arrays, the data from the arrays is copied to a Vector of Vectors.
I want to be able to load the new data back into an array (Object[][]).
I'd rather not just update the array bit by bit
Unfortunately you will have to update the array cell by cell since the data is not stored in a 2D array.
Or, since the DefaultTableModel does use a Vector of Vectors to store the data you can use the getDataVector() method to access the data. Then you get each row from the Vector and invoke the List.toArray() method on the row Vector before adding it to your array.
Either way you will need to loop through the Vectors in the model.
If you want to use the 2D array as storage for the TableModel, then you will need to create a custom TableModel that uses the supplied array for the data storage. After implemting all the required methods of the TableModel interface you will need to provide a getTableDataArray() method to return the reference to the array.
Not with the existing default table model. As a rule of thumb, you should ever use the default table model. You should implement your own table model (MyTableModel). You can either implement TableModel or extend AbstractTableModel. I suggest the latter as it provides some nice utility methods. There are 2 ways to achieve what you are doing
populate your new data into a new instance of MyTableModel and call JTable.setModel().
A second way is to create a method in MyTableModel call eg, replaceData(T[][] data). Hold a reference to the model that the table is current displaying. Whenever you want to replace the data, call replaceData(). Assuming you are extending AbstractTableModel, then call fireTableChanged() to notify the table.
With the out-of-the-box JTable implementation, you can't. When you initialize a JTable with Object[][] rowData that rowData is used by an anonymous AbstractTableModel instance but it's not accesible as such from outside.
public JTable(final Object[][] rowData, final Object[] columnNames) {
this(new AbstractTableModel() {
public String getColumnName(int column) { return columnNames[column].toString(); }
public int getRowCount() { return rowData.length; }
public int getColumnCount() { return columnNames.length; }
public Object getValueAt(int row, int col) { return rowData[row][col]; }
public boolean isCellEditable(int row, int column) { return true; }
public void setValueAt(Object value, int row, int col) {
rowData[row][col] = value;
fireTableCellUpdated(row, col);
}
});
}
You could consider to subclass both JTable and AbstractTableModel and "overwrite" this constructor in JTable to create your own TableModel implementation that will hold that Object[][] reference and return it with Object[][] getRowData(). Or just keep the rowData as a field in the JTable subclass itself after calling super(...) in that constructor -- if you don't really care about MVC.
But you need to make sure that after the table is edited, the initial model is preserved and not replaced by a new model object (of course, of a different type) with setModel. If this is the case, what you want is impossible to achieve -- you will need to iterate through all the cells.

create TableModel and populate jTable dynamically

I want to store the results of reading lucene index into jTable, so that I can make it sortable by different columns. From index I am reading terms with different measures of their frequencies.
Table columns are these :
[string term][int absFrequency][int docFrequency][double invFrequency]
So i in AbstractTableModel I can define column names, but i dont know how to get the Object[][]data with results from the following method:
public static void FrequencyMap(Directory indexDir) throws Exception
{
List<ArrayList>redoviLista = new ArrayList<ArrayList>();
//final Map<String,TermRow> map = new TreeMap<String,TermRow>();
List<String>termList = new ArrayList<String>();
IndexReader iReader = IndexReader.open(indexDir);
FilterIndexReader fReader = new FilterIndexReader(iReader);
int numOfDocs = fReader.numDocs();
TermEnum terms = fReader.terms();
while (terms.next()){
Term term = terms.term();
String termText = term.text();
termList.add(termText);
//Calculating the frequencies
int df = iReader.docFreq(term);
double idf = 0.0F;
idf = Math.log10((double) numOfDocs / df);
double tfidf = (df*idf);
//Here comes important part
//Changes according to takoi's answer
ArrayList<Object> oneRow = new ArrayList<Object>();
oneRow.add(termText);
oneRow.add(df);
oneRow.add(idf);
oneRow.add(tfidf);
redoviLista.add(oneRow);
}
iReader.close();
// So I need something like this, and i Neeed this array to be stored out of this method
So I am kindda stuck here to proceed to implement AbstractTableModel and populate and display this table .... :/
Please help!
When you are inserting, deleting or updating data in your model, you need to notify the GUI of the changes. You can do this with the fire-methods in the AbstractTableModel.
I.e. if you add an element to your list, you also have to call fireTableRowsInserted(int firstRow, int lastRow) so that the visible layer can be updated.
Have a look at addElement(MyElement e) in the code below:
public class MyModel extends AbstractTableModel {
private static final String[] columnNames = {"column 1", "column 2"};
private final LinkedList<MyElement> list;
private MyModel() {
list = new LinkedList<MyElement>();
}
public void addElement(MyElement e) {
// Adds the element in the last position in the list
list.add(e);
fireTableRowsInserted(list.size()-1, list.size()-1);
}
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public int getRowCount() {
return list.size();
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch(columnIndex) {
case 0: return list.get(rowIndex).getColumnOne();
case 1: return list.get(rowIndex).getColumnOne();
}
return null;
}
}
There is no need to create a custom TableModel for this. Just use the DefaultListModel.
The DefaultListModel allows you to dynamcially add rows to the model using the addRow(...) method and it automatically invokes the appropriate fireXXX method to tell the table to repaint itself.
The basic code would be:
DefaultTableModel model = new DefaultTableModel( columnNames );
while (...)
{
Vector row = new Vector();
row.add(...)
row.add(...)
model.addRow( row );
}
JTable table = new JTable( model );
You don't need to create a custom TableModel everytime. Sometimes you can start with the DefaultTableModel.
You dont have to create an Object[][]. Just make your redoviLista a list of lists:
redoviLista.add( new ArrayList<Object>(termText, df, idf, tfidf) ); #pseudocode
then you implement getValueAt like this:
getValueAt(int row, int column){
redoviLista.get(row).get(column);
}

Manipulating fields in the jTable Java

I have populated my jTable with the following Code. It has two columns, the first has variable name and the second is a list of its dependencies. The user can change the dependencies by selecting them from the list in the jTable.
When the user changes a value, I want to row to be added to another jTable (which would be no user editable. How would I do that?
The code to populate the table is
Vector<Vector> data = new Vector<Vector>();
for (String v : acn.getVariableNames()) {
Vector tmp = new Vector();
tmp.add(v);
ArrayList<String> temp = new ArrayList<String>();
for (String u : acn.getVariableDomain(v)) {
temp.add(u);
}
tmp.add(temp);
data.add(tmp);
}
Vector names = new Vector();
names.add("Variable");
names.add("Domain Value");
DefaultTableModel dt = new DefaultTableModel();
dt.setDataVector(data, names);
jTable2.setModel(dt);
jTable2.getColumnModel().getColumn(1).setCellEditor(new ChangeImpactEditor());
jTable2.getColumnModel().getColumn(1).setCellRenderer(new TableListRenderer());
The way i would do it is to override
public void setValueAt(Object aValue, int rowIndex, int columnIndex);
from your TableModel.
The setValue method get called by the JTable after the user has editted a value
In your overriden method you then can set the value in the other tablemodel

Categories

Resources