Hey guys i doing my assignment and now i have the problem with non editable cells, actually it became editable, but the result of editing didn't set at arraylist, I tried many solution from internet, but it doesn't work.
So my work like registration system which get information about guest, and then stored it into csv file. In additional function the program must let display, update, delete and searching function.
I finished all, without update,delete and searching. Can you please looking my code and help me or give the advice, link or something useful.
this is my abstract model:
public class ddispmodel extends AbstractTableModel {
private final String[] columnNames = { "FirstName", "SecondName", "Date of
birth", "Gender", "Email", "Address", "Number", "Attending","ID" };
private ArrayList<String[]> Data = new ArrayList<String[]>();
private boolean editable;
public void AddCSVData(ArrayList<String[]> DataIn) {
this.Data = DataIn;
this.fireTableDataChanged();
}
#Override
public int getColumnCount() {
return columnNames.length;// length;
}
#Override
public int getRowCount() {
return Data.size();
}
#Override
public String getColumnName(int col) {
return columnNames[col];
}
#Override
public Object getValueAt(int row, int col) {
return Data.get(row)[col];
}
public boolean isCellEditable(int row, int col) {
setValueAt(Data, row, col);
this.fireTableCellUpdated(row, col);
return true;
}
}
This is part of my main class
It is action Listener of menu item witch activate displaying function
(I didn't copy all class, because it nearly 1000 lines, but if it necessary, i can submit all code )
dlog.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent e){
CSVFileDomestic Rd = new CSVFileDomestic();
ddispmodel ddispm = new ddispmodel();
ddisp.setModel(ddispm);
File DataFile = new File("D:\\cdne4\\WorkPlace\\Domestic.csv");
ArrayList<String[]> Rs2 = Rd.ReadCSVfile(DataFile);
ddispm.AddCSVData(Rs2);
System.out.println("Rows: " + ddispm.getRowCount());
System.out.println("Cols: " + ddispm.getColumnCount());
cl.show(cp, "dispDomPanel");
}
});
and File class which convert date from csv to arraylist
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
public class CSVFileDomestic {
private final ArrayList<String[]> Rs = new ArrayList<String[]>();
private String[] OneRow;
public ArrayList<String[]> ReadCSVfile(File DataFile) {
try {
BufferedReader brd = new BufferedReader(new
FileReader(DataFile));
while (brd.ready()) {
String st = brd.readLine();
OneRow = st.split(",");
Rs.add(OneRow);
System.out.println(Arrays.toString(OneRow));
}
}
catch (Exception e) {
String errmsg = e.getMessage();
System.out.println("File not found:" + errmsg);
}
return Rs;
I am new at Java and this is my first program , please can you explain more easily
but the result of editing didn't set at arraylist,
You need to override the setValueAt(...) method of the TableModel to save the data.
It would be something like:
String[] row = data.get(row);
row[column] = value;
this.fireTableCellUpdated(row, col);
Also, the isCellEditable(...) method should NOT do any processing. It simply returns true/false for the given column. If you want all columns editable then it should just be:
public boolean isCellEditable(int row, int col) {
//setValueAt(Data, row, col);
//this.fireTableCellUpdated(row, col);
return true;
}
I finish this)) and go to do others options.
camickr thank you for help, you give me the way, which bring me to answer))
I spend nearly 6 hours for trying to do it and finally I got it.
If someone interesting, answer is
public boolean isCellEditable(int row, int col) {
return true;
}
#Override
public void setValueAt(Object aValue, int row, int col){
Data.get(row)[col]= (String) aValue;
fireTableCellUpdated(row,col);
so I just make new method setValueAT which said me camickr.
than I went to Oracle site and read about it, and after try it to do, but
it doesn't, because aValue can't be converted from object to String, and finally I initiate aValue as a String, so now it works.However it is not all, it only change arraylist. Needs new method to convert arraylist to csv file. I am working about it now, maybe after I will show it. Sorry for my theory, I am new at java, just learn how it works))
Related
Im developing a app for ordeing system and i have to set data into JTabels.
And this code is successfully working.I wanted to know what the importance of and whats happen in this class?
Why we need to import AbstractTabelModel.class?
OrderTabelModel Class:-
public class OrderTableModel extends AbstractTableModel{
protected static final String[] COLUMN_NAMES={"Item","Qty","Amount"};
private List<Order> rows;
public OrderTableModel(List<Order> rows){
this.rows = new ArrayList<>(rows);
}
#Override
public int getRowCount() {
return rows.size();
}
#Override
public int getColumnCount() {
return COLUMN_NAMES.length;
}
#Override
public String getColumnName(int column) {
return COLUMN_NAMES[column];
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object value = null;
Order row = rows.get(rowIndex);
switch (columnIndex) {
case 0:
value = row.getItem();
break;
case 1:
value = row.getQty();
break;
case 2:
value = row.getAmount();
break;
}
return value;
}
}
this is other class
private void tblOrderListMouseClicked(java.awt.event.MouseEvent evt) {
int raw = tblOrderList.getSelectedRow();
Order or;
String item;
Double qty,amount,total;
ArrayList<Order> arrOrder = new ArrayList<Order>();
String selectedRaw = tblOrderList.getModel().getValueAt(raw, 0).toString();
System.out.println("order id : "+selectedRaw);
String sql = "select item,qty,amount from orderdetails where orderid='"+selectedRaw+"'";
con = new DBconnector().connect();
try {
Statement ps =con.createStatement();
ResultSet rs2 = ps.executeQuery(sql);
while(rs2.next()){
or = new Order();
or.setItem(rs2.getString("item"));
System.out.println("Item :" +rs2.getString("item"));
or.setQty(rs2.getDouble("qty"));
or.setAmount(rs2.getDouble("amount"));
arrOrder.add(or);
}
rs2.close();
ps.close();
OrderTableModel tblModel = new OrderTableModel(arrOrder);
tblOrderItems.setModel(tblModel);
} catch (Exception e) {
e.printStackTrace();
}
}
Can some one explain me the process of this please?
It is not always mandatory to extend the AbstractTableModel. You can simply extend the DefaultTableModel and only override the getValueAt() method if you have to.
But most of the time for simple usages it is not even needed to override the getValueAt() method either.
By using the DefaultTableModel, you have a limitation for the converting you data (imported from DB) to an object[][] or Vector types which may be a little boring.
But you asked what is the importance of using AbstractTabelModel?
In this case I can say when JTable is started to being rendered, it needs to determine the number of rows and number of the columns and also it needs to know which data should be renedered in each cell and so on. Based on this, JTable ask for this Information from the underlying TableModel. So it is needed for your TableModel(any child or implementation of TableModel) to have those methods which are used by JTable to retrieve the needed information.
Hope this would be helpful.
Good Luck.
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).
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.
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.
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.