Selecting cells in a JTable

Hi All,
I'm looking for a way of selecting all cells from the original drag point to the current cell that the mouse is over.
This is for a year planner which displays the months vertcally and the days horizontally. So if the user was to start selecting cells in one month and move the mouse down a row onto the next month, I would want all cells selected from the first cell to the current cell.
Has anyone got any ideas?

Hi Pchatwin,
Any dukes available for bad news? :)
Thanks Stas but wouldn't that select entire rows
rather than cells?
For example, if I have a grid:
12345
67890
and drag from cell 3 to cell 9 I would need to see
cells 3, 4, 5, 6, 7, 8, 9 highlightedUnfortunately this is impossible with JTable's default selection model. By default, JTable models selections simply as an intersection of selected rows and columns. It doesn't track individual cells.
Turning to your example:
If you select cells 2,3,4,5 JTable tracks the following.
Note: The numbers I am using are row/col indexes, not your cell values.
Selected rows = {0}
Selected cols = {1,2,3,4}
This means the following cells are selected:
{{0,1},{0,2},{0,3},{0,4}} or {2,3,4,5}
Now if you want to add cells 6, 7, 8, 9 it won't work. The selection model tracks whether a column is selected or not. It can't be selected for one row and not for another. So it's impossible to have cell 6 selected and not 1. It would mean that column 0 would need to be both selected (to include 6) and not (to include 1). Does this make sense?
Sorry to have to tell you that. On the other hand it may save you some frustration.
Oh, and whether or not one can provide a custom model that allows this, I don't know - I've not tried it myself. It could be, but might be very difficult. For example, what would you return from JTable.getSelectedRows()?
Thanks!
Shannon Hickey (Swing Team)
>
Paul

Similar Messages

  • How do I change the colour of a selected cell in a jTable?

    I have a Jtable that displays URL names in one column. There are several problems I'm having. The effect I'm trying to achieve is this:
    When the user runs the mouse over the URL name the cursor should change into a hand (similar to what happens in an HTML hyperlink). I'm aware that the Cursor class can set the cursor graphic so i figure that i need a listener of some sort on each cell (so the cursor can change from an arrow to a hand) and also one to indicate when the cursor is not on a cell (so that it can change from a hand back into an arrow). Is this the right track?
    Also, I've looked at the DefaultTableCellRenderer class (which, as i understand it, is responsible for how each cell in the jtable is displayed) for a method that will allow me to set the background of a selected cell (or row or column). I require this because each time i select a cell (or row) it becomes highlighted in blue. I would rather it just remained white and changed the cursor to a hand. I know there exists a method for setting the background for an unselected cell but none for a selected cell. Again, I'm not sure if I'm going down the right track with this approach.
    Lastly, if the cell has been selected (by a mouse click) the font of the writing in the cell (i.e. The name of the URL) should change. This shouldn't be too much of a problem I think.
    I do not expect anyone to provide code to do all of this but some general pointers would be extremely helpful as I do not know if I'm thinking on the right track for any of this. Having some (limited) experience with Swing I doubt there is a simple way to do this but I can only hope!
    Thanks.
    Chris

    http://www2.gol.com/users/tame/swing/examples/SwingExamples.html
    there you can find some examples with CellRenderer's and so on ...
    have fun

  • How to outline selected cells during drag and drop in the jtable

    Hi,
    I have spent a lot of time to find out how to outline selected cells during drag in the jtable, but I did not find the answer.
    Can anybody give me a tip, where to read more about this problem or even better, give an example...
    I have the following situation:
    1.Table has 10 rows and 10 columns
    2.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION) and setCellSelectionEnabled(true)
    3.user select 5 cells in 4th row (for example cell45,cell46,cell47,cell48 and cell49)
    4.user starts dragging. During dragging an outline should be drawn. Outline should be a rectangular with width of 5 cells and height of one cell. Outline should move according to the mouse position.
    5.rectangular disappears when dropped
    Regards,
    Primoz

    In "createTransferable" you can create a drag image
    which you can paint in "dragOver" and clear in "drop" method of DropTarget :
    package dnd;
    * DragDropJTableCellContents.java
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    public class DragDropJTableCellContents extends JFrame {
        public DragDropJTableCellContents() {
            setTitle("Drag and Drop JTable");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            getContentPane().add(createTable("JTable"), BorderLayout.CENTER);
            setSize(400, 300);
            setLocationRelativeTo(null);
        private JPanel createTable(String tableId) {
            DefaultTableModel model = new DefaultTableModel();
            for (int i = 0; i < 10; i++) {
                model.addColumn("Column "+i);
            for (int i = 0; i < 10; i++) {
                String[] rowData = new String[10];
                for (int j = 0; j < 10; j++) {
                    rowData[j] = tableId + " " + i + j;
                model.addRow(rowData);
            JTable table = new JTable(model);
            table.getTableHeader().setReorderingAllowed(false);
            table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            table.setCellSelectionEnabled(true);
            JScrollPane scrollPane = new JScrollPane(table);
            table.setDragEnabled(true);
            TableTransferHandler th = new TableTransferHandler();
            table.setTransferHandler(th);
            table.setDropTarget(new TableDropTarget(th));
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(scrollPane);
            panel.setBorder(BorderFactory.createTitledBorder(tableId));
            return panel;
        public static void main(String[] args) {
            new DragDropJTableCellContents().setVisible(true);
        abstract class StringTransferHandler extends TransferHandler {
            public int dropAction;
            protected abstract String exportString(JComponent c);
            protected abstract void importString(JComponent c, String str);
            @Override
            protected Transferable createTransferable(JComponent c) {
                return new StringSelection(exportString(c));
            @Override
            public int getSourceActions(JComponent c) {
                return COPY;
            @Override
            public boolean importData(JComponent c, Transferable t) {
                if (canImport(c, t.getTransferDataFlavors())) {
                    try {
                        String str = (String) t.getTransferData(DataFlavor.stringFlavor);
                        importString(c, str);
                        return true;
                    } catch (UnsupportedFlavorException ufe) {
                    } catch (IOException ioe) {
                return false;
            @Override
            public boolean canImport(JComponent c, DataFlavor[] flavors) {
                for (int ndx = 0; ndx < flavors.length; ndx++) {
                    if (DataFlavor.stringFlavor.equals(flavors[ndx])) {
                        return true;
                return false;
        class TableTransferHandler extends StringTransferHandler {
            private int dragRow;
            private int[] dragColumns;
            private BufferedImage[] image;
            private int row;
            private int[] columns;
            public JTable target;
            @Override
            protected Transferable createTransferable(JComponent c) {
                JTable table = (JTable) c;
                dragRow = table.getSelectedRow();
                dragColumns = table.getSelectedColumns();
                createDragImage(table);
                return new StringSelection(exportString(c));
            protected String exportString(JComponent c) {
                JTable table = (JTable) c;
                row = table.getSelectedRow();
                columns = table.getSelectedColumns();
                StringBuffer buff = new StringBuffer();
                for (int j = 0; j < columns.length; j++) {
                    Object val = table.getValueAt(row, columns[j]);
                    buff.append(val == null ? "" : val.toString());
                    if (j != columns.length - 1) {
                        buff.append(",");
                return buff.toString();
            protected void importString(JComponent c, String str) {
                target = (JTable) c;
                DefaultTableModel model = (DefaultTableModel) target.getModel();
                String[] values = str.split("\n");
                int colCount = target.getSelectedColumn();
                int max = target.getColumnCount();
                for (int ndx = 0; ndx < values.length; ndx++) {
                    String[] data = values[ndx].split(",");
                    for (int i = 0; i < data.length; i++) {
                        String string = data;
    if(colCount < max){
    model.setValueAt(string, target.getSelectedRow(), colCount);
    colCount++;
    public BufferedImage[] getDragImage() {
    return image;
    private void createDragImage(JTable table) {
    if (dragColumns != null) {
    try {
    image = new BufferedImage[dragColumns.length];
    for (int i = 0; i < dragColumns.length; i++) {
    Rectangle cellBounds = table.getCellRect(dragRow, i, true);
    TableCellRenderer r = table.getCellRenderer(dragRow, i);
    DefaultTableModel m = (DefaultTableModel) table.getModel();
    JComponent lbl = (JComponent) r.getTableCellRendererComponent(table,
    table.getValueAt(dragRow, dragColumns[i]), false, false, dragRow, i);
    lbl.setBounds(cellBounds);
    BufferedImage img = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
    BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics2D graphics = img.createGraphics();
    graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
    lbl.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
    lbl.paint(graphics);
    graphics.dispose();
    image[i] = img;
    } catch (RuntimeException re) {
    class TableDropTarget extends DropTarget {
    private Insets autoscrollInsets = new Insets(20, 20, 20, 20);
    private Rectangle rect2D = new Rectangle();
    private TableTransferHandler handler;
    public TableDropTarget(TableTransferHandler h) {
    super();
    this.handler = h;
    @Override
    public void dragOver(DropTargetDragEvent dtde) {
    handler.dropAction = dtde.getDropAction();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    Point location = dtde.getLocation();
    int row = table.rowAtPoint(location);
    int column = table.columnAtPoint(location);
    table.changeSelection(row, column, false, false);
    paintImage(table, location);
    autoscroll(table, location);
    super.dragOver(dtde);
    public void dragExit(DropTargetDragEvent dtde) {
    clearImage((JTable) dtde.getDropTargetContext().getComponent());
    super.dragExit(dtde);
    @Override
    public void drop(DropTargetDropEvent dtde) {
    Transferable data = dtde.getTransferable();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    clearImage(table);
    handler.importData(table, data);
    super.drop(dtde);
    private final void paintImage(JTable table, Point location) {
    Point pt = new Point(location);
    BufferedImage[] image = handler.getDragImage();
    if (image != null) {
    table.paintImmediately(rect2D.getBounds());
    rect2D.setLocation(pt.x - 15, pt.y - 15);
    int wRect2D = 0;
    int hRect2D = 0;
    for (int i = 0; i < image.length; i++) {
    table.getGraphics().drawImage(image[i], pt.x - 15, pt.y - 15, table);
    pt.x += image[i].getWidth();
    if (hRect2D < image[i].getHeight()) {
    hRect2D = image[i].getHeight();
    wRect2D += image[i].getWidth();
    rect2D.setSize(wRect2D, hRect2D);
    private final void clearImage(JTable table) {
    table.paintImmediately(rect2D.getBounds());
    private Insets getAutoscrollInsets() {
    return autoscrollInsets;
    private void autoscroll(JTable table, Point cursorLocation) {
    Insets insets = getAutoscrollInsets();
    Rectangle outer = table.getVisibleRect();
    Rectangle inner = new Rectangle(outer.x + insets.left,
    outer.y + insets.top,
    outer.width - (insets.left + insets.right),
    outer.height - (insets.top + insets.bottom));
    if (!inner.contains(cursorLocation)) {
    Rectangle scrollRect = new Rectangle(cursorLocation.x - insets.left,
    cursorLocation.y - insets.top,
    insets.left + insets.right,
    insets.top + insets.bottom);
    table.scrollRectToVisible(scrollRect);
    Edited by: Andre_Uhres on Nov 18, 2007 10:03 PM

  • JTable selected cell highlight

    Hi,
    I want to reproduce Excel behaviour in a JTable :
    highlight the cell on which user has clicked once
    show the caret when the user has double-cliked on it.
    The second behaviour looks like being built-in the JTable
    But when the user clicks once on the cell not visual effect appears
    to reflect the click event.
    I would like to have the selected cell "border" painted in another color.
    Would you have a hint for that ?
    thanks

    Thanks you the hint Razor_Blade.
    could you elaborate a bit more please.
    I don't feel like getting deep into rendering stuff now,
    and was expecting a simple solution.
    But if there's no, don't bother.
    It will take the time that it needs but I'll find out.
    thx.

  • JTable selected Cell Fontsize

    1)
    I work with a JTable.
    The cells display the value in font size 18.
    If I click on a cell to edit it,
    than the cell fontsize is smaller, I think its the default size 10.
    How can I modify the selected cell fontsize?
    2)
    Is it possible to modify the font color of a cell
    without using TableCellRenderer, because I have to modify it dynamically.
    e.g. jTable.cell(2,2).setFontColor(Color.BLUE);

    1)
    I work with a JTable.
    The cells display the value in font size 18.
    If I click on a cell to edit it,
    than the cell fontsize is smaller, I think its the
    default size 10.
    How can I modify the selected cell fontsize?probably something to do with the renderer
    >
    2)
    Is it possible to modify the font color of a cell
    without using TableCellRenderer, because I have to
    modify it dynamically.
    e.g. jTable.cell(2,2).setFontColor(Color.BLUE);no, use the renderer

  • How to listen for cell selection changes within a JTable

    Problem: my table has 8 columns, with 4 of them containing very large text (up to 1000 chars). Solution is to set the initial size these columns so that the 1st 20 chars are visible, and if one of these columns gains focus/selection via mouse-clicking/tabbing/arrow keys, the entire text is shown in a JTextArea below the table.
    I added a ListSelectionListener to the table, but this only informs me when the row selection has changed.
    I added a FocusListener to the table, but this only informs me when the table gains/loses focus, not when it's been changed within.
    I added a TableColumnModelListener to the TableColumnModel, but this only informs me when the column selection has changed.
    I didn't bother with MouseListener as this won't handle change of selection via tabbing.
    The LSL got me half way there, and the TCML got me the other half. Any ideas on how to combine?
    Or is there something obvious that I'm missing?

    Walter Laan wrote:
    Use both and call the same method which updates the text area based on the current selected (or focused == lead selection index) cell.Yeah - that's what I figured. I just didn't know if there was a magic bullet (i.e., a single listener) out there that I was missing.
    While you are at it, also add a table model listener which calls the same method if the selected cell is updated.I'll keep that in mind, but it's not necessary in this particular case. The table cells in question will be uneditable. The text area will have supporting Edit/Save/Cancel buttons.

  • How to change a selected cell background color in JTable?

    Hi all,
    I am trying to change the background color of a selected cell by clicking on that particular cell. DefaultTableCellRenderer class provides setBackground(Color c) to change the background color of unselected cells. Is there a way to change a selected cell background color?
    Thank you,
    Arthur

    Write your own renderer (eg. extending DefaultTableRenderer) and put in getTableCellRendererComponent method something like this:
    if( isSelected && hasFocus )
        setBackground( Color.RED );
        setForeground( Color.GREEN );
    }

  • Jtable keep the selected cells' background

    hi,
    I want to change the background color of the selected cells.
    after selection, I may do another selection,but I want to keep the previous selected cells' background color.
    any help will be appreciated!
    thanks!
    zhangv

    Did you try using Ctrl + Mouse Click ?
    Remember you need to set following property before you try the above solution:
    tableObj.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );

  • Getting right end of text displayed in cells of a JTable column

    Hey All,
    Platform: WinXP, Java 5.0.
    I have a simple one-column table whose cells contain pathnames of user-selected files. The pathnames may be quite long, and when they're too long for the fixed width of the column (the containing JFrame is not resizable), I want the trailing (right) end of the pathnames to visible (so the filenames are visible) and for elipsis to be used on the left side (omitting root directory, etc., if need be). I can't figure out how to do this. I've tried many different approaches. Currently I use a class that extends TableCellRenderer, but no combination of alignment settings in this class seems to do the trick.
    I've noticed that in the case of JTextFields, this manner of display seems to be the default, no matter what alignment setting I choose. I can't seem to get the desired effect with the display of cells in my JTable though.
    Anyone have any suggestions?
    Thanks in advance.

    Great job camickr,
    That did just what I wanted; you get the points for sure! I will say that It's surprising to me that Swing leaves so much work in calculation to be done for this simple idea.
    Btw, I also want to mention here that there's another forum issue I raised and you responded to recently, and you never quite answered my question there:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=5160875
    That's got 10 pts riding on it too, if you care to revisit the issue...
    Thanks very much for the good work on the CellRenderer.

  • A problem to get the value of a selected cell

    Hi all,
    I am trying to get the value of a cell in JTable. The problem that I have is ListSelectionListener only listens if the selection changes(valueChanged method).
    It means that if I select apple then rum, only rowSelectionModel is triggered, which means I do not get the index of the column from selectionModel of ColumnModel.
    apple orange plum
    rum sky blue
    This is a piece of code from JTable tutorial that I modified by adding
    selRow and selCol variables to keep track of the location so that I can get the value of the selected cell.
    Thank you.
    if (ALLOW_ROW_SELECTION) { // true by default
    ListSelectionModel rowSM = table.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    System.out.println("No rows are selected.");
    } else {
    int selectedRow = lsm.getMinSelectionIndex();
    selRow = selectedRow;
    System.out.println("Row " + selectedRow + " is now selected.");
    else {
    table.setRowSelectionAllowed(false);
    if (ALLOW_COLUMN_SELECTION) { // false by default
    if (ALLOW_ROW_SELECTION) {
    table.setCellSelectionEnabled(true);
    table.setColumnSelectionAllowed(true);
    ListSelectionModel colSM = table.getColumnModel().getSelectionModel();
    colSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    //Ignore extra messages.
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    System.out.println("No columns are selected.");
    } else {
    int selectedCol = lsm.getMinSelectionIndex();
    selCol = selectedCol;
    System.out.println("Column " + selCol + " is now selected.");
    System.out.println("Row " + selRow + " is now selected.");
    javax.swing.table.TableModel model = table.getModel();
    // I get the value here
    System.out.println("Value: "+model.getValueAt(selRow,selCol));
    }

    maybe you can try with :
    table.getSelectedColumn()
    table.getSelectedRow()
    :)

  • To change the font of a selected row in a Jtable

    Hello,
    Is it possible to change the font of a selected row in a jtable?
    i.e. if all the table is set to a bold font, how would you change the font of the row selected to a normal (not bold) font?
    thank you.

    String will be left justified
    Integer will be right justified
    Date will be a simple date without the time.
    As it will with this renderer.Only if your custom renderer duplicates the code
    found in each of the above renderers. This is a waste
    of time to duplicate code. The idea is to reuse code
    not duplicate and debug again.
    No, no, no there will be NO duplicated code.
    A single renderer class can handle all types ofdata.
    Sure you can fit a square peg into a round hole if
    you work hard enough. Why does the JDK come with
    separate renderers for Date, Integer, Double, Icon,
    Boolean? So that, by default the rendering for common classes is done correctly.
    Because its a better design then having code
    with a bunch of "instanceof" checks and nested
    if...else code.This is only required for customization BEYOND what the default renderers provide
    >
    And you would only have to use instanceof checkswhen you required custom
    rendering for a particular classAgreed, but as soon as you do require custom
    renderering you need to customize your renderer.
    which you would also have to do with theprepareRenderer calls too
    Not true. The code is the same whether you treat
    every cell as a String or whether you use a custom
    renderer for every cell. Here is the code to make the
    text of the selected line(s) bold:
    public Component prepareRenderer(TableCellRenderer
    renderer, int row, int column)
    Component c = super.prepareRenderer(renderer, row,
    , column);
         if (isRowSelected(row))
              c.setFont( c.getFont().deriveFont(Font.BOLD) );
         return c;
    }It will work for any renderer used by the table since
    the prepareRenderer(...) method returns a Component.
    There is no need to do any kind of "instanceof"
    checking. It doesn't matter whether the cell is
    renderered with the "Object" renderer or the
    "Integer" renderer.
    If the user wants to treat all columns as Strings or
    treat individual columns as String, Integer, Data...,
    then they only need to override the getColumnClass()
    method. There is no change to the prepareRenderer()
    code.
    Have you actually tried the code to see how simple it
    is?
    I've posted my code. Why don't you post your solution
    that will allow the user to bold the text of a Date,
    Integer, and String data in separate column and then
    let the poster decide.Well, I don't see a compilable, runnable demo anywhere in this thread. So here's one
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Arrays;
    import java.util.Date;
    import java.util.Vector;
    public class TableRendererDemo extends JFrame{
        String[] headers = {"String","Integer","Float","Boolean","Date"};
        private JTable table;
        public TableRendererDemo() {
            buildGUI();
        private void buildGUI() {
            JPanel mainPanel = (JPanel) getContentPane();
            mainPanel.setLayout(new BorderLayout());
            Vector headerVector = new Vector(Arrays.asList(headers));
             Vector data = createDataVector();
            DefaultTableModel tableModel = new DefaultTableModel(data, headerVector){
                public Class getColumnClass(int columnIndex) {
                    return getValueAt(0,columnIndex).getClass();
            table = new JTable(tableModel);
    //        table.setDefaultRenderer(Object.class, new MyTableCellRenderer());
            table.setDefaultRenderer(String.class, new MyTableCellRenderer());
            table.setDefaultRenderer(Integer.class, new MyTableCellRenderer());
            table.setDefaultRenderer(Float.class, new MyTableCellRenderer());
            table.setDefaultRenderer(Date.class, new MyTableCellRenderer());
            JScrollPane jsp = new JScrollPane(table);
            mainPanel.add(jsp, BorderLayout.CENTER);
            pack();
            setLocationRelativeTo(null);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        private Vector createDataVector(){
            Vector dataVector = new Vector();
            for ( int i = 0 ; i < 10; i++){
                Vector rowVector = new Vector();
                rowVector.add(new String("String "+i));
                rowVector.add(new Integer(i));
                rowVector.add(new Float(1.23));
                rowVector.add( (i % 2 == 0 ? Boolean.TRUE : Boolean.FALSE));
                rowVector.add(new Date());
                dataVector.add(rowVector);
            return dataVector;
        public static void main(String[] args) {
            Runnable runnable = new Runnable() {
                public void run() {
                    TableRendererDemo tableRendererDemo = new TableRendererDemo();
                    tableRendererDemo.setVisible(true);
            SwingUtilities.invokeLater(runnable);
        class MyTableCellRenderer extends DefaultTableCellRenderer{
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                 super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                if ( isSelected){
                    setFont(getFont().deriveFont(Font.BOLD));
                else{
                    setFont(getFont().deriveFont(Font.PLAIN));
                if ( value instanceof Date){
                    SimpleDateFormat formatter =(SimpleDateFormat) SimpleDateFormat.getDateInstance(DateFormat.MEDIUM);
                    setText(formatter.format((Date)value));
                if(value instanceof Number){
                   setText(((Number)value).toString());
                return this;
    }Hardly a "bunch of instanceof or nested loops. I only used the Date instanceof to allow date format to be specified/ modified. If it was left out the Date column would be "18 Apr 2005" ( DateFormat.MEDIUM, which is default).
    Cheers
    DB

  • JComboBox Cell Editor in JTable

    I've scouered the forums for an answer to my question, and while
    finding other valuable advice, I have yet to find an answer to my
    question. But first, a little description:
    I have a JTable consisting of 5 columns:
    col1= standard Object cell editor
    col2= JComboBox cell editor
    col3= JComboBox cell editor, values dependent on col2
    col4= JComboBox cell editor, values dependent on col3
    col5= JComboBox cell editor, values dependent on col4
    Data structure looks like this:
    col1= company object, containing vector of values for col2
    col2= lease object, containing vector of values for col3
    col3= well object, containing vector of values for col4
    col4= pump object, containing vector of values for col5
    col5= simply displayed.
    I have a JButton that adds a new row to the table via dialog, then menu
    options to add entries to the comboboxes/vectors. The kicker here is
    that everything is fine up until I've added a pump, and click the cell
    to view the entry. In my cellEditor class, I have a 'getSelected()'
    method that returns 'combobox.getSelectedIndex()'. When 'edittingStopped()'
    is thrown for any cell in this column, I get a null pointer in my
    getSelectedIndex() method of the lease combobox - only in this pump
    column. Even the part column works correctly. Code snips:
    public class MyApplication ... {
      private TableColumn leaseColumn;
      private TableColumn wellColumn;
      private TableColumn pumpColumn;
      private TableColumn partColumn;
      private LeaseDropDown leaseDropDown;
      private WellDropDown wellDropDown;
      private PumpDropDown pumpDropDown;
      private PartDropDown partDropDown;
      private int currentLease = 0;
      private int currentWell = 0;
      private int currentPump = 0;
      public MyApplication() {
        leaseColumn = pumpshopTable.getColumnModel().getColumn(1);
        leaseDropDown = new LeaseDropDown(companies);
        leaseColumn.setCellEditor(leaseDropDown);
        DefaultTableCellRenderer leaseRenderer =
          new DefaultTableCellRenderer();
        leaseRenderer.setToolTipText("Click for leases");
        leaseColumn.setCellRenderer(leaseRenderer);
        //... same for lease, well, pump, part ...
        leaseDropDown.addCellEditorListener(new CellEditorListener() {
          public void editingCanceled(ChangeEvent e) {
          } // end editingCanceled method
          public void editingStopped(ChangeEvent e) {
            updateCells();
          } // end editingStopped method
        }); // end addCellEditorListener inner class
        //.... same inner class for well, pump, part ...
      } // end MyApplication constructor
      public void updateCells() {
        currentLease = leaseDropDown.getSelectedLease();
        //... get current well, pump, part ...
        leaseDropDown = new LeaseDropDown(companies); // companies=Vector,col1
        leaseColumn.setCellEditor(leaseDropDown);
        //... same for lease, well, pump and part columns ...
      } // end updateCells method
    } // end MyApplication class
    public class LeaseDropDown extends AbstractCellEditor
        implements TableCellEditor {
      private Vector companiesVector;
      private JComboBox leaseList;
      public LeaseDropDown(Vector cVector) {
        companiesVector = cVector;     
      } // end LeaseDropDown constructor
      public Component getTableCellEditorComponent(JTable table,
          Object value, boolean isSelected, int rowIndex, int vColIndex) {
        Company thisCompany = (Company) companiesVector.get(rowIndex);
        Vector leasesVector = (Vector) thisCompany.getLeases();
        leaseList = new JComboBox(leasesVector);
        return leaseList;
      } // end getTableCellEditorComponent method
      public Object getCellEditorValue() {
        return leaseList.getSelectedItem();
      } // end getCellEditorValue method
      public int getSelectedLease() {
        JOptionPane.showInputDialog("Selected lease is: " +
          leaseList.getSelectedIndex());
        return leaseList.getSelectedIndex();          
      } // end getSelectedLease method
    } // end LeaseDropDown class... LeaseDropDown can be extrapolated to well, pump, and part,
    handing well the selected lease, handing pump the selected
    lease and well, handing part the selected lease, well and pump.
    I guess my question is how do I get the selected comboboxitem (I'd
    settle for the entire combobox if there's no other way) to fill in the
    next column? Why does the way I have it now work for the first 2 combobox
    columns and not the third?

    I'll try to provide more details.
    I use a JComboBox implementation as a cell in a JTable. The CombBox is editable . This is what I get when I try to type in something.
    java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    at java.awt.Component.getLocationOnScreen_NoTreeLock(Component.java:1507)
    at java.awt.Component.getLocationOnScreen(Component.java:1481)
    at javax.swing.JPopupMenu.show(JPopupMenu.java:921)
    at javax.swing.plaf.basic.BasicComboPopup.show(BasicComboPopup.java:177)
    at javax.swing.plaf.basic.BasicComboBoxUI.setPopupVisible(BasicComboBoxUI.java:927)
    at javax.swing.JComboBox.setPopupVisible(JComboBox.java:790)
    at javax.swing.JComboBox.showPopup(JComboBox.java:775)
    I read some related bugs on the sun site but I am not sure if this is a bug and if it is then has it been fixed or work-around provided.
    any insights ??

  • 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

  • Change the cell color in JTable?

    Hi all,
    I'm trying to do that, the user make a selection of multiple cells in a table. And when it press enter, I whant to change the color of the selected cells.(the isEditable of JTable it's already overwritten to return always false)
    I have already make my own CellRender, my problem is, because the cell remains unchanged the render are not called...
    Thanks,
    NeuralC

    You need not access this function when you want to paint a cell. This is how your code while instantiating the table should typically look like.
    JTable table = new JTable(model);
    table.setDefaultRenderer(Object.class,new MyCellRenderer());
    and
    public class MyTableCellRenderer extends JLabel implements TableCellRenderer
    public MyTableCellRenderer
    setOpaque(true);
    setBackground(Color.white);
    public Component getTable.....(JTable table,Object value,......) //fill all these things
    setFont(table.getFont());
    if(value != null && isSelected)
    setHorizontalAlignment(SwingConstants.RIGHT);
    setText(value);
    return this;
    When you set MyTableCellRenderer to the table, the getTableCellRedererComponent method is called automatically to renderer the cells and only the selected cells will be hightlighted in blue color. For a better understanding of how tables work and their corresponding Renderers work, you might have to read the tutorial on JTable. Do that as that would help you in removing all the confusion.
    Thanks,
    Kalyan

  • Help on Editing a Cell in a JTable

    Hi Folks,
    I have a JTable with two Columns and Some number of rows. My Second Column is Editable i.e., I can change the contents of the cell in the same. My Problem is, When I Select the particular cell in Column2 for Editing it starts appending the text I have typed after the text already present in the Selected Cell.Instead I wanted it to overwrite the previous text present in that cell.(Just like the effect we get in MS Excel). Now What I have to do is press F2 and then press CTRL+A to select all the text in the selected Cell and do the editing. This is somewhat a pain in the Ass to do if you have to Edit a huge table. Is there a Solution for the above problem wherein as soon as I select the cell to edit, it should start overwriting on the previous text instead of appending to the same.There are duke dollars in the offing. Anybody interested in helping me out...???
    Thanks in Advance...
    Sachin Shanbhag

    Hi,
    I am using a JTable with cell editor using TableCellEditor.My table consists of two columns of which first one is using JTextField and the second column ( only the for the column of newly added row) using combobox as editors.My requirement is when a cell gets a focus the cell text should be selected automatically (only for the first column which is using JTextField)) with out the user explicitly going to the focused cell and select the text using mouse.
    If anybody can put some idea on this then it would be fine.
    Thanks
    My code is like this.
    public class PurposesTableEditor implements TableCellEditor
              private TableCellEditor editor;
              private TableCellEditor defaultEditor;
              * HashTable variable for storing editors.
              private Hashtable editors;
              * Constructor.
              public PurposesTableEditor()
                   editors = new Hashtable();
                   defaultEditor = new DefaultCellEditor(new JTextField());
              public void add(int row , TableCellEditor editor)
                   editors.put(new Integer(row),editor);
              public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int col)
                   editor = (TableCellEditor)editors.get(new Integer(row));
                   if (editor == null)
                        editor = defaultEditor;
                   return editor.getTableCellEditorComponent(table, value, isSelected, row, col);
              public boolean stopCellEditing()
                   table.getCellRect(table.getSelectedRow(),0,false);
                   table.getCellRect(table.getRowCount()-1, 0, false);
                   return editor.stopCellEditing();
              public void cancelCellEditing()
                   editor.cancelCellEditing();
              public boolean isCellEditable(EventObject anEvent)
                   return true;
              public boolean shouldSelectCell(EventObject anEvent)
                   return editor.shouldSelectCell(anEvent);
              public void addCellEditorListener(CellEditorListener l)
                   editor.addCellEditorListener(l);
              public Object getCellEditorValue()
                   return editor.getCellEditorValue();
              public void removeCellEditorListener(CellEditorListener l)
                   editor.removeCellEditorListener(l);
         }

Maybe you are looking for

  • Mac Mini Pre 2009 Wireless Question

    I have 3 ways of accessing my wireless network. My wife's new macbook (5,1), my iPhone 3G and my pre 2009 Mac Mini. All worked in our old house. We just moved and wireless router is located further away from my mac mini. Wife's computer and my iPhone

  • App world/twitter app

    Can anyone offer a solution as to why for tuesday and today 7/24 and 7/26, my app world and twitter app will not open?? I do not have the latest versions because I heard they are not better and it is really getting annoying now?

  • A wierd thing with the MSI Radeon 9800 Pro

    I bought this card a few days ago and the wierd thing is that the Windows "thinks" its a 9800XT and not 9800Pro. I installed the latest ATI Drivers (4.8) and there is no change. did someone solved this problem. ty Game Freak

  • Css Error "Unexpected character :: "

    Build JDEVADF_11.1.1.4.0_GENERIC_101227.1736.5923 Hi, in MySkin.css, i have this error: Unexpected character ::, ecpecting :for example af|inputText::content is displayed as error, why? What is missing here? best regards

  • Re-install Cloud applications on upgraded PC to Windows 7

    How do i reinstall Creative Cloud after my computer comes back from being upgraded to Windows 7