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.

Similar Messages

  • How to insert check box value in table?

    Hi all
    kindly help me how to insert check box value in database. what code i have to use as i am new in programing.
    thanx in advance

    Hi,
    There is no "Check box" in a table, a check box is a GUI (Graphical user interface) item.
    What you want is to store a boolean value in a table. For that you can use the varchar2(1) datatype and store Y or N. (or anything else)
    (you cannot define boolean as a datatype for a column).
    If you're using a front-end application like apex then it might be useful for you to read the documentation about chekc boxes :
    http://download.oracle.com/docs/cd/E10513_01/doc/appdev.310/e10497/check_box.htm#CHDDFBFH
    (for the rest if it's Oracle Forms then everything is already said).
    Edited by: user11268895 on Aug 17, 2010 10:44 AM

  • How to filter check box values in WAD.

    Hi Gurus,
    In my WAD i am having check box and the object name is defined as 0SEM_CGCOMP, it is a master data info object and having values like CG1,CG2,CG3....CG10. But i want to restrict the values to CG1,CG2,CG3,CG4 only. how can i filter the values?
    </object>
    </td>
              <td class="SAPBEXHLevel2"><object>
             <param name="OWNER" value="SAP_BW"/>
             <param name="CMD" value="GET_ITEM"/>
             <param name="NAME" value="CKBOX_CONS"/>
             <param name="ITEM_CLASS" value="CL_RSR_WWW_ITEM_FILTER_CHECBOX"/>
             <param name="DATA_PROVIDER" value="DP_1"/>
             <param name="GENERATE_CAPTION" value=""/>
             <param name="BORDER_STYLE" value="NO_BORDER"/>
             <param name="WIDTH" value="240"/>
             <param name="GENERATE_LINKS" value=""/>
             <param name="IOBJNM" value="0SEM_CGCOMP"/>
             <param name="SHOW_LABEL" value=""/>
             <param name="TARGET_DATA_PROVIDER_1" value="DP_1"/>
             <param name="HORIZONTAL_NUMBER" value="5"/>
             ITEM:            CKBOX_CONS
    </object></td>
    Thanks
    Raju.k

    Hi Raju,
    Try this.  Create another dataprovider within your web template?  This new dataprovider refers to a similar query, but this query definition should restrict values CG1, CG2, CG3 and CG4.  Assign this dataprovider to your checkbox.  Then make sure the properties of the checkbox affect all other dataproviders.
    Also, if this list is static, you could create an HTML checkbox object coding the options (cg1, cg2, cg3, and cg4) programmatically.  Then add javascript code to produce the proper filtering based on the users' selections.
    Let me know what happens.
    Larry

  • How to know the right value for SHMMAX and SHMALL for ia64 memory 32Gb

    Dear all,
    I want to install Oracle database 10g R2 on RHEL 5 ia64.
    Here the server specification :
    Proc : itanium64 ( montecito )
    Mem : 32Gb
    # getconf PAGE_SIZE = 16384
    Metalink says, that SHMMAX should be half of physical memory and SHMALL = SHMMAX / PAGE_SIZE.
    kernel.shmmax = 17179869184
    kernel.shmall = 1048576
    My Question is this is right value for SHMMAX and SHMALL on my server..??
    Thank you

    if shmmax is half the ram then what should be sga
    sga size should anyhow should be less then shmmax ,means we cannot increase sga size more than half the ram
    then how ROT for SGA that should be 70% of RAM hold good

  • How can I check stock value per valuation class at a certain period

    Hi,
    I have done this several times but with material ledger, but if I don't have material ledger available, how can I check the total stock value per valuation class for example at a certain period, lets say december 2012?
    I have check menu reports, and also the historical tables, but is there any standard to use?
    Thank you,

    HI,
    Please check transaction
    S_P00_07000140
    S_P00_07000139

  • How 2 assgin a character value to the auxillary cell

    Hi,
         I'm assigning a character value to the auxiliary cell in the macro. But it gives me a dump. So do let me know can I assign a character value to the auxiliary cell ( I need to display this value for the alert text).
    Thanks,
    Siva.

    Why are you trying to use a character in the planning book - why not a representative value in numbers
    but if you HAVE to use characteristic then you can also try to use the notes functionality (right click on a cell and go to notes if you have not seen this )
    These notes are usually anchored to a cell. These notes are stored in a table (check in se 16 with wildcard on notes ) and is associated to the value of a cell
    So if you can reference a cell value and put in the conditons to the values on it you might be able to manipulate the values in the table for notes and this will cause the notes in the interactive planning boo to change accoring to the value of the cell

  • How can I change the value in a stepper cell

    In Numbers 2.3 I was able to change the value in a stepper cell by highlighting the value and using the arrow keys to increase or decrease the value. This was a very easy way to input data. Numbers 3.0 when I do this is moves to another cell
    Is there a way to get the use of the arrow keys to change the values in 3.0?
    Thanks

    I use number to keep a running daily tally of the productivity of the members of my group. As each member performs certain tasks, all I had to do was click the up arrow and add to it. IE Jim made 4 widgets yesterday and then made 4 today, I would just hit the up 4 times total 8.
    I guess the good news is when I upgraded to Numbers 3.0, It did not delete Numbers 2.3
    I will continue to use 2.3 until it no longer works, I guess
    Thanks for the replies

  • How to create 2 checkboxs in 2 different JTable cells within 1 buttonGroup?

    Hi,
    I have a JTable with dynamic number of rows and 5 columns. What I mean by dynamic is that new rows can be added and existing rows can be deleted so the number of rows may change. As I said before there are 5 columns. The first 3 columns will always contains Strings. The fourth and fifth column will have checkboxs. I'm creating the checkboxes be specifying that the forth and fifth columns will have boolean in them. As you all know JTable converts boolean values to checkboxes.
    Here is my problem:
    I want to add these 2 checkboxes in column 4 and column 5 to a buttonGroup, s� that if I check the checkbox in column 4 the checkbox in column 5 will be unchecked and vice versa. An importent thing is that every row has its own buttonGroup for its checkboxes.
    To use buttonGroup I have to have 2 checkboxes to add them to the group for example
    buttonGroupForRow1.add(checkBox1);
    buttonGroupForRow2.add(checkBox2);
    But in my case there are no specific checkBoxes to add, I only have boolean values in 2 different cells in the JTable.
    How can I solve the problem?
    Here is a part of the code to help you undersand my problem:
    JTableToggle getPrgMemberPopupTable() {
              if (prgMemberPopupTable == null) {
                   DefaultTableModel model = new MyTableModel(10,5);
                   prgMemberPopupTable = new JTableToggle(model) {
                        public boolean isCellEditable(int rowIndex, int vColIndex) {
                             if (vColIndex == 3 || vColIndex == 4)
                             return true;
                             else return false;
                   prgMemberPopupTable.setRowSelectionAllowed(false);
                   prgMemberPopupTable.setColumnSelectionAllowed(false);
                   prgMemberPopupTable.getColumnModel().getColumn(0).setHeaderValue("Name");
                   prgMemberPopupTable.getColumnModel().getColumn(1).setHeaderValue("Subrack");
                   prgMemberPopupTable.getColumnModel().getColumn(2).setHeaderValue("Slot");
                   prgMemberPopupTable.getColumnModel().getColumn(3).setHeaderValue("Active");
                   prgMemberPopupTable.getColumnModel().getColumn(4).setHeaderValue("Passive");
                   prgMemberPopupTable.setName("prgMemberPopupTable");
                   prgMemberPopupTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
                   prgMemberPopupTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              return prgMemberPopupTable;
        class JTableToggle extends javax.swing.JTable {
            public JTableToggle(DefaultTableModel aDefaultTableModel){
                super(aDefaultTableModel);
            public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
                // toggle is true in the case where the control key is pressed, i will invert that case.
                toggle = !toggle;
                super.changeSelection(rowIndex,columnIndex,toggle,extend);
         class MyTableModel extends DefaultTableModel{
              public MyTableModel(int a, int b){
                   super(a, b);
              public Class getColumnClass(int index){
                   if (index == 3 || index == 4)
                        return Boolean.class;
                   return super.getColumnClass(index);
         }Grateful for all help
    //Roomi

    Thanks for your help.
    2 requirements has to be fulfiled here:
    Req.1. A member is selected. The memeber is selected either by checking Active or Passive checkbox
    Req.2. Every selected member is either Active or Passive.
    My solution is build on the ide that when you check the active checkbox, then that member is selected and its is an active member. If the passive checkbox is selected then it is a passive member.
    The thing is, not every member in the JTable is selected, only those who are relative to that specfic case are selected.
    Let's say that I have 10 members in my table (which means 10 rows). Then I can select for example the second and fifth members as an active members and the seventh member as a passive one. That means only those members are selected (Req.1.). And (2 and 5) are actives and (7) is passive (Req.2)
    But lets say that I change my mind, and decide that the seventh member should be active and not passive. Then when I modify the selection and check the active checkBox (on column 3) the passive checkBox (on column 4) should become unchecked.
    Camickr, with your suggestion I can not distinguish between if the member is passive or it is not selected at all.
    Even if I use JRadioButtons instead of JCheckBoxes the problems still the same, 2 different JRadioButtons (or JCheckBoxs), both of them are in seperate columns (seperate cells), how can I add them to one ButtonGroup? Or let me refrase the last sentence (question), How can build up the solution so that when one of them is selected the other one is unselected. If I don't use ButtonGroup and have to build my own buttonGroup then I have to start thinking about mouse listner, and where the mouse click to plase, ...etc which is a lot of work for a simble thing to do.
    Unfortuntly I cannot change the layout either, I'm stricted to this layout by the company.
    //Roomi

  • How to display cusomized custom tooltip(jwindow)  in jtable cell position

    Hi,
    i am trying to display custom tooltip for jtable cell. i created custom tooltip(jwindow) and on mouseover of jtable cell i am trying to display the custom tooltip.
    But it is not display the position of jtable cell. How to display the exact position of jtable cell
    please help me on this.

    Did you read the posting directly below yours which was also about a custom tool tip?
    JScrollableToolTip is buggy
    The code presented there shows the tool tip in the proper location.
    For more help create a [url http://sscce.org]SSCCE, that demonstrates the incorrect behaviour.
    Don't forget to read the "Welcome to the new home" posting at the start of the forum to learn how to use the "code tags" so posted code is formatted and readable.

  • How to automatically highlight / bold words in a JTable cell?

    how do i do it?
    i have an Object called Data (where toString() is the same as getDataName()).
    and i want the JTable to either highlight or bold specific words (using the bold HTML tags) that are present in a SortedSet.
    i do not want the dataName to be changed by directly manipulating the Object because the Data Objects were taken from the DB and i need the Objects and the records to be synchronised, and because the words in the SortedSet itself are subject to changes (add/edit/remove).
    thanks.

    Edit: removed
    db
    Cross posted
    http://www.java-forums.org/awt-swing/47138-how-automatically-highlight-bold-words-jtable-cell.html
    Edited by: Darryl Burke

  • How to force checked out CSV Files to open in Excel and not in Notepad

    Hi,
    I'm looking for some pointers / direction.
    .CSV files on SharePoint 2010 document library opens up in notepad by default. I did the DocIcon.xml CSV entry, changed the MIME type in IIS and did the IIS reset. Also on client computer CSV file is associated with MS Excel 2013. Now clicking a CSV file
    opens it up in MS Excel.
    Now a user checks out a CSV file and the same user clicks on the CSV file, the file is opening in notepad! If other users clicks on the same checked out file (checked out by the first user) it opens up in Excel for them. I've tried the 'Edit in Microsoft
    Excel' from the pop up menu but with same result.
    How can I force a checked out CSV file to open in MS Excel?
    Thanks

    1. Highlight one of the images and press cmd+i (or right click and select "Get info")
    2. Click the dropdown menu and select Photoshop (you might have to click "Other..." to find it.
    3. Then click "Change All" button below.
    You're going to have to do this with every different TYPE of image (e.g. jpeg, tiff etc) but once you've covered all the types you won't have the problem again.
    Hope this helps!

  • How to force checking uniqueness in datablock?

    Hi all,
    How do you force Form 6i to check uniqueness of the records in datablock. I want Form to be able to check uniqueness in datablock AS users type in the data NOT when users commit the data.
    For example: I want form to be able to fires warning when users type an identical data in 2 records just when (before) the users begin to key in the third records.
    Thanks in advance for your help.

    Hi there,
    Thanks for your response. Using item primary key property will only check the uniqness when I commit the form. By then it will be to late.
    My situation is that I have a primary key that some part of it has today's date. The first 6 number will be unique for each day. For example:
    123456-0505 (05-MAY)
    123457-0505 (05-MAY)
    123456-0605 (06-MAY)
    In order to save data entry time I hardcode the date part so that user only have to enter the first 6 number in the primary key. I create a non-database item (eg. ND_item) in the datablock that the user use to enter 6 number part and I do not show the real primary key item (PK_item). Then I use pre-insert trigger in the datablock to add the date part as:
    :PK_item := ND_item || to_char(date...);
    The problem with this method is that when the user commit but there is a violation of primary key, the user will get FRM-40600 Records has been inserted. I could not just change the value in the ND-item because form still give FRM-40600 after I change it. The only way to fix this is that user has to cancel the operation, rollback and retype all the data. Each data entry will have 20-50 records so it will be time consuming to retype the data.
    That is why I ask for a code that will use form to check uniqness as the user move to next records. Or can anyone give me advice on what is the best way to handle this situation.
    Thanks in advance for your help.

  • How to Insert check box value into database column

    Hi All,
    I had checkbox group in a region which is using an LOV......and having 18 items in that lov.
    i.e. Total 18 checkboxes in Total. User has to select only 2 checkboxes from that 18.
    I created two columns for storing two values of checkboxes. How to insert two selectives in two columns.........Moreover, How to give the query i.e. how to know which values are selected.
    Please Help me in achieving this. apart from the two columns (Focus1,Focus2) .......One more column(l_spo_val) is there which is a foreign key.
    My Insert Statement is like this:
    INSERT INTO SPO_RESEARCH_FOCUS VALUES(l_spo_val
    ,:P4_RESEARCH_LIST_1
                        ,:P4_RESEARCH_LIST_2);
    Please narrate the code if possible.
    Thanks,
    Sekhar.

    Hi Denes,
    I saw the example in your workspace and it is the same what exactly i want and instead of storing in one column i want to store the two selected values into two different columns. Also i need to restrict the selection of checkboxes upto 2 only. So If the user tries to select the third check box it doesnt have to accept.
    Even I am ready to change my table as according to your example i.e. creating only one column. Store the values of selection into that column.
    I was unable to see how u wrote the logic (Code) for your example in your workspace. It helps alot if you provide me the code for that example(Multi Checkbox One Column).
    I was facinated after watching your examples in your workspace and am very much interested to know more about Apex.
    Please help me insolving this as it is long pending issue for my requirement.
    Thanks a lot again,
    Sekhar.
    Edited by: Sekhar Nooney on Mar 26, 2009 4:35 AM

  • How can I check the values of a textbox, if the vaule is numeric?

    Hello,
    I have a (maybe simple?) problem:
    I'm using a Webform with a input-field. With JSP I want do check, if the value of this textbox is numeric.
    In Visual Basic there exists the method IsNumeric(). But I don't know how to check it with Java/JSP?
    What classes/methods have I to use ?
    Bye
    Chris

    If you don't want to work with the exceptions then, you could just check if all the digits are numbers or a decimal point, but then you may need exponents or comma's for seperation too.

  • How to retain check box value

    Hi All,
    In my application there are using a check box item..what they have done is under
    source used: Alaways,replcaing existing value in session state.
    Source type: sql query
    Now the problem is when ever they is a record in backend it is not showing selected in check list..
    But when i have tried to change Source used from Alawys to Only when then in that case i am able to see tick mark under that check box..
    But when no data exists even though the tick mark still exists...
    How do we handle such scenerio's..
    Thanks,
    Anoo..

    we don't even know the context you're in, you must give more informations about what you exactly want to do
    if you're using java servlets, it goes like that:
    first page (servlet) must contain:
    <form action=nextPage.html method=get>
    <input type=checkbox name=toto>
    </form>
    second page (servlet) must contain:
    req.getParameter("toto");
    (req being the HttpServletRequest of the first servlet)
    that will give you the state of the box
    Message was edited by:
    calvino_ind

Maybe you are looking for