Edited/Changed Value tracking in Jtable
how will i keep track of all the values of a only those cells that are edited(changed) in Jtable having multiple row and columns.
The reason for this is that I want to build a dynamic update query which updates only those cells(JTable corresponds to a resultset) that are changed.
http://forum.java.sun.com/thread.jsp?forum=57&thread=234558
Similar Messages
-
Editing the values of a JTable
I am trying to allow the user to edit the values of a JTable. I have captured the event of editing the table, but I can't find out how to know what the new value of cell is... it always gets reverted to the old value.
I can't find any method or way how to know what the new value is.
Any help?Problem solved ...
setValueAt() was not overridden ... -
Hi
It's a bit of a weird one. In an XSLT List View web part when Inline editing is enabled if I change the date column, it changes the lookup field column as well. This behavior only occurs if the lookup list has more than 20 entries. Below 20 and we are
OK.
Let me explain by example:
MileStones List - Having more than 20 items
Tasks List - having a lookup to the Title field from MileStones list. Also having a due date field.
Simple web part page with one XSLT List View web part for Tasks having inline editing enabled.
When I edit the first record's due date and press enter (which saves the changes and moves onto next record) and change the due date on second record without even touching the MileStone field. Press enter to commit changes and you see the milestone changing
on first record!
The wierd thing is that if the MileStone list has less than 20 items all works as expected.
Any pointers will be appreciated
ThanksHi,
This is a known limitation when working with complex fields like Lookup field.
A workaround is that we can avoid using the inline edit feature when there are
complex fields in a list.
You can take a look at this KB from Microsoft Support to get more details:
http://support.microsoft.com/kb/2600186/en-us
A similar thread for your reference:
http://social.technet.microsoft.com/Forums/sharepoint/en-US/3d369611-ee79-4b5c-86bb-c0f3878cd746/standard-list-view-with-inline-editing-lookup-column-copies-preceding-or-following-items-related?forum=sharepointgeneralprevious
Thanks
Patrick Liang
TechNet Community Support -
Hi all,
I m using interactive ALV grid with 1 column editable with some default values, When i m clicking on SAVE button, only the values which are changed by the user in that column are coming in the internal table, & the default values are automatically deleted by the following code....
But my requirement is to save all the default & changed values of the ALV column....
<b>Help me out & have ur points.</b>
DATA ref1 TYPE REF TO cl_gui_alv_grid.
CALL FUNCTION 'GET_GLOBALS_FROM_SLVC_FULLSCR'
importing
e_grid = ref1
CALL METHOD ref1->check_changed_data
IMPORTING
e_valid =
CHANGING
c_refresh = 'X'Pradeep,
When ur doing the CHECK_CHANGED_DATA, u ll get the edited values inside this callback sub -routine only. so here u trap the values those are changed ( thats after editing).
Once the control goes back to the original program ( calling prog ) , u ll end up with ur old data ( before editing).
you ll have to handle that explictly in your code, or shift to OO alv grid like this -
REPORT ZSKC_GRID.
TABLES : EQUI.
DATA : BEGIN OF T_EQUI OCCURS 0,
EQUNR TYPE EQUI-EQUNR,
AENAM TYPE EQUI-AENAM,
END OF T_EQUI.
DATA : T_FCAT TYPE LVC_T_FCAT,
G_FCODE TYPE SY-UCOMM.
DATA : G_GRID TYPE REF TO CL_GUI_ALV_GRID.
SELECT-OPTIONS: S_EQUNR FOR EQUI-EQUNR.
START-OF-SELECTION.
* get data.
PERFORM SUB_GET_DATA.
* Populate catalog.
PERFORM SUB_BUILD_CATALOG CHANGING T_FCAT.
* Display the grid.
PERFORM SUB_SHOW_GRID.
CALL SCREEN 9001.
*& Form SUB_GET_DATA
* Get data
FORM SUB_GET_DATA .
SELECT EQUNR AENAM
FROM EQUI
INTO TABLE T_EQUI
WHERE EQUNR IN S_EQUNR.
IF SY-SUBRC NE 0.
* Give some message if needed
ENDIF.
ENDFORM. " SUB_GET_DATA
*& Form SUB_BUILD_CATALOG
* text
* <--P_T_FCAT text
FORM SUB_BUILD_CATALOG CHANGING PT_FCAT TYPE LVC_T_FCAT.
DATA : WA_CAT TYPE LVC_S_FCAT.
CLEAR WA_CAT.
WA_CAT-FIELDNAME = 'EQUNR'.
WA_CAT-TABNAME = 'T_EQUI'.
WA_CAT-REF_FIELD = 'EQUNR'.
WA_CAT-REF_TABLE = 'EQUI'.
APPEND WA_CAT TO PT_FCAT.
CLEAR WA_CAT.
WA_CAT-FIELDNAME = 'AENAM'.
WA_CAT-TABNAME = 'T_EQUI'.
WA_CAT-REF_FIELD = 'AENAM'.
WA_CAT-REF_TABLE = 'EQUI'.
WA_CAT-EDIT = 'X'.
APPEND WA_CAT TO PT_FCAT.
ENDFORM. " SUB_BUILD_CATALOG
*& Form SUB_SHOW_GRID
* Show grid
FORM SUB_SHOW_GRID .
* create the Grid Object.
CREATE OBJECT G_GRID
EXPORTING
I_PARENT = CL_GUI_CONTAINER=>SCREEN0
EXCEPTIONS
ERROR_CNTL_CREATE = 1
ERROR_CNTL_INIT = 2
ERROR_CNTL_LINK = 3
ERROR_DP_CREATE = 4
OTHERS = 5.
CHECK SY-SUBRC EQ 0.
* Display contents,
CALL METHOD G_GRID->SET_TABLE_FOR_FIRST_DISPLAY
CHANGING
IT_OUTTAB = t_equi[]
IT_FIELDCATALOG = t_fcat
EXCEPTIONS
INVALID_PARAMETER_COMBINATION = 1
PROGRAM_ERROR = 2
TOO_MANY_LINES = 3
others = 4.
ENDFORM. " SUB_SHOW_GRID
*& Module STATUS_9001 OUTPUT
* text
MODULE STATUS_9001 OUTPUT.
SET PF-STATUS 'PF_9001'.
SET TITLEBAR 'TITLE_9001'.
ENDMODULE. " STATUS_9001 OUTPUT
*& Module USER_COMMAND_9001 INPUT
* text
MODULE USER_COMMAND_9001 INPUT.
CASE G_FCODE.
WHEN 'BACK' OR 'CANC' OR 'EXIT'.
LEAVE TO SCREEN 0.
WHEN 'HAVE'.
* After editing everything user presses this button.
PERFORM SUB_GET_EDITED_DATA.
ENDCASE.
ENDMODULE. " USER_COMMAND_9001 INPUT
*& Form SUB_GET_EDITED_DATA
* Read the ALV grid and get current internal table.
FORM SUB_GET_EDITED_DATA .
DATA : T_OLD_DATA LIKE T_EQUI OCCURS 0.
* hold the old values if u need them.
t_old_data[] = t_equi[].
* This will update the global internal table.
CALL METHOD G_GRID->CHECK_CHANGED_DATA.
* Now t_equi have changed here. u have the old data in the T_OLD_DATA.
BREAK-POINT.
ENDFORM. " SUB_GET_EDITED_DATA
Create a blank screen called 9001. and Pf-staus has a buton with fcode "HAVE". ( alongwith BACK canc exit). -
How to paint a Custom Cell while you are editing on adjacent Cell in JTabl
Hi All,
I have two Columns in my Custom Table . Both Two Columns are Custom Cell Editors/Renderers.
I have made UI such that Column1 is Label , Column 2 is TextBox / Combo/ UI Input any
My Custom Table View when i edit some value against Max Conn. it should display Blue
=================================
Column A | Column B
==================================
Timeout | some_unchanged_value
*{color:#0000ff}Session{color}* | some_unchanged_value
Log File | some_unchanged_value
===================================
My issue is when i start typing in my Custom Editor suppose i Type /invoke Edtir of Index 2, Column 2 font should become Blue.
It becomes blue only when i debug this issue it perfectly works, without Debugger it doesnt changes the Font
MyDefaultRenderer is my Custom renderer - I have set Foregroud Color as BLUE
NOTE:_
In run method if table.repaint() instead of single renderer:
It turns Blue when i make call on table.repaint() methosd but i feel that repainting full table on every key Stroke should not be very good programming. Whats is more appropriate way?
I want to repaint only that particular cell against which i change the Value
private class MyDefaultEditor extends AbstractCellEditor implements TableCellEditor {
private JTextField txtField = null;
private int rowIndex;
public MyDefaultEditor() {
txtField = new JTextField();
txtField.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
super.keyTyped(e);
System.out.println("########### Hello This is MyDefaultEditor");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Call Renderer adjacentt to input to turn Blue (Is this Valid Code ??)
MyDefaultRenderer defRen = (MyDefaultRenderer) thisTable.getCellRenderer(activeRowIndex, 0);
defRen.paintMe();
// table.repaint() works for me but i dont want to call it on evey ket type, that will be Heave rite???
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column) {
rowIndex = row;
String valStr = "";
if (value != null && value instanceof String) {
valStr = value.toString();
txtField.repaint();
return txtField;
public Object getCellEditorValue() {
return txtField.getText();
}Edited by: Shubhadeep on Jun 27, 2009 1:58 AM
Edited by: Shubhadeep on Jun 27, 2009 2:01 AM
Edited by: Shubhadeep on Jun 27, 2009 2:06 AM
Edited by: Shubhadeep on Jun 27, 2009 2:12 AMWell, I think you need to add a custom renderer to the first column. The renderer would check if the table.isEditing(). If it is and the editing is done on the same row, then you set the font color blue, otherwise you use the default font color.
Then the next question is how do you repaint the cell. Well you can use the table.repaint(Rectangle) method. You can get the Rectangle to repaint by using the table.getCellRect(...) method.
Finally, you need to know when to repaint the cell. Well a PropertyChangeEvent is fired when a cell starts and stops editing. So you only need to handle these events. Don't use a KeyListener. The PropertyChangeListener you add to the table might be something like:
public void propertyChange(PropertyChangeEvent e)
if ("tableCellEditor".equals(e.getPropertyName()))
if (table.isEditing())
processEditingStarted();
else
processEditingStopped();
}So when editing is started you need to determine the "adjacent" cell you want to repaint to the blue font is used. You would save the cell Rectangle so you can restore the font when editing is stopped. -
Editable Combo box in a JTable
Hi,
Is it possible to have an editable combo Box in a JTable with an item Listener attached to the combo Box?
Based on whatever value the user enters in that column that is rendered as a combo Box(editable) i should be able to do some validation. Is this possible?
Thanks in advance for your time and patience.
ArchanaHere's a start:
public class FileModel5 extends AbstractTableModel
public boolean isEditable = false;
protected static int NUM_COLUMNS = 3;
// initialize number of rows to start out with ...
protected static int START_NUM_ROWS = 0;
protected int nextEmptyRow = 0;
protected int numRows = 0;
static final public String file = "File";
static final public String mailName = "Mail Id";
static final public String postName = "Post Office Id";
static final public String columnNames[] = {"File", "Mail Id", "Post Office Id"};
// List of data
protected Vector data = null;
public FileModel5()
data = new Vector();
public boolean isCellEditable(int rowIndex, int columnIndex)
// The 2nd & 3rd column or Value field is editable
if(isEditable)
if(columnIndex > 0)
return true;
return false;
* 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();
* Retrieves number of columns
public synchronized int getColumnCount()
return NUM_COLUMNS;
* Get a column name
public String getColumnName(int col)
return columnNames[col];
* Retrieves number of records
public synchronized int getRowCount()
if (numRows < START_NUM_ROWS)
return START_NUM_ROWS;
else
return numRows;
* Returns cell information of a record at location row,column
public synchronized Object getValueAt(int row, int column)
try
FileRecord5 p = (FileRecord5)data.elementAt(row);
switch (column)
case 0:
return (String)p.file;
case 1:
return (String)p.mailName;
case 2:
return (String)p.postName;
catch (Exception e)
return "";
public void setValueAt(Object aValue, int row, int column)
FileRecord5 arow = (FileRecord5)data.elementAt(row);
arow.setElementAt((String)aValue, column);
fireTableCellUpdated(row, column);
* Returns information of an entire record at location row
public synchronized FileRecord5 getRecordAt(int row) throws Exception
try
return (FileRecord5)data.elementAt(row);
catch (Exception e)
throw new Exception("Record not found");
* Used to add or update a record
* @param tableRecord
public synchronized void updateRecord(FileRecord5 tableRecord)
String file = tableRecord.file;
FileRecord5 p = null;
int index = -1;
boolean found = false;
boolean addedRow = false;
int i = 0;
while (!found && (i < nextEmptyRow))
p = (FileRecord5)data.elementAt(i);
if (p.file.equals(file))
found = true;
index = i;
} else
i++;
if (found)
{ //update
data.setElementAt(tableRecord, index);
else
if (numRows <= nextEmptyRow)
//add a row
numRows++;
addedRow = true;
index = nextEmptyRow;
data.addElement(tableRecord);
//Notify listeners that the data changed.
if (addedRow)
nextEmptyRow++;
fireTableRowsInserted(index, index);
else
fireTableRowsUpdated(index, index);
* Used to delete a record
public synchronized void deleteRecord(String file)
FileRecord5 p = null;
int index = -1;
boolean found = false;
int i = 0;
while (!found && (i < nextEmptyRow))
p = (FileRecord5)data.elementAt(i);
if (p.file.equals(file))
found = true;
index = i;
} else
i++;
if (found)
data.removeElementAt(i);
nextEmptyRow--;
numRows--;
fireTableRowsDeleted(START_NUM_ROWS, numRows);
* Clears all records
public synchronized void clear()
int oldNumRows = numRows;
numRows = START_NUM_ROWS;
data.removeAllElements();
nextEmptyRow = 0;
if (oldNumRows > START_NUM_ROWS)
fireTableRowsDeleted(START_NUM_ROWS, oldNumRows - 1);
fireTableRowsUpdated(0, START_NUM_ROWS - 1);
* Loads the values into the combo box within the table for mail id
public void setUpMailColumn(JTable mapTable, ArrayList mailList)
TableColumn col = mapTable.getColumnModel().getColumn(1);
javax.swing.JComboBox comboMail = new javax.swing.JComboBox();
int s = mailList.size();
for(int i=0; i<s; i++)
comboMail.addItem(mailList.get(i));
col.setCellEditor(new DefaultCellEditor(comboMail));
//Set up tool tips.
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for mail Id list");
col.setCellRenderer(renderer);
//Set up tool tip for the mailName column header.
TableCellRenderer headerRenderer = col.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer)
((DefaultTableCellRenderer)headerRenderer).setToolTipText(
"Click the Mail Id to see a list of choices");
* Loads the values into the combo box within the table for post office id
public void setUpPostColumn(JTable mapTable, ArrayList postList)
TableColumn col = mapTable.getColumnModel().getColumn(2);
javax.swing.JComboBox combo = new javax.swing.JComboBox();
int s = postList.size();
for(int i=0; i<s; i++)
combo.addItem(postList.get(i));
col.setCellEditor(new DefaultCellEditor(combo));
//Set up tool tips.
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for post office Id list");
col.setCellRenderer(renderer);
//Set up tool tip for the mailName column header.
TableCellRenderer headerRenderer = col.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer)
((DefaultTableCellRenderer)headerRenderer).setToolTipText(
"Click the Post Office Id to see a list of choices");
} -
In ALV Report ,a field to allow the user EDIT/CHANGE
Hi Guys,
My requirement is
in the ALV Grid display iam having 10 fields.5th field should be allow the user EDIT/CHANGE mode.
what ever he enters the value the same should be updated to an custom table.
EX.
o/p:
0001 0002 0003 0004 0005 0006 0007 0008 0009 0010
Now the user changed the value 0005 to 0011.
0001 0002 0003 0004 0011 0006 0007 0008 0009 0010
now 0011 should be updated in custom table.
to do this process please suggest a best way for coding.
thanks in advance.
Sunil.hi
*& Report ZTESTDEMO_INTERACTIVE_LIST_2
REPORT ZTESTDEMO_INTERACTIVE_LIST_2.
TABLES: MARA,MARC,MARD.
* internal table itab_mara 3 fields matnr, ernam,mtart
DATA: BEGIN OF ITAB_MARA OCCURS 0,
MATNR LIKE MARA-MATNR, " material number
ERNAM LIKE MARA-ERNAM, " name of person who create
MTART LIKE MARA-MTART, " Material Type
END OF ITAB_MARA.
* internal table itab_marc 3 fields matnr, werks,lvorm
DATA: BEGIN OF ITAB_MARC OCCURS 0,
MATNR LIKE MARC-MATNR,
WERKS LIKE MARC-WERKS, " Plant
LVORM LIKE MARC-LVORM, " Flag Material for Deletion at Plant Level
END OF ITAB_MARC.
* internal table itab_mard 2 fields
DATA: BEGIN OF ITAB_MARD OCCURS 0,
MATNR LIKE MARD-MATNR,
LGORT LIKE MARD-LGORT, " Storage Location
END OF ITAB_MARD.
SELECT-OPTIONS: S_MTART FOR MARA-MTART.
INITIALIZATION.
S_MTART-LOW = 'HALB'.
S_MTART-HIGH = 'HAWA'.
S_MTART-OPTION = 'BT'.
APPEND S_MTART.
START-OF-SELECTION.
SELECT MATNR ERNAM MTART FROM MARA INTO TABLE ITAB_MARA WHERE MTART IN
S_MTART.
PERFORM DISPLAY.
TOP-OF-PAGE.
WRITE:/2(15) 'MATERIAL NO',20(20) 'CREATED BY',45(15) 'MATERIAL TYPE'.
FORM DISPLAY.
LOOP AT ITAB_MARA.
WRITE:/ ITAB_MARA-MATNR UNDER 'MATERIAL NO' HOTSPOT ON,ITAB_MARA-ERNAM
UNDER 'CREATED BY',ITAB_MARA-MTART UNDER 'MATERIAL TYPE'.
HIDE: ITAB_MARA-MATNR.
ENDLOOP.
ENDFORM.
AT LINE-SELECTION.
CASE SY-LSIND.
WHEN 1.
SELECT MATNR WERKS LVORM FROM MARC INTO TABLE ITAB_MARC WHERE MATNR =
ITAB_MARA-MATNR.
PERFORM DISPLAY1.
WHEN 2.
SELECT MATNR LGORT FROM MARD INTO TABLE ITAB_MARD WHERE MATNR =
ITAB_MARC-MATNR.
PERFORM DISPLAY2.
when 3.
sy-lsind = 0.
ENDCASE.
FORM DISPLAY1.
LOOP AT ITAB_MARC.
WRITE:/ ITAB_MARC-MATNR HOTSPOT ON, ITAB_MARC-WERKS,ITAB_MARC-LVORM.
HIDE: ITAB_MARC-MATNR.
ENDLOOP.
WRITE:/ SY-LSIND.
ENDFORM.
FORM DISPLAY2.
LOOP AT ITAB_MARD.
WRITE:/ ITAB_MARD-MATNR, ITAB_MARD-LGORT.
ENDLOOP.
WRITE:/ SY-LSIND.
ENDFORM.
regards
ravish
<b>plz dont forget to reward points if helpful</b> -
How to get edited row values from ADF table?
JDev 11.
I have a table which is populated with data from Bean.
I need to save changes after user make changes in any table cell. InputText is defined for table column component.
I have defined ValueChangeListener for inputText field and AutoSubmit=true. So when user change value in inputText field, method is called:
public void SaveMaterial(ValueChangeEvent valueChangeEvent) {
getSelectedRow();
SaveMaterial(material);
This method should call getSelectedRow which take values from selected table row and save them into object:
private Row getSelectedRow(){
RichTable table = this.getMaterialTable();
Iterator selection = table.getSelectedRowKeys().iterator();
while (selection.hasNext())
Object key = selection.next();
table.setRowKey(key);
Object o = table.getRowData();
material = (MATERIAL) o;
System.out.println("Selected Material Desc = "+material.getEnumb());
return null;
Problem is that getSelectedRow method doesnt get new (edited) values, old values are still used.
I have tried to use ActiveButton with same method and it works fine in that case. New values are selected from active row and inserted into object.
JSF:
<af:table var="row" rowSelection="single" columnSelection="single"
value="#{ManageWO.material}" binding="#{ManageWO.materialTable}">
<af:column sortable="false" headerText="E-number">
<af:inputText value="#{row.enumb}" valueChangeListener="#{ManageWO.SaveMaterial}" autoSubmit="true"/>
</af:column>
<af:column sortable="false" headerText="Description">
<af:inputText value="#{row.desc}" valueChangeListener="#{ManageWO.SaveMaterial}" autoSubmit="true"/>
</af:column>
</af:table>
<af:activeCommandToolbarButton text="Save" action="#{ManageWO.EditData}"/>
What is a correct place from where save method should be called to get new (edited) values from ADF table?
Thanks.Did you look into the valueChangeEvent?
It has oldValue and newValue attributes.
public void SaveMaterial(ValueChangeEvent valueChangeEvent) {
Object oldVal = valueChangeEvent.getOldValue();
Object newVal = valueChangeEvent.getNewValue();
// check if you see what you are looking for.....
getSelectedRow();
SaveMaterial(material);
}Timo -
Getting change values from a collection
Title says it all. I have a collection connected to a
datagrid and have a simple form that allows me to add/modify/delete
entries from the collection. Now I want to send the changes to the
collection back to the server. How do I read/parse the collection
for these changes? Examples would be helpful. Below is what I have
so far to examine the collection (found elsewhere) how do I extract
the name/value pairs that have changed?
public function
collectionEventHandler(event:CollectionEvent):void {
switch(event.kind) {
case CollectionEventKind.ADD:
addLog("Item "+ event.location + " added");
break;
case CollectionEventKind.REMOVE:
addLog("Item "+ event.location + " removed");
break;
case CollectionEventKind.REPLACE:
addLog("Item "+ event.location + " Replaced");
break;
case CollectionEventKind.UPDATE:
addLog("Item updated");
break;
}ArrayCollection supports the length property, so you can
simply iterate over it with a for loop and use the bracket notation
to return each item. Build the structure you want to sent, then
away you go.
If you are wanting to only select changed values, you will
have to track this yourself.
Tracy -
How to capture changed value in ALV Grid
Hi Guys,
I have an ALV grid report where I have 'Edit On' for one of the quantity fields in the report. How do I capture the new (changed) value in the suboutine for user command when user changes the value in the report and clicks on a button ?
Points assured for helpful replies.FORM USER_COMMAND USING P_UCOMM LIKE SY-UCOMM...........
Data ref1 type ref to cl_gui_alv_grid.
CALL FUNCTION 'GET_GLOBALS_FROM_SLVC_FULLSCR'
IMPORTING
E_GRID = ref1.
call method ref1->check_changed_data
ENDFORM.
Also chk the blog
/people/community.user/blog/2007/01/10/displaychange-mode-of-editable-fields-in-alv-using-function-modules-but-not-custom-containers -
How to change value date from posting date to net due date
Hi Gurus,
My client wants to change value date from posting date to net due date. currently posting date is considered as value date but in future client wants to change value date to net due date of documents.
1. what configurations need to be maintained to change value date from posting date to net due date.
2. Will these changes effect automatic payment run.
Thanks and Regards,
SureshHi Suresh,
In Future
While posting the documents you can mention the value date as due date of the documents.
For already posted documents
You can change the value date to net due date.
If the value date is display mode i.e. if you are not able to change the value date in FB02 (Document Change Mode), use OB32 transaction and make value date field as eidtable (BSEG-VALUT).
In OB32 transaction enter all the required fields like Account type, transaction type, company code and finally activate the Field can be changed check box.
But not sure, whether we can change the value date to previous date or not?
This would help you..
Regards,
Praisty
Edited by: Praisty on Jul 28, 2009 9:56 AM -
How to force check right value of a JTable cell?
Hi,
I have a JTable with a column that must have a value no empty and between 0 and 100. I made a sample with only one column for simplicity.
The code works fine when the user types some value. However, when the user press ENTER to go to next column, without editing the cell, no checks run.
I have also other column that the user may type a part of a name and the system must find the full name of a person. In this column, if user uses ENTER without editing the cell, the same problem ocurrs.
The simplistic code is here, runnable:
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.text.NumberFormat;
import java.text.ParseException;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;
public class TableCheckCell extends JFrame {
/** Creates a new instance of TableCheckCell */
public TableCheckCell() {
Object[] columnNames = {"Percents"};
Object[][] data =
{new Integer(-1)}, // <--- DEFAULT VALUE FORCED TO BE OUT OF RANGE...
{new Integer(-1)},
{new Integer(-1)},
{new Integer(-1)}
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
TableColumn col = table.getColumnModel().getColumn(0);
col.setCellEditor(new CellIntegerEditor(CellIntegerEditor.CHECKMINMAX,0,100));
public static void main(String[] args) {
TableCheckCell frame = new TableCheckCell();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
* Implements a cell editor that uses a formatted text field
* to edit Integer values.
class CellIntegerEditor extends DefaultCellEditor {
public static final int NOCHECK = 0;
public static final int CHECKMINMAX = 1;
public static final int CHECKMIN = 2;
public static final int CHECKMAX = 3;
JFormattedTextField ftf;
NumberFormat integerFormat;
private int checkinterv;
private Integer minimum, maximum;
private boolean DEBUG = false;
public CellIntegerEditor(int checkinterv, int min, int max) {
super(new JFormattedTextField());
init(checkinterv, min, max);
void init(int checkinterv, int min, int max) {
ftf = (JFormattedTextField)getComponent();
this.checkinterv = checkinterv;
minimum = new Integer(min);
maximum = new Integer(max);
//Set up the editor for the integer cells.
integerFormat = NumberFormat.getIntegerInstance();
NumberFormatter intFormatter = new NumberFormatter(integerFormat);
intFormatter.setFormat(integerFormat);
if (checkinterv == CHECKMIN || checkinterv == CHECKMINMAX)
intFormatter.setMinimum(minimum);
if (checkinterv == CHECKMAX || checkinterv == CHECKMINMAX)
intFormatter.setMaximum(maximum);
ftf.setFormatterFactory(new DefaultFormatterFactory(intFormatter));
ftf.setValue(minimum);
ftf.setHorizontalAlignment(JTextField.TRAILING);
ftf.setFocusLostBehavior(JFormattedTextField.PERSIST);
//React when the user presses Enter while the editor is
//active. (Tab is handled as specified by
//JFormattedTextField's focusLostBehavior property.)
ftf.getInputMap().put(KeyStroke.getKeyStroke(
KeyEvent.VK_ENTER, 0),
"check");
ftf.getActionMap().put("check", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (!ftf.isEditValid()) { //The text is invalid.
if (userSaysRevert()) { //reverted
ftf.postActionEvent(); //inform the editor
} else try { //The text is valid,
ftf.commitEdit(); //so use it.
ftf.postActionEvent(); //stop editing
} catch (java.text.ParseException exc) { }
//Override to invoke setValue on the formatted text field.
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected,
int row, int column) {
JFormattedTextField ftf =
(JFormattedTextField)super.getTableCellEditorComponent(
table, value, isSelected, row, column);
ftf.setValue(value);
return ftf;
//Override to ensure that the value remains an Integer.
public Object getCellEditorValue() {
JFormattedTextField ftf = (JFormattedTextField)getComponent();
Object o = ftf.getValue();
if (o instanceof Integer) {
return o;
} else if (o instanceof Number) {
return new Integer(((Number)o).intValue());
} else {
if (DEBUG) {
System.out.println("getCellEditorValue: o isn't a Number");
try {
return integerFormat.parseObject(o.toString());
} catch (ParseException exc) {
System.err.println("getCellEditorValue: can't parse o: " + o);
return null;
//Override to check whether the edit is valid,
//setting the value if it is and complaining if
//it isn't. If it's OK for the editor to go
//away, we need to invoke the superclass's version
//of this method so that everything gets cleaned up.
public boolean stopCellEditing() {
JFormattedTextField ftf = (JFormattedTextField)getComponent();
if (ftf.isEditValid()) {
try {
ftf.commitEdit();
} catch (java.text.ParseException exc) { }
} else { //text is invalid
if (!userSaysRevert()) { //user wants to edit
return false; //don't let the editor go away
return super.stopCellEditing();
* Lets the user know that the text they entered is
* bad. Returns true if the user elects to revert to
* the last good value. Otherwise, returns false,
* indicating that the user wants to continue editing.
protected boolean userSaysRevert() {
Toolkit.getDefaultToolkit().beep();
ftf.selectAll();
Object[] options = {"Corrigir"};
String msg = "";
if (checkinterv == CHECKMINMAX)
msg = "Value must be between " + minimum + " and " + maximum + ".";
else if (checkinterv == CHECKMIN)
msg = "Value must be >= " + minimum + ".";
else if (checkinterv == CHECKMAX)
msg = "Value must be <= " + maximum + ".";
JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(ftf),msg);
ftf.setValue(ftf.getValue());
return true;
}Then, I'd like to know if there is any way to check the user typed ENTER to go out of the cell, check the value of the cell and, if it is wrong, to come back to the cell, forcing the user to type a right value.Editing to force the entry of data in a cell is typically done when you press a button to process the data. It doesn't make sense to "edit" the cell when the user presses enter to go to the next cell. What if the user never places focus on a particular cell. Then the cell will never be edited.
To force a user to enter a valid value once they have started editing you can do something like this:
http://forum.java.sun.com/thread.jspa?forumID=57&threadID=575309
But you can't force a user to visit every cell in the table so you need to handle that as described above. -
Help with editing a cell in a JTable. DESPERATE
Hi! Is there someone out there that could help with some source code for editing a cell in my JTable when I run it as an applet??
It works fine when I run it as an application.
I manage to select the row and write a number in it, but I can't get out of the cell (it seems that the program stops??). I want to enter an integer in a cell and when I click enter or with the mouse in an other cell the value that I enter should update some other cell( multiply the entered value with some fixed number and update a cell in a second coloumn)
I am really desperate now..... I have thought about using a MouseListener....
I am using a tablemodel that is from AbstractTableModel.Are you using some cell editors?
While converting inside them, you might be getting some exceptions (like parseexception)which is stopping you from proceeding further.
Are you using your own tablemodel with custom datatypes?
Hope this helps,
Ramkumar -
User should not be able to edit characteristics Value
Hi Friends
I have requirement where in a user creates a document with Two characteristics assigned to that Document.
Say CHAR1 and CHAR2.
When he creates DIR , He assigns value to these characteristics
CHAR1 = 666454
CHAR2 = 55333
No I want No other user to be able to change the values assigned to both CHAR1 and CHAR2.
Can this be possible.
With Regards
Mangesh PandeHi Mangesh,
I think the easiest way to find an authorization object which prevents users to edit characteristic values would be to made an authorization trace in transaction ST01. For further information please see the following link:
http://wiki.sdn.sap.com/wiki/display/PLM/AuthorizationTrace-+ST01
This trace lists all checked authorization objects and you should be able to identify a suitbale object for restricting edit permission for classification values.
Best regards,
Christoph -
Saving as SVG (w/out AI editability) changes artboard size ...why? ai saves the artboard dimensions as the frame, unless it decides to expand the frame to accommodate extraneous material. what is weird and disappointing is that ai does not read these frame values back in to recreate the artboard; you have to use preserve ai capability which attaches huge code. How to get it to retain the chosen artboard size? Thanks, Rich.
I have the same problem. When I save as AI and reopen it the graphics are crisp and align to the pixel grid. When I save as SVG and reopen it the graphics are no longer crisp and no longer align to the pixel grid. It looks like the artboard shifts .5 pixels right and down. That's just odd.
Here's the screenshots (sorry 144dpi).
AI File:
SVG file: (do you see the .5 pixel shift?)
This really concerned me because I am designing SVG's for the web - so they would look crisp on the pixel grid. I tested the SVG in html and it looked crisp on 72dpi and 144dpi displays. So the problem is only how Illustrator imports the SVG, which is very weird. Any thoughts why this happens?
Also, i'm using Illustrator CS6.
Maybe you are looking for
-
In the message thread, I can scroll all the way up to click on contact and see which number it is. I was hoping that there was a quicker way, like the contact name with the phone label displayed too.
-
How can i get this set up to work? PLEASE HELP
Ok so right now i have a airport express, and i bought a xbox 360. I want a wired connection for my xbox 360, so the guy at bestbuy said to buy a dlink EBR-2310 switch so i would still have a wireless connection for all the laptops, phone, etc in my
-
Looking fora camcorder that also has an s-video or rca jack input to convert my vhs tapes to digital
looking fora camcorder that also has an s-video or rca jack input to convert my vhs tapes to digital.
-
How do I stop camera raw automatically applying contrast and brightness when I load an image?
Everytime I load an image in photoshop or camera raw from bridge it automatically applies 50% brightness and 25% contrast and 5% black fill. It's ruining the pictures. I have already tried resetting photoshop and bridge to their default settings usin
-
Anyone have a problem submitting podcast to a personal domain with iWeb 08?
I created a new website with several podcasts and published fine to a personal domain. Works great. When I try to submit the podcasts to iTunes through iWeb I get the following error message: "We had difficulty reading this feed. Bad http result code