Programmatically selecting a cell in a two-dimensional JTable

The problem is that when a person edits a cell and the value fails validation, I would like to programmatically select the cell. The validation is done in the setValueAt method of a Class extending the AbstractTableModel. By simply returning out of that method, the cell value is set back to the way it was before the user changed it. In addition, I would like the problem cell to be automatically selected rather than requiring the user to click in it to select it. The first question is 1- Is this possible, and 2- Any clues as to how to select it?
We find for examle in Chapter 6 of the CoreJava 2 Vol II Advanced features statements like this on page 399 of, I think, Edition 4, (can anyone tell what edition it is?) by Cay Horstmann
void setCellSelectionEnabled(boolean b)
If b is true, then individual cells are selected (when the user clicks in the cell?). I have researched this problem for several days and don't have a clue how to automatically select the cell although I know precisely what row and column it is.

This is the code to return the focus to error cell.
/* TableCellValidator class */
/* The class basically validates the input entry in a cell and */
/* pops up a JOptionPane if its an invalid input */
/* And an OK is clicked on the JOptionPane, the control returns back */
/* to the same cell */
/* Basic Idea: The controls Arrow/Tab/mouse clicks are handled by our */
/* ----------- custom table. Its has been slightly tricky to handle */
/* mouse clicks, since when you click the next cell, the */
/* editingrow/editingcol advances. Hence the */
/* previousrow/previouscol has been captured in the */
/* setValueAt method. */
/* To capture Table/Arrow/Numeric Arrow, The keyStrokes(TAB etc)*/
/* assigned different AbstractionActions to execute like */
/* validateBeforeTabbingToNextCell */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableCellValidator {
* Constructor.
* Basically instantiates the class and sets up the
* JFrame object and the table.
public TableCellValidator() {
JFrame f = new JFrame("JTable test");
f.getContentPane().add(new JScrollPane(createTable()), "Center");
f.pack();
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
* A method which created our custom table.
* The JTable methods processMouseEvent
* and setValueAt are overridden to handle
* Mouseclicks.
* The Tables ActionMap is fed with different
* AbstractAction classes eg: (validateBeforeTabbingToNextCell)
* (Scroll down below for the innerclass
* validateBeforeTabbingToNextCell).
* So basically when TAB is pressed the stuff present
* in the validateBeforeTabbingToNextCell's actionPerformed(..)
* method is performed.
* So we need to handle all the stuff a TAB does.
* ie. if a TAB hits the end of the row, we need to increment
* it to the next Row (if the validation is successful)
* in the current row etc..
* @return JTable
* @see validateBeforeTabbingToNextCell
* @see validateBeforeShiftTabbingToNextCell
* @see validateBeforeMovingToNextCell
* @see validateBeforeMovingDownToCell
* @see validateBeforeMovingUpToCell
* @see validateBeforeMovingLeftToCell
private JTable createTable() {
JTable table = new JTable(createModel()){
private int previousRow =0;
private int previousCol =0;
* Processes mouse events occurring on this component by
* dispatching them to any registered
* <code>MouseListener</code> objects.
* <p>
* This method is not called unless mouse events are
* enabled for this component. Mouse events are enabled
* when one of the following occurs:
* <p><ul>
* <li>A <code>MouseListener</code> object is registered
* via <code>addMouseListener</code>.
* </ul>
* <p>Note that if the event parameter is <code>null</code>
* the behavior is unspecified and may result in an
* exception.
* @param e the mouse event
* @see java.awt.event.MouseEvent
* @see java.awt.event.MouseListener
* @see #addMouseListener
* @see #enableEvents
* @since JDK1.1
protected void processMouseEvent(MouseEvent e) {
boolean canMoveFocus = true;
int currentRowAndColumn[] = getCurrentRowAndColumn(this); //we pull the current row and column
int row = currentRowAndColumn[0];
int column = currentRowAndColumn[1];
if ( e.getID() == MouseEvent.MOUSE_PRESSED || e.getID() == MouseEvent.MOUSE_CLICKED) {
stopCurrentCellBeingEdited(this); //stop the cellbeing edited to grab its value
final String value = (String)getModel().getValueAt(row,column);
try {
Integer.parseInt(value);
} catch (NumberFormatException nfe) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JOptionPane.showMessageDialog(null,"Alpha value ="+ value ,"Invalid entry!",JOptionPane.WARNING_MESSAGE);
changeSelection(previousRow,previousCol, true, true);
editCellAt(previousRow, previousCol);
requestFocus(); // or t.getEditorCompo
if ( canMoveFocus ) {
super.processMouseEvent(e);
* The method setValueAt of the JTable is overridden
* to save the previousRow/previousCol to enable us to
* get back to the error cell when a Mouse is clicked.
* This is circumvent the problem, when a mouse is clicked in
* a different cell, the control goes to that cell and
* when you ask for getEditingRow , it returns the row that
* the current mouse click occurred. But we need a way
* to stop at the previous cell(ie. the cell that we were editing
* before the mouse click occurred) when an invalid data has
* been entered and return the focus to that cell
* @param aValue
* @param row
* @param col
public void setValueAt(Object aValue,int row, int col) {     
this.previousRow = row;
this.previousCol = col;
super.setValueAt(aValue,row,col);
/* These are the various KeyStrokes like
ENTER,SHIFT-TAB,TAB,Arrow Keys,Numeric Arrow keys being assigned an Abstract action (key string ) in to the
inputMap first . Then an Action is assigned in the ActionMap object
table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0) ,"validateBeforeTabbingToNextCell");
table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,1) ,"validateBeforeShiftTabbingToNextCell");
table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0) ,"validateBeforeMovingToNextCell");
table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_RIGHT,0) ,"validateBeforeMovingToNextCell");
table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,0) ,"validateBeforeMovingDownToCell");
table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_DOWN,0) ,"validateBeforeMovingDownToCell");
table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0) ,"validateBeforeMovingDownToCell");
table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP,0) ,"validateBeforeMovingUpToCell");
table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_UP,0) ,"validateBeforeMovingUpToCell");
table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0) ,"validateBeforeMovingLeftToCell");
table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_LEFT,0) ,"validateBeforeMovingLeftToCell");
table.getActionMap().put("validateBeforeTabbingToNextCell",
new validateBeforeTabbingToNextCell());
table.getActionMap().put("validateBeforeShiftTabbingToNextCell",
new validateBeforeShiftTabbingToNextCell());
table.getActionMap().put("validateBeforeMovingToNextCell",
new validateBeforeMovingToNextCell());
table.getActionMap().put("validateBeforeMovingDownToCell",
new validateBeforeMovingDownToCell());
table.getActionMap().put("validateBeforeMovingUpToCell",
new validateBeforeMovingUpToCell());
table.getActionMap().put("validateBeforeMovingLeftToCell",
new validateBeforeMovingLeftToCell());
table.setPreferredScrollableViewportSize(table.getPreferredSize());
return table;
* A table model is created here for 5 rows/5 columns.
* And the isCellEditable is overridden to return true,
* indicating that the cell can be edited.
* So fine tuned control can be done here by saying,
* the user can be allowed to edit Row 1,3 or 5 only.
* or column 1 only etc..
* @return DefaultTableModel
private DefaultTableModel createModel() {
DefaultTableModel model = new DefaultTableModel(5, 5) {
public boolean isCellEditable(int row, int column) {
return true;
return model;
* This method basically returns the currentRow/currentCol value
* If the current Row/Col is being edited then
* it returns the getEditingRow/getEditingColumn
* If its not being edited,
* it return the getAnchorSelectionIndex of the JTables
* ListSelectionModel.
* If the column or row is -1, then it return 0.
* The first element in the int[] array is the row
* The second element in the int[] array is the column
* @param t input a JTable
* @return int[]
* @see ListSelectionModel
* @see JTable
private int[] getCurrentRowAndColumn(JTable t){
int[] currentRowAndColum = new int[2];
int row, column;
if (t.isEditing()) {
row = t.getEditingRow();
column = t.getEditingColumn();
} else {
row = t.getSelectionModel().getAnchorSelectionIndex();
if (row == -1) {
if (t.getRowCount() == 0) {
//actually this should never happen.. we need to return an exception
return null;
column =t.getColumnModel().getSelectionModel().getAnchorSelectionIndex();
if (column == -1) {
if (t.getColumnCount() == 0) {
//actually this should never happen.. we need to return an exception
return null;
column = 0;
currentRowAndColum[0]=row;
currentRowAndColum[1]=column;
return currentRowAndColum;
* Tbis basically a wrapper method for CellEditors,
* stopCellEditing method.
* We need to do this because,
* for instance we have entered a value in Cell[0,0] as 3
* and when we press TAB or mouse click or any other relevant
* navigation keys,
* ** IF the cell is BEING EDITED,
* when we do a getValueAt(cellrow,cellcol) at the TableModel
* level , it would return "null". To overcome this problem,
* we tell the cellEditor to stop what its doing. and then
* when you do a getValueAt[cellrow,cellcol] it would
* return us the current cells value
* @param t Input a JTable
* @see CellEditor
private void stopCurrentCellBeingEdited(JTable t){
CellEditor ce = t.getCellEditor(); /*this not the ideal way to do..
since there is no way the CellEditor could be null.
But a nullpointer arises when trying to work with mouse.. rather than just
keyboard" */
if (ce!=null) {
ce.stopCellEditing();
* The following Action class handles when a
* RIGHT ARROW or NUMERIC RIGHT ARROW is pressed.
* There just a basic checking for Numeric values
* (Integer.parseInt) inside the code.
* When validation is successfull, we need to move it to the
* next Cell.. else take it back to the currentCell
class validateBeforeMovingToNextCell extends AbstractAction {
* The following Action class handles when a
* DOWN ARROW or NUMERIC DOWN ARROW is pressed.
* There is just a basic checking for Numeric values
* (Integer.parseInt) inside the code.
* When validation is successfull, we need to move it to
* down by one Cell.. else take it back to the currentCell
* @param e
public void actionPerformed(ActionEvent e) {
JTable t = (JTable) e.getSource();
int currentRowAndColumn[] = getCurrentRowAndColumn(t);
int row = currentRowAndColumn[0];
int column = currentRowAndColumn[1];
stopCurrentCellBeingEdited(t);
String value = (String)t.getModel().getValueAt(row,column);
if (value!= null && !value.equals("")) {
try {
Integer.parseInt(value);
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
t.changeSelection(row, column, true, true);
t.editCellAt(row,column);
t.getEditorComponent().requestFocus();
return;
column++;
if (column >= t.getColumnCount())
column = column-1;
if (t.isCellEditable(row, column)) {
t.changeSelection(row, column, true, true);
t.editCellAt(row, column);
if ((t.getEditingRow() == row)
&& (t.getEditingColumn() == column)) {
t.requestFocus();
return;
* The following Action class handles when a
* DOWN ARROW or NUMERIC DOWN ARROW is pressed.
* There just a basic checking for Numeric values
* (Integer.parseInt) inside the code.
* When validation is successfull, we need to move it to the
* down by Cell.. else take it back to the currentCell
class validateBeforeMovingDownToCell extends AbstractAction {
public void actionPerformed(ActionEvent e) {
JTable t = (JTable) e.getSource();
int currentRowAndColumn[] = getCurrentRowAndColumn(t);
int row = currentRowAndColumn[0];
int column = currentRowAndColumn[1];
stopCurrentCellBeingEdited(t);
String value = (String)t.getModel().getValueAt(row,column);
if (value!= null && !value.equals("")) {
try {
Integer.parseInt(value);
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
t.changeSelection(row, column, true, true);
t.editCellAt(row,column);
t.getEditorComponent().requestFocus();
return;
row++;
if (row >= t.getRowCount())
row = row - 1;
if (t.isCellEditable(row, column)) {
t.changeSelection(row, column, true, true);
t.editCellAt(row, column);
if ((t.getEditingRow() == row)
&& (t.getEditingColumn() == column)) {
t.requestFocus();
return;
* The following Action class handles when a
* UP ARROW or NUMERIC UP ARROW is pressed.
* There just a basic checking for Numeric values
* (Integer.parseInt) inside the code.
* When validation is successfull, we need to move the cursor/
* editable status up by a Cell.. else take it back to the currentCell
class validateBeforeMovingUpToCell extends AbstractAction {
public void actionPerformed(ActionEvent e) {
JTable t = (JTable) e.getSource();
int currentRowAndColumn[] = getCurrentRowAndColumn(t);
int row = currentRowAndColumn[0];
int column = currentRowAndColumn[1];
stopCurrentCellBeingEdited(t);
String value = (String)t.getModel().getValueAt(row,column);
if (value!= null && !value.equals("")) {
try {
Integer.parseInt(value);
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
t.changeSelection(row, column, true, true);
t.editCellAt(row,column);
t.getEditorComponent().requestFocus();
return;
row--;
if (row <0)
row = 0;
if (t.isCellEditable(row, column)) {
t.changeSelection(row, column, true, true);
t.editCellAt(row, column);
if ((t.getEditingRow() == row)
&& (t.getEditingColumn() == column)) {
t.requestFocus();
return;
* The following Action class handles when a
* LEFT ARROW or NUMERIC LEFT ARROW is pressed.
* There just a basic checking for Numeric values
* (Integer.parseInt) inside the code.
* When validation is successfull, we need to move the cursor/
* editable status up by a Cell.. else take it back to the currentCell
class validateBeforeMovingLeftToCell extends AbstractAction {
public void actionPerformed(ActionEvent e) {
JTable t = (JTable) e.getSource();
int currentRowAndColumn[] = getCurrentRowAndColumn(t);
int row = currentRowAndColumn[0];
int column = currentRowAndColumn[1];
stopCurrentCellBeingEdited(t);
String value = (String)t.getModel().getValueAt(row,column);
if (value!= null && !value.equals("")) {
try {
Integer.parseInt(value);
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
t.changeSelection(row, column, true, true);
t.editCellAt(row,column);
t.getEditorComponent().requestFocus();
return;
column--;
if (column <0)
column = 0;
if (t.isCellEditable(row, column)) {
t.changeSelection(row, column, true, true);
t.editCellAt(row, column);
if ((t.getEditingRow() == row)
&& (t.getEditingColumn() == column)) {
t.requestFocus();
return;
* The following Action class handles when a TAB is pressed.
* There just a basic checking for Numeric values
* (Integer.parseInt) inside the code.
* When validation is successfull, we need to move the cursor/
* editable status up by a Cell.. else take it back to the currentCell
class validateBeforeTabbingToNextCell extends AbstractAction {
public void actionPerformed(ActionEvent e) {
JTable t = (JTable) e.getSource();
int currentRowAndColumn[] = getCurrentRowAndColumn(t);
int row = currentRowAndColumn[0];
int column = currentRowAndColumn[1];
stopCurrentCellBeingEdited(t);
String value = (String)t.getModel().getValueAt(row,column);
if (value!= null && !value.equals("")) {
try {
Integer.parseInt(value);
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
t.changeSelection(row, column, true, true);
t.editCellAt(row,column);
t.getEditorComponent().requestFocus();
return;
column++;
int rows = t.getRowCount(), columns = t.getColumnCount();
while (row < rows) {
while (column < columns) {
if (t.isCellEditable(row, column)) {
t.changeSelection(row, column, true, true);
t.editCellAt(row, column);
if ((t.getEditingRow() == row)
&& (t.getEditingColumn() == column)) {
t.requestFocus();
return;
column++;
row++;
column = 0;
row = 0;
if (t.isCellEditable(row, column)) {
t.changeSelection(row, column, true, true);
t.editCellAt(row, column);
if ((t.getEditingRow() == row)
&& (t.getEditingColumn() == column)) {
t.requestFocus();
return;
* The following Action class handles when a SHIFT TAB is pressed.
* There just a basic checking for Numeric values
* (Integer.parseInt) inside the code.
* When validation is successfull, we need to move the cursor/
* editable status up by a Cell.. else take it back to the currentCell
class validateBeforeShiftTabbingToNextCell extends AbstractAction {
public void actionPerformed(ActionEvent e) {
JTable t = (JTable) e.getSource();
int currentRowAndColumn[] = getCurrentRowAndColumn(t);
int row = currentRowAndColumn[0];
int column = currentRowAndColumn[1];
stopCurrentCellBeingEdited(t);
String value = (String)t.getModel().getValueAt(row,column);
if (value!= null && !value.equals("")) {
try {
Integer.parseInt(value);
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
t.changeSelection(row, column, true, true);
t.editCellAt(row,column);
t.getEditorComponent().requestFocus();
return;
column--;
int rows = t.getRowCount(), columns = t.getColumnCount();
while ((row < rows) && (row >= 0)) {
while ((column < columns) && (column >= 0)) {
if (t.isCellEditable(row, column)) {
t.changeSelection(row, column, true, true);
t.editCellAt(row, column);
if ((t.getEditingRow() == row)
&& (t.getEditingColumn() == column)) {
t.requestFocus();
return;
column--;
row--;
column = columns - 1;
row = rows - 1;
if (t.isCellEditable(row, column)) {
t.changeSelection(row, column, true, true);
t.editCellAt(row, column);
if ((t.getEditingRow() == row)
&& (t.getEditingColumn() == column)) {
t.requestFocus();
return;
public static void main(String[] args) {
new TableCellValidator();

Similar Messages

  • JTable - Programmatically selection multiple cells

    Hi!
    I'd like to know wether it's possible to programmatically select certain cells of a Jtable component.
    For example:
    My Jtable looks like that
    1 2 3
    4 5 6
    7 8 9
    and I want to select cell 2,4 and 7. How could I do that??
    Thanks for answers...

    Hello,
    I consciously read your thread, but I still can't get the sample code running.
    (java.lang.StackOverflowError
    Exception in thread "main" )
    Would you please give me a hint?
    Or better,
    send or post me the sample code of your class 'AttributiveCellTableModel', please.
    Thank you very much in advance!
    Thorsten

  • Programmatically select a cell on pivotTable

    Hi,
    I have a case where on initial load of a page that contains a pivot table with dates as columns, on the first row, the current day cell should be selected .
    Pivottable has a selection property accepting oracle.adf.view.faces.bi.component.pivotTable.Selection but I can’t find how to instantiate and set a proper Selection object.
    There are many examples for how to handle similar scenario using table component but nothing for pivot and the documentation is very limited.
    Any help for achieving the desired functionality would be very appreciated.
    Yiannis

    Any help ?

  • Two dimensional Grouping

    Hi 2 all,
    I'm trying to build a report starting from two complex PL/SQL query like this(simplified):
    SELECT SUM(x),SUM(y),SUM(z),Name,type,product
    FROM DESC A, STORE1 B, STORE2 C, store3 D, store4 E
    WHERE b.ID=c.ID(+)
    AND b.ID=d.ID(+)
    AND b.ID=e.ID(+)
    AND a.code=b.code
    AND a.product='oneproduct'(...another query with !='oneproduct')
    group by b.Name,b.type
    I need to have on each report page the results of the two queries grouped by type, one page for each (Name).
    how can I have the content of Name field on the header/margin (as a title) and the remainder data below grouped by the same Name?
    =&gt; In the end I should have one page for each Name
    thanks
    Matteo

    On the other hand I do recall having read somewhere
    that the "new" operator
    is very costly and should strictly be
    avoided in loops.Not that expensive performance-wise. It could potentially suck up a lot of memory if you are creating LOTS of objects
    Now for the concrete case of reading some user's
    datasets from a database
    and then processing them further, is it advisable
    to instantiate a new user object for each row, or
    where is the alternative
    to be found?I think you should create an object to represent each row.
    two dimensional collections (any favourites in java)I always create my own. I try to use Vectors and Hashtables exclusively, depending on my needs re: ordering and lookup. Mixing and matching these could result in Vectors of Hashtables, Vectors of Vectors, Hashtables of Vectors, and Hashtables of Hashtables.
    synchronized one dimensional collections each
    representing one field in a
    table ? (is this really more performant than simple
    classes)Doubtful - any gain that you get by avoiding the constructor call would be obviated by the overhead of iterating through multiple lists and keeping them synchronized.
    a Collection of Collections (here comes the new
    operator again)Same as two-dimensional collections.
    I remember having seen inner classes used for the
    purpose of holding just a
    couple of attributes, is there some performance
    advantage like "the class
    loader does not have to look for the class".No advantage - the only reason to create an inner class is to prevent other classes from using those objects. The inner class still compiles to a separate class object that needs to be loaded separately.

  • Formatting a two-dimensional list...

    Is there a way to create a two-dimensional ArrayList of Integers with all cells containing certain values, for example zeros? -I will be storing changing Integer values in certain x- and y-coordinates!!
    Something like:
    ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();But my problem is that the .get commands cause an Exception if a cell value is not set:
    list.get(x).get(y) and list.get(x).set(y,int)How could I get around the "null" values without Exceptions? Would you first replace the null values with zeros? (Or is there some other way to store such information?)

    If you want to a fill a List up with values, use java.util.Collections.fill().
    But do you really want it full of some kind of value, or do you just want to indicate "no value filled in" for a bunch of positions in the grid? What percentage of positions will not be filled in, or will be filled in with the default?
    Here's a simple sparse grid:
    public class Pair {
      final int x;
      final int y;
      public boolean equals(Object o) {
        Pair p = (Pair) o;
        return p.x == x && p.y == y;
      public int hashcode() {
        return x + y;
    public class SparseGrid {
      private Map<Pair, Integer> grid = new HashMap<Pair, Integer>();
      public Integer get(Pair p) {
        Integer i = grid.get(p);
        if (i == null)
          return 42; // the default.  or just skip this test if you don't want a default
        return i;
      // also a put method, left as exercise
    }That's all untested.

  • How to sort a selection of cells?

    If anyone can answer this question I will be very grateful - here's the scoop: I need to sort the data in a selection of cells that run down several rows - but NOT all of the cells in the entire row. The last column contains formulas which must NOT be sorted - if those cells are included in the sort, all of the data they contain will be out of order and all fouled up. So, I need to select, for instance, A1:G10 - and not touch anything that is in H1:H10. It appears that with Numbers, it's all or nothing - which, if that's true, is a really big problem. I can't sort the entire selection of rows and then drag and replace the formulas in the last column - there are thousands of rows and it has already taken me an hour to straighten out this mess. I can do this in 2 seconds in Excel, which I've used for very complex spreadsheets and models for years - but I expected to at least be able to do some basic calculating with Numbers in a reasonably easy fashion. I am royally frustrated - what is the hidden secret to sorting a selection of cells without being forced to sort an entire row? Thanks for your help!

    Numbers sorts apply to the whole table, or in the case of sorting selected rows, to the whole width of the table. For ANY sort, header rows and footer rows are not included in the sort.
    Two ways around this limitation are to:
    1.
    Place the 'non-sorting'columns into a separate table, and use INDIRECT addressing to reference cells on the sorting table.
    2.
    Write the formulas so as to be immune to sorting. Use column only references where possible and construct cell addresses for rows other than the result row using the ROW() function.
    Check the Functions and Formulas User Guide for ROW(), INDIRECT() and OFFSET() for descriptions and examples. That guide and the Numbers '09 User Guide are available for download through Numbers's Help menu.
    Post a question regarding specific formulas if you require further assistance.
    Regards,
    Barry

  • Problem with select all cells in JTable

    Hi guys! I get some problem about selecting all cells in JTable. I tried to used two methods:
    1> table.selectAll()2> changeSelection(firstcell, lastcell,false,true)
    firstcell:[0,0], lastcell[rowcount-1,colcount-1]
    Result: only the first row selected when i use both methods.
    Note: i set up the selection model as following:
    this.dataSheet.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                    this.dataSheet.setCellSelectionEnabled(true);
                    this.dataSheet.setRowSelectionAllowed(true);
                    this.dataSheet.setColumnSelectionAllowed(true);Thanks !

    What selection properity should be changed in order to enable selectAll() method work properly? Is there Any constraints? Here is the TableModel I am using. And i set up selection mode use the following code:
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setCellSelectionEnabled(true);
    table.setRowSelectionAllowed(true);
    table.setColumnSelectionAllowed(true);
    import java.util.Vector;
    import javax.swing.table.*;
    import javax.swing.JTable;
    public class DataSheetModel extends AbstractTableModel{
              private Vector data = new Vector();//Store data
              private Vector columnNames = new Vector();//Store head
              public DataSheetModel(){}
              public DataSheetModel(Vector headVector, Vector dataVector){
                   if(headVector != null) this.columnNames = headVector;
                   if(dataVector != null) this.data = dataVector;
              public int getColumnCount(){
                   return columnNames.size()+1;
              public int getRowCount(){
                   return data.size()+1;
              public String getColumnName(int col){
                   if(col==0) return "";
                   else return (String)columnNames.get(col-1);
              public Object getValueAt(int row, int col){
                   if(col==0) {
                        if(row != data.size()) return String.valueOf(row);
                        else return "*";
                   else{
                        if(row != data.size()){
                             Vector rowVector = (Vector)data.elementAt(row);
                             return rowVector.elementAt(col-1);
                        }else return null;
              public void setValueAt(Object value, int row, int col){
                   if(row != this.data.size()){
                        Vector rowVector = (Vector)data.elementAt(row);
                        rowVector.set(col-1,value);
                        this.data.set(row,rowVector);
                        this.fireTableDataChanged();
                   }else{
                        Vector rowVector = new Vector();
                        for(int i=0; i<this.getColumnCount()-1; i++) rowVector.add(null);
                        rowVector.set(col-1,value);
                        this.data.add(rowVector);
                        this.fireTableDataChanged();
              public Class getColumnClass(int c){
                   return getValueAt(0,c).getClass();
              public boolean isCellEditable(int row, int col){
                   if(col == 0) return false;
                   else return true;
              public void setDataVector(Vector head, Vector data){
                   if(head != null) this.columnNames = head;
                   if(data != null) this.data = data;
    }

  • How can I do two dimensional arrays?

    I am a C++ programmer and in C++ I am able make a two dimensional array and input the values that correspond to those cells.
    After I saw the proposals that you (experts) made I am going to share a little of the classified information that I was working for the undefeatable XO game.
    First step:My idea was to make a two dimensional array(in C++ we use the following syntex for two dimensional array{array[i][j]})
    I was wondering if I am able to make a two dimensional array using LABVIEW .
    Second step: Store the values of X or O inside the 2D array.And use maybe boolean variables(in C++ we use inaddition to that if statement).
    My second question :What can I do inorder to minimize the number of boolean vaariables?(also if statements in C++)
    Jupiter
    extinct when hell froze over

    This is a subroutine I use to check for a winner in a XO game.
    While playing, the main code replaces default 0's by 1's inside the 2D array of a single player.
    Then the main code calls this VI with the 2D array of that player and check for a winning game.
    Any board size is ok as long as you have equal number of cols & rows.
    So, enter 1's at any location in the "Score" 2D array and the code will check for a winning game.
    As you can see I don't use any boolean variables, except the return value of this VI (read function) 
    So to answer your second question; I minimized the use of boolean variables to 0 1! Is that ok for you?
    Attachments:
    TTT-Check4Winner.vi ‏20 KB

  • Programmatically select a property

    Hello,
    Is it possible to programmatically select a property for a FP object? Properties for which a value change is required are stored in a database (as are the values itself). I can't use a property node because the poperty to change is not fixed and the database can and will be extended in near future.
    Thanks.
    Jan

    That looks to be a very powerful library of VI's that you have linked to tst.
    It looks like they've basically enumerated all the possible properties for all the control types.  They some tricky combination of names and tags and the properties saved as binary data and can parse the file they have to determine which VI's to run and which cases of all the case structures to execute to get to the appropriate property node.
    I'm going to hold on to this library as it could be very helpful in the future.
    I dug into the VI's to see how they were doing this.  I came across a property node with a pink top bar instead of the usual yellow, and I've never seen this before.  What does it mean?
    Attachments:
    [psr] Tree - Cell Colors_BD.png ‏34 KB

  • Selecting a cell wich contains a desired letter

    Hi! I need to find a function wich select the cell that begins with a desired letter, P in this case.

    efrain,
    Assuming Yvan has demonstrated what you want, his solution may be carried one step further to include multiple results. One of my favorite techniques applies here. Set up a two-cell table where you enter the letter you're searching. Then in column A of your list, isolate and number all instances of words beginning with the chosen letter. Finally, display the results.
    Column A: =IF(LEFT(B2,1)=Table 6 :: B$1,MAX($A$1:A1)+1,"")
    Column D: =IF(ROW()-1>MAX(Hidden),"",LOOKUP(ROW()-1,Hidden,B))
    pw

  • Distinguishing user selections from programmatic selections in JList

    I have two jlists., and registered a subclass of ListSelectionListener on each list. When the user selects a record in the first list part of of the code I have written sets a selection on the second list which is correct, but then this triggers the listener on the second list to receive an event, and run its listener code which is not what I want.
    I want to be able to identify a list selection caused by the user selecting a record in the list rather than the a programmatic selection, so that i can ignore programmatic selections.
    Checking event.getSource() is no good as it always just returns the JList itself regardless of whether it has been done programtaically or by a user.
    I tried checking list.isFocusOwner() , figuring that only lists that had been user selected would be focus owner. This works for Windows but on MacOS, it doesnt work the frst time you select something from the list after moving from another component (it does work after that).
    How do i do this, thanks Paul

    an alternative is to set a flag
    boolean fromList1Listener = false;//class field scope
    list1Listener
      fromList1Listener = true;
      change list2 selection
      fromList1Listener = false;
    list2Listener
      if(fromList1Listener == false)
        normal code goes here
    }

  • ADF Tree (10.1.3) Programmatically select Tree node

    Hi,
    i want to pre-select a specific treenode in an af:tree programmatically. I got it nearly working with using a CoreTree-binding in the backing bean using set setFocusRowKey method. After that, the node is selected properly, but when selecting another node in the tree via the UI, the programmatically selected node is not deselected, means in the display is see two selected nodes.
    Any ideas ?
    Tia,
    Andreas

    Hi,
    is this the same as
    Re: Facing a problem in programmatically setting focus on a node in <af:tre
    Frank

  • Please change the view in the top sites, the 6.1 upgrade has reverted back to a plane two dimensional view, which is a little plain. Can I revert back to an older version via my time capsule save?

    Please change the view in the top sites, the 6.1 upgrade has reverted back to a plain two-dimensional view, which is a little dated. Can I revert back to an older version via my time capsule save? C'mon Apple upgrades supposed to leap into the future not the past. :-(

    Please change the view in the top sites, the 6.1 upgrade has reverted back to a plain two-dimensional view, which is a little dated. Can I revert back to an older version via my time capsule save? C'mon Apple upgrades supposed to leap into the future not the past. :-(

  • How can I select multiple cells in tableview with javafx only by mouse?

    I have an application with a tableview in javafx and i want to select multiple cells only by mouse (something like the selection which exists in excel).I tried with setOnMouseDragged but i cant'n do something because the selection returns only the cell from where the selection started.Can someone help me?

    For mouse drag events to propagate to nodes other than the node in which the drag initiated, you need to activate a "full press-drag-release gesture" by calling startFullDrag(...) on the initial node. (See the Javadocs for MouseEvent and MouseDragEvent for details.) Then you can register for MouseDragEvents on the table cells in order to receive and process those events.
    Here's a simple example: the UI is not supposed to be ideal but it will give you the idea.
    import java.util.Arrays;
    import javafx.application.Application;
    import javafx.beans.property.SimpleStringProperty;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.event.EventHandler;
    import javafx.geometry.Insets;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.control.SelectionMode;
    import javafx.scene.control.TableCell;
    import javafx.scene.control.TableColumn;
    import javafx.scene.control.TableView;
    import javafx.scene.control.cell.PropertyValueFactory;
    import javafx.scene.input.MouseDragEvent;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.layout.VBox;
    import javafx.scene.text.Font;
    import javafx.stage.Stage;
    import javafx.util.Callback;
    public class DragSelectionTable extends Application {
        private TableView<Person> table = new TableView<Person>();
        private final ObservableList<Person> data =
            FXCollections.observableArrayList(
                new Person("Jacob", "Smith", "[email protected]"),
                new Person("Isabella", "Johnson", "[email protected]"),
                new Person("Ethan", "Williams", "[email protected]"),
                new Person("Emma", "Jones", "[email protected]"),
                new Person("Michael", "Brown", "[email protected]")
        public static void main(String[] args) {
            launch(args);
        @Override
        public void start(Stage stage) {
            Scene scene = new Scene(new Group());
            stage.setTitle("Table View Sample");
            stage.setWidth(450);
            stage.setHeight(500);
            final Label label = new Label("Address Book");
            label.setFont(new Font("Arial", 20));
            table.setEditable(true);
            TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
            firstNameCol.setMinWidth(100);
            firstNameCol.setCellValueFactory(
                    new PropertyValueFactory<Person, String>("firstName"));
            TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
            lastNameCol.setMinWidth(100);
            lastNameCol.setCellValueFactory(
                    new PropertyValueFactory<Person, String>("lastName"));
            TableColumn<Person, String> emailCol = new TableColumn<>("Email");
            emailCol.setMinWidth(200);
            emailCol.setCellValueFactory(
                    new PropertyValueFactory<Person, String>("email"));
            final Callback<TableColumn<Person, String>, TableCell<Person, String>> cellFactory = new DragSelectionCellFactory();
            firstNameCol.setCellFactory(cellFactory);
            lastNameCol.setCellFactory(cellFactory);
            emailCol.setCellFactory(cellFactory);
            table.setItems(data);
            table.getColumns().addAll(Arrays.asList(firstNameCol, lastNameCol, emailCol));
            table.getSelectionModel().setCellSelectionEnabled(true);
            table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
            final VBox vbox = new VBox();
            vbox.setSpacing(5);
            vbox.setPadding(new Insets(10, 0, 0, 10));
            vbox.getChildren().addAll(label, table);
            ((Group) scene.getRoot()).getChildren().addAll(vbox);
            stage.setScene(scene);
            stage.show();
        public static class DragSelectionCell extends TableCell<Person, String> {
            public DragSelectionCell() {
                setOnDragDetected(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        startFullDrag();
                        getTableColumn().getTableView().getSelectionModel().select(getIndex(), getTableColumn());
                setOnMouseDragEntered(new EventHandler<MouseDragEvent>() {
                    @Override
                    public void handle(MouseDragEvent event) {
                        getTableColumn().getTableView().getSelectionModel().select(getIndex(), getTableColumn());
            @Override
            public void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setText(null);
                } else {
                    setText(item);
        public static class DragSelectionCellFactory implements Callback<TableColumn<Person, String>, TableCell<Person, String>> {
            @Override
            public TableCell<Person, String> call(final TableColumn<Person, String> col) {         
                return new DragSelectionCell();
        public static class Person {
            private final SimpleStringProperty firstName;
            private final SimpleStringProperty lastName;
            private final SimpleStringProperty email;
            private Person(String fName, String lName, String email) {
                this.firstName = new SimpleStringProperty(fName);
                this.lastName = new SimpleStringProperty(lName);
                this.email = new SimpleStringProperty(email);
            public String getFirstName() {
                return firstName.get();
            public void setFirstName(String fName) {
                firstName.set(fName);
            public String getLastName() {
                return lastName.get();
            public void setLastName(String fName) {
                lastName.set(fName);
            public String getEmail() {
                return email.get();
            public void setEmail(String fName) {
                email.set(fName);

  • How to get selected/focused cell from table, and action on clicked

    Hello Web Dynpro Community!
    i have a view with a table, (id "Table_0");
    table is 3x3 size, as celleditors i used inputfields; (standard binding to context with string atributes)
    below table i have textarea.
    when i select any cell in table i want to add that cell coords to textarea (col and row)
    i know that i should use onLeadSelect action, but i dont know exacly how. or to be precise.. how to access to ID and row variables in that action.
    the other problem is.. that onLeadSelect seems to work only when i change lead not the cell in same row.. so prabobly there is better way to do that..
    any ideas?
    Looking to hear from You.
    EDIT:
    Now i have following problem:
    i have a table 3x3 with one column as dropdownbykey box and 2 as TableSingleMarkableCell (and inputFields As editors).
    it works as i wanted:
    so when i click on one of those input cells, insert vale AND click enter then the action onEnter( for inputfield) is fired... i can get the coords of that cell..
    problem is.. that i want to get the coords before i click enter.. just when i click in cell.
    i tried to use onAction event for column.. but it doesnt work for TableSingleMArkableCells (but it works for ddk column correctly).
    so there is any way to do that?
    ie:
    below table i have inputfield (called  value).
    when i click on cell (and DO NOT press enter) i want to see the cell value in inputfield value.
    future (and target need) is that i need to show some additional text for specific Cell. (i have an Object with 2 strings attributes, one i want to show in cell, and one in inputfield when cell is clicked).
    M.
    Edited by: Michal Rowinski on Jan 16, 2008 9:51 AM

    You can use cell variant  for your requirement . Go through the below link
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/c0310fd2-f40d-2a10-b288-bcbe0810a961
    Regards,
    Nethaji

Maybe you are looking for

  • Can't scan to mac

    I have tried all the tips in the messages but I cannot scan to my Mac.  I tried also using the HP utility and it says it scans an overview, but I cannot find the files on the computer.  Here is the message I am getting.  The printer function works fi

  • Counting files in a Flder

    Hi all, I have to count the number of files in a folder and their respectives name in it using flash.Is it possible to do it by JSFL. can anyone give me samples regarding this.thanks in advance. Regards, S.Hidayath

  • What's your strategy for WebService errors that aren't raised through fault handler?

    Is there a way to underride the default functionality of WebService.as? I can't find the source code in the SDK, so I'm assuming this part of Flex isn't Open Source. I find that using WebServices that there are a lot of errors that potentially occur

  • Rapport missing from toolbar in Firefox version 18. Is it no longer compatible with Firefox?

    I get no indication that Rapport is active so I can't trust Firefox if I need Rapport protection.

  • Change configuration of Webservice Proxy

    Hi! I've generated a webservice proxy to call to a webservice. My problem is that when it call the service, it send and xml like this: <env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xm