Read cell value in JTable while it is being edited - java

Please guide me how can i read the value of jtable cell while it is in edit mode ( being edited). I have written above code in keyTyped event of jtable.
int col = tblItem.getSelectedColumn();
int row = tblItem.getSelectedRow();
try {
float value = Float.parseFloat(tblItem.getModel().getValueAt(row,2).toString());
String str = new help.StringHelp().convertFloatString(value);
tblItem.setValueAt(str + "", row, 2);
} catch (Exception ex) {
ex.printStackTrace();
}
Suggest me how can i solve this issue.

and directly press save button
So you need to stop editing on the cell before doing the Save.
You can either use:
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
when you create the table.
Or use:
if (table.isEditing())
table.getCellEditor().stopCellEditing();
in the ActionListener of your button.
Check out Table Stop Editing for more information.

Related

JTable get value from cell when is not submitted

I would like to get value from cell when its is no submitted (cell is in edit mode) - "real time"; Is it possible?
I tried this but it is working only if i submit data - press enter
int row = jTable.getSelectedRow();
int col = jTable.getSelectedColumn();
String cellValue = jTable.getValueAt(row, col).toString();
I want to get on keypress cell value without exiting it, get this text real time while typing
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
#Override
public boolean dispatchKeyEvent(KeyEvent e) {
int row = jTable.getSelectedRow();
int col = jTable.getSelectedColumn();
if (e.getID() == KeyEvent.KEY_RELEASED) {
if (jTable.isEditing())
jTable.getCellEditor().stopCellEditing();
String cellValue = (jTable.getValueAt(row, col)!=null) ? jTable.getValueAt(row, col).toString() : "";
System.out.println(cellValue);
}}
jTable.getCellEditor().stopCellEditing() - cause ugly in/out animation while typing
#camickr Sorry for the confusion. Your solution is ok.
I just needed to add jTable.editCellAt(row, col); to get back into edit mode.
Thanks again
cell is in edit mode
The editing must be stopped before the value is saved to the model.
The easiest way to do this is to use:
JTable table = new JTable(...);
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
when you create the table.
Now when you click on the button to do your processing the table loses focus so the data is saved.
Check out Table Stop Editing for more information.

Select a row of a Table for second time

i currently able to select a row of table using ListSelectionModel object and open a new window. but if i close that window and click that row again, it would not open anymore until i select another row of table (i can't select a row for a second time). do you know how can i solve this issue ?
this is what i have done:
ListSelectionModel model = table.getSelectionModel();
model.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e)
{
if(!model.getValueIsAdjusting())
{
int row = model.getMinSelectionIndex();
//new Window opens :
SubjectDetail sd = new SubjectDetail(Datalist2.project.listOfData().get(row));
}
}
});
The selection is not working because that particular row is already selected.
Try clearing the selection when a new window is opened.
table.getSelectionModel().clearSelection().

How to get the contains of file in jtable?

I create a jtable like this :
String name = temp.getName();
String enemy = namaFileUtama.toString();
DefaultTableModel models = (DefaultTableModel) Main_Menu.jTable4.getModel();
List<ReportMomentOfTruth> theListRMOT = new ArrayList<ReportMomentOfTruth>();
ReportMomentOfTruth rmot = new ReportMomentOfTruth();
rmot.setNameOfMainFile(name);
rmot.setNameOfComparingFile(enemy);
theListRMOT.add(rmot);
for (ReportMomentOfTruth reportMomentOfTruth : theListRMOT) {
models.addRow(new Object[]{
reportMomentOfTruth.getNamaFileUtama(),
reportMomentOfTruth.getNamaFilePembanding(),
});
}
You know, I dont get an idea. How can I get the contains the file if I click one row in jtable then the contains will be show in jTextArea ? Any suggestion ? any example perhaps ?
Thanks
edit
You know, I am using netbeans, I can get a method like this
private void jTable4MouseClicked(java.awt.event.MouseEvent evt) {
if (evt.getClickCount() == 1) {
}
}
Now how to ?
How can I get the contains the file if I click one row in jtable then the contains will be show in jTextArea?
You can better use JEditorPane that has a method setPage() that can be used to initialize the component from a URL.
Just get the values of selected row and use below code to set the content in JEditorPane.
sample code:
final JEditorPane document = new JEditorPane();
document.setPage(new File(".../a.java").toURI().toURL());
Add ListSelectionListener to detect the selection change event in the JTable
final JTable jTable = new JTable();
jTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int row = jTable.getSelectedRow();
if(row != -1){
String firstColumnValue = jTable.getModel().getValueAt(row, 0).toString();
String secondColumnValue = jTable.getModel().getValueAt(row, 1).toString();
// load the JEditorPane
}
}
});;
Read more...

JTable reverts to old cells when clicked on

This Code is in a While Loop, and each time I run a new Query it will go through this block after I have chosen what to filter it by, the problem is when I run it a second time and click on a cell in my table it will revert to cells in my previous table/query. I attached an image to show what I mean(I need 10 reputation for that so nevermind on the picture), I filtered the table by procsessState = -1 and when I clicked on some cells it reverted to what the previous table had. Help would be greatly appreciated. The program is around 1000 lines long and I did a terrible job of splitting it into different classes So I just posted where I am almost certain the issue arises.
I declared
final String columnNamesForTable[] = {"Error Message", "ID", "Locked By", "Message Id", "Process State",
"Row Date", "Sender", "Sent Date", "Subject" };
At The top, then I have this a bit later on.
else if (checkBoxCounter != 0)
{
DefaultTableModel tableModel = new DefaultTableModel(columnNamesForTable, 0);
tableModel.fireTableDataChanged();
try
{
Connection conn = DatabaseConnection.getConnection();
System.out.println("Connected");
PreparedStatement statement = conn.prepareStatement(sb.toString(),
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
// Change CONCUR_READ_ONLY to CONCUR_UPDATABLE
ResultSet resultSet = statement.executeQuery();
int errorMessageIndex = resultSet.findColumn("ErrorMessage");
int idIndex = resultSet.findColumn("Id");
int lockedByIndex = resultSet.findColumn("LockedBy");
int messageIdIndex = resultSet.findColumn("MessageId");
int processStateIndex = resultSet.findColumn("ProcessState");
int rowDateIndex = resultSet.findColumn("RowDate");
int senderIndex = resultSet.findColumn("Sender");
int sentDateIndex = resultSet.findColumn("SentDate");
int subjectIndex = resultSet.findColumn("Subject");
while (resultSet.next()) {
Object[] rowsForTable = { resultSet.getString(errorMessageIndex),
resultSet.getString(idIndex), resultSet.getString(lockedByIndex),
resultSet.getString(messageIdIndex), resultSet.getString(processStateIndex),
resultSet.getString(rowDateIndex), resultSet.getString(senderIndex),
resultSet.getString(sentDateIndex), resultSet.getString(subjectIndex)};
tableModel.addRow(rowsForTable);
}
resultSet.close();
statement.close();
conn.close();
filterFrame.setVisible(false);
JTable resultsTable = new JTable(tableModel);
JScrollPane pane = new JScrollPane(resultsTable);
displayPnl.add(pane);
pack();
resultsTable.repaint();
isDone= true;
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Database error");
ex.printStackTrace();
isDone = true;
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Error loading database driver");
ex.printStackTrace();
isDone = true;
}
}
This Code is in a While Loop
Why would it be in a while loop. Swing is event driven. Code should only be executed when the uses generates some kind of event like clicking on a button, typing text, editing a cell.
I have chosen what to filter it by,
Don't create a whole new table and scroll pane. Just update the TableModel of the existing JTable.
pack();
Why would you pack the frame. The query could have 100's of rows of data. Pick a reasonable size for the table when the frame is created and there is no need to use pack() or repaint(). When you invoke the setModel(...) method of the JTable to replace the current model the table will be repainted automatically.
So all the code you need should be:
//filterFrame.setVisible(false);
//JTable resultsTable = new JTable(tableModel);
//JScrollPane pane = new JScrollPane(resultsTable);
//displayPnl.add(pane);
//pack();
//resultsTable.repaint();
existingTable.setModel( tableModel );
I cant comment I do not have enough reputation.
You fire tabledatachanged before changing data.
TableDataChanged does not always properly update rows , it seems better to fire update rows.
If your table is editable , if you clicked the table you need to release the editor.

Jtable shows "old" text even though render-component has no text anymore

i use Jpanel with a Jlabel on it as render-component in my jtable. i add "fake-entries" (=JLabel without text) if there are not enough entries to fill the whole table.
it happens from time to time that text is displayed in the jtable after deleting it. each entrie contains the text of the last table entrie (before the delete) e.g. "Gegeben Bar..."
Even calling a repaint doesn't solve the problem. Only after inserting a new row the table gets displayed correctly. jre is 1.4_09 on running on linux
here's what i do after clearing table-elements
model.fireTableRowsDeleted( firstRow, firstRow + rowCount - 1);
model.fireTableDataChanged();
i've a function to log the table elements and component when the problem occures
for(int i=0; i < model.getRowCount();i++){
try
{
bw.newLine();
bw.write("el"+i+" "+model.getValueAt(i, 1)+"->" +model.getValueAt(i, 1).hashCode());
bw.newLine();
bw.write(" ->"+((JPanel)renderer.getTableCellRendererComponent(this, model.getValueAt(i,1),false, false, i, 0)).getComponent(0).hashCode()+"->" +((JPanel)renderer.getTableCellRendererComponent(this, model.getValueAt(i,1),false, false, i, 0)).getComponent(0));
bw.newLine();
if(observedElement.getElements().size()>i)
bw.write(" -> "+observedElement.getElements().get(i));
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
in the output you can see the neither the element nor the jlabel contain text
el0 ->5840819
->20546691->javax.swing.JLabel[,4,0,273x19,alignmentX=0.0,alignmentY=null,border=,flags=8,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEFT,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=<html><font face="Inconsolata,Inconsolata"></font></html>,verticalAlignment=CENTER,verticalTextPosition=CENTER]
->
el1 ->5840819
->20546691->javax.swing.JLabel[,4,0,273x19,alignmentX=0.0,alignmentY=null,border=,flags=8,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEFT,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=<html><font face="Inconsolata,Inconsolata"></font></html>,verticalAlignment=CENTER,verticalTextPosition=CENTER]
->
el2 ->5840819
->20546691->javax.swing.JLabel[,4,0,273x19,alignmentX=0.0,alignmentY=null,border=,flags=8,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEFT,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=<html><font face="Inconsolata,Inconsolata"></font></html>,verticalAlignment=CENTER,verticalTextPosition=CENTER]
->
...
any idea what might be the cause of the problem or how to solve it?

Categories