Simple JTable / Select Row example?

Hi - I'm having a really hard time wrapping my brain around JTables and their events. Can anybody give me just a real simple example of how to get the value of whatever cell (row, preferrably) by clicking on that cell / row?

Hey there,
im currently doing Jtables within a system i am coding too so thought i would help ya out!
1. You can recognise if a row is selected within your table by using a possible two methods: example of how this can be implemented:
//This method used for only one row at a time being selected
int selectedRow = table.getSelectedRow(); (table being the name of your JTable obviously)
                    if (selectedRow == -1) {//When there is no selected row show error message
                         JOptionPane.showMessageDialog(null, "Must select an employee from the table", "Error Message",
                                                  JOptionPane.ERROR_MESSAGE);
                    else {
                    //DO SOMETHING                    }
               }2. Or you could use the public int [ ] getSelectedRows() method of recognising selected JTable rows: example of how u might implement this, this returns an array of interger values when 1 or more rows are selected:
int [ ] rowselected = table.getSelectedRows();
//In order to go through each selected row and do something with it a loop is obviously needed like:
for (int i = 0; i < rowselected.length; i++) {
                    String empName = (String)(table.getValueAt(rowselected,0));
                    System.out.println(empName);
Hope this helps ;-)

Similar Messages

  • JTable, select row on right mouse click

    Hi,
    If I right click on a jTable row in my application, the row I click on does not get selected.
    How can I modify the mouse listener attached to the jtable to deal with this?
    jtable.addMouseListener( { e->
    if (e.isPopupTrigger())
        swing.popupMenu(menuItems).show(e.getComponent(), e.getX(), e.getY());
    } as java.awt.event.MouseListener)Thanks!

    Problem solved!
    jtable.addMouseListener( { e->
    if (e.isPopupTrigger()){
        int row = jtable.rowAtPoint( e.getPoint() );
        jtable.changeSelection( row, 0, false, false );
        swing.popupMenu(menuItems).show(e.getComponent(), e.getX(), e.getY());
    } as java.awt.event.MouseListener)

  • JTable: Selecting rows in columns independently

    Dear all,
    I have a JTable with two columns. I want the user to be able to select cells in columns independently. At present, the entire row gets marked as selected. Is it possible at all to, for instance, select row1 1 to 3 in column 1 and rows 4 to 5 in column 2? If so, where's the switch? Thanks a lot in advance!
    Cheers,
    Martin

    Are you trying to use a seperate table for each column.
    Thats not a good idear.
    Here is what you have to do.
    1. Create a sub class of JTable
    2. You will have to redefine how the selection is done so. You will need some sort of a collection to store the list of selected cells indexes
    2.1 Selecting a cell is simply adding the coordinations of the cell to the selection
    2.2 de selecting is just removing it from the collection.
    2.3 Here is what you have to override
         setColumnSelectionInterval()
         setColumnSelectionInterval()
         changeSelection()
         selectAll()
         getSelectedColumns()
         getSelectedColumn()
         getSelectedRows()
         getSelectedRow() You migh also need few new methods such as
         setCellSelected(int row, int column, boolean selected);
         boolean isCellSelected(int row, int column);
         clearSelection();
         int[][] getSelectedCells();You will have to implement the above in terms of your new data structure.
    3. Handle mouse events.
    Ex:- when user cicks on a cell if it is already selected it should be deselected (see 2.2)
    other wise current selected should be cleared and the clicked cell should be selected
    if your has pressed CTRL key while clicking the the cell should be selected without deselecting the old selection.
    ---you can use above using a MouseListener
    When the user hold down a button and move the mouse accross multiple cell those need to be selected.
    --- You will need a MouseMotionListener for this
    You might also need to allow selection using key bord. You can do that using a KeyListener
    4. Displaying the selection
    You have to make sure only the selected cells are high lighted on the table.
    You can do this using a simple trick.
    (Just override getCellEditor(int row, int column) and getCellRenderer(int row, int column) )
    Here is what you should do in getCellRenderer(int row, int column)
    public TableCellRenderer getCellRenderer(int row, int column)
      TableCellRenderer realRenderer = super.getCellRenderer(int row, int);
      return new WrapperRenderer(realRenderer,selectedCellsCollection.isCellSelected(row,column));
    static class WrapperRenderer implements TableCellRenderer{
        TableCellRenderer realRenderer;
        boolean selected;
        public WrapperRenderer(TableCellRenderer realRenderer, boolean selected){
           this.realRenderer = realRenderer;
           this.selected = selected;
        public Component getTableCellRendererComponent(JTable table,
                                                   Object value,
                                                   boolean isSelected,
                                                   boolean hasFocus,
                                                   int row,
                                                   int column){       
            return realRenderer.getTableCellRendererComponent(table,value,selected,hasFocus,row,column);
    }What the above code does is it simply created wrapper for the Renderer and when generating the rendering component it replaces the isSeleted flag with our on selected flag
    and the original renderer taken from the super class will do the rest.
    You will have to do the same with the TableCellEditor.
    By the way dont use above code as it is becouse the getCellRenderer method create a new instance of WrapperRenderer every time.
    If the table has 10000 cells above will create 10000 instances. So you should refine above code.
    5. Finnaly.
    Every time the selection is changes you should make the table rerender the respective cells in or der to make the changes visible.
    I'll leave that part for you to figure out.
    A Final word
    When implementing th above make sure that you do it in the java way of doing it.
    For the collection of selected cells write following classes
    TableCellSelectionModel  // and interface which define what it does
    DefaultTableCellSelectionModel //Your own implementation of above interface the table you create should use thisby default
    //To communicate the selection changes
    TableCellSelectionModelListener
    TableCellSelectionModelEventif you read the javadoc about similer classes in ListSelectionModel you will get an idear
    But dont make it as complex as ListSelectionModel try to keep the number of methods less than 5.
    If you want to make it completly genaric you will have to resolve some issues such as handling changes to the table model.
    Ex:- Rows and colums can be added and removed in the TableModle at the run time as a result the row and column indexes of some cells might change
    and the TableCellSelectionModel should be updated with those changes.
    Even though the todo list is quite long if you plan your implementation properly the code will not be that long.
    And more importantly you will learn lots more by trying to implementing this.
    Happy Coding :)

  • JTable select row by double click, single click

    Hi all,
    I would like to double click on the row of the JTable and pop up a window for adding stuff, a single click for selecting the row and then in the menu bar I can choose to etither add, change or delete stuff. I try to use the ListSelectionModel but does not seems to distinguish between double or single click.
    Any idea, doc, samples?
    or I should not use ListselectionModel at all?
    thanks
    andrew

    Hi. I used an inner class. By using MouseAdapter u dont have to implement all methods in the interface..
    MouseListener mouseListener = new MouseAdapter()
    public void mouseClicked(MouseEvent e)
    if(SwingUtilities.isLeftMouseButton(e))// if left mouse button
    if (e.getClickCount() == 2) // if doubleclick
    //do something
    U also need to add mouselistener to the table:
    table.addMouseListener(mouseListener);
    As I said, this is how I did it.. There are probably alot of ways to solve this, as usual :). Hope it helps

  • 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

  • Looping the selected row in JTable

    By default, when the first row in a JTable is selected and the up arrow is pressed, the first row remains selected. What I need in this case is the selected row to change to the last row in the table, in effect creating a circular selection. I might have missed something in the API, but is there a way to (easily) change the default selection behavior?
    I have thought of adding a listener that would select the last row when the up arrow is pressed and the first row is selected, but it seems like a hack. Searching the web has provided little to no help.
    Does anyone know of an elegant way to do this? ...or can anyone provide any links that could be of help?
    Thanks!
    Glenn

    Thanks for the help! I made some minor changes to the code you provided because it was not allowing me to select the first and last row (it just skips them). Also, the row that is selected must be in edit mode in order for it to work.
    Here is the modified code. For simplicity, I just put the operations for the up and down arrow in the same method.
      protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
                                          int condition, boolean pressed) {
        // if pressed == false, no looping is needed, so perform default action
        if (!pressed)
          return super.processKeyBinding(ks, e, condition, pressed);
        // up arrow
        if (e.getKeyCode() == KeyEvent.VK_UP) {
          // if the current selected row is 0 or less, then loop.
          if (this.getSelectedRow() <= 0) {
            // if the cell is in edit mode, stop editing
            if (this.getCellEditor() != null)
              this.getCellEditor().stopCellEditing();
            int rowCount = this.getModel().getRowCount();
            this.getSelectionModel().setSelectionInterval(rowCount-1, rowCount-1);
            return true;
          } else {
            return super.processKeyBinding(ks, e, condition, pressed);
        } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
          // if the selected row is the last row, then loop
          if (this.getSelectedRow() >= (this.getModel().getRowCount() - 1) ) {
            // if the cell is in edit mode, stop editing
            if (this.getCellEditor() != null)
              this.getCellEditor().stopCellEditing();
            // loop the selection to the first row
            this.getSelectionModel().setSelectionInterval(0, 0);
            return true;
          } else {
            return super.processKeyBinding(ks, e, condition, pressed);
        } else {
          return super.processKeyBinding(ks, e, condition, pressed);
      }The above code does not attempt to restore the editor component when a new row is selected like the code you provided.
    Thanks again for providing such a thorough example!

  • How to delete the selected rows in a JTable on pressing a button?

    How to delete the selected rows in a JTable on pressing a button?

    You are right. I did the same.
    Following is the code where some of them might find it useful in future.
    jTable1.selectAll();
    int[] array = jTable1.getSelectedRows();
    for(int i=array.length-1;i>=0;i--)
    DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
    model.removeRow(i);
    }

  • Overriding the SelectionForegroundColor of a selected row in a JTable

    Hi
    First, apologize for my poor English.
    I looked for a similar topic in the forum, but coudn't find one.
    What I want to achieve is this :
    upon data contained in a column, I want the foreground color of the row to be gray. To do this, I write my own TableCellRenderer and it works perfectly except for the unique selected row of the table (single selection model) whose foreground color is the table's selectionForegroundColor.
    I found a workaround...but the code is awful and leads to OutOfMemoryErrors.
    Here is the code :
    <
    public Component getTableCellRendererComponent(JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus,
    int row,
    int column) {
         boolean isGrayColored = false;
         // some process to set whether the foreground color should be gray
         if (isGrayColored) {
              //table.setSelectionForeground(Color.gray);
              setForeground(Color.gray);
         } else {
              //table.setSelectionForeground(Color.black);
              setForeground((isSelected) ? table.getSelectionForeground() : table.getForeground());
         if (table != null && value == null && isSelected && hasFocus) {
              return this;
         } else {
              return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    >
    If I uncomment the lines "table.setSelectionForeground(..", I got the expected result.
    Thanks for your help
    Regards,

    Try this:
          public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
             if (isSelected && hasFocus) {
                setForeground(Color.black);
             } else {
                setForeground(Color.gray);
             setText((value==null)?"":""+value);
             return this;
          };o)
    V.V.
    PS: If it helps, don't forget the dukes!

  • The columns of a selected row in a JTable

    Hello guys,
    I am trying to loop through the columns of a selected row in a JTable. Any ideas how i can do that?
    Thanks in advance for your replies.
    Antana.

    there is getValueAt(int row, int column) method in JTable.
    will this help you?
    and please post swing related queries to swing forum.
    --Azodious_                                                                                                                                                                                                                                                                                                           

  • How to find out if JTable's selected row is visible?

    Hello there,
    Given:
    a JTable is inserted into a JScrollPane and the number of rows in the table is greater than the vieport size.
    A random row within the table gets programmatically selected.
    How to find out if the selected row is visible in a JTable visible area?
    Your help will be greatly appreciated.
    Tim

    That will make the row visible, but not answer whether it was visible
    in the first place. Try something like:
    public boolean isRowVisible( JTable table, int row ) {
        Rectangle rect = table.getBounds();
        int rowHeight = table.getRowHeight();
        int viewHeight = table.getParent().getHeight();
        int max = rect.y - viewHeight + 1;
        int rowPos = - rowHeight * row;
        return ( rect.y >= rowPos && rowPos > max );
    }assuming all rows have the same height.
    : jay

  • How to select rows in the inner JTable rendered in an outer JTable cell

    I have wrriten the following code for creating cell specific renderer - JTable rendered in a cell of a JTable.
    table=new JTable(data,columnNames)
    public TableCellRenderer getCellRenderer(int row, int column)
    if ((row == 0) && (column == 0))
    return new ColorRenderer();
    else if((row == 1) && (column == 0))
    return new ColorRenderer1();
    else
    return super.getCellRenderer(row, column);
    ColorRenderer and ColorRenderer1 are two inner classes, which implement TableCellRenderer to draw inner JTable on the outer JTable cell, having 2 rows and 1 column each.
    Now what is happening the above code keeps executing continously, that is the classes are being initialised continously, inner JTables are rendered (drawn) continously, and this makes the application slow after some time. It throws java.lang.OutOfMemoryException.
    WHY IS IT SO??? I can't understand where's the bug..
    Any advice please???
    Moreover i want selections in inner tables and not on outer table, how can this be possible.
    I am working on this since a long time but have not yet found a way out...

    With your help i have overcome the problem of continous repeatition.
    The major problem which I am facing is, in selecting rows in the inner rendered JTables.
    I have added listener on outer JTable which select rows on the outer JTable, hence the complete inner JTable which being treated as a row, gets selected.
    The thing is i need to select the rows of inner rendered JTables,not the outer JTable.
    How to go about it??
    I have even added listener to inner rendered JTables, but only first row of every table gets selected.
    Please help....
    Thanks in advance.

  • How to set the Selected row and Column in JTable

    Hi,
    i have a problem like the JTable having one Method getSelectedRow() and getSelectedColumn to know the Selected row and Column but if i want to explicitly set the Selected Row and Column,then there is no such type of Methods.If anybody has any solution then i will be thankful to him/her.
    Praveen K Saxena

    Is that what you're looking for? :myTable.getSelectionModel().setSelectionInterval(row, row);
    myTable.getColumnModel().getSelectionModel().setSelectionInterval(column, column);

  • (JTable) How can i get the first columns cell in a selected row?

    Hello. I am trying to figure out how i can get the first columns cell within a selected row no matter what cell is selected in that row. I have a class that extends AbstractTableModel which represents the table. Now i have another class that extends DefaultSelectionModel. Each model is added to the JTable via setModel(TableModel dataModel), setSelectionModel(ListSelectionModel newModel). Now i don't understand what i have to return from getMaxSelectionIndex(). Any ides? Thanks.
      class xTableModel extends AbstractTableModel{
         private static String[] cols;
         private Object[][] data;
            public void setTableModel(Object data[][], String[] cols){
             this.cols = cols;
             this.data = data;
            public String getColumnName(int col){
             return cols[col];
            public int getRowCount() {
             return data.length;
            public Object getValueAt(int row, int col) {
             return data[row][col];           
            public void setValueAt(Object value,int row,int col){
             data[row][col]=value;
            public int getColumnCount(){
             return cols.length;
    class ColumnListenerModel extends DefaultListSelectionModel{
         public int getMaxSelectionIndex(){}

    int row = table.getSelectedRow();
    Object data = table.getValueAt(row, 0);

  • Select row and column from header in jtable

    hello i have a problem to select row and column from header in jtable..
    can somebody give me an idea on how to write the program on it.

    Hi Vicky Liu,
    Thank you for your reply. I'm sorry for not clear question.
    Answer for your question:
    1. First value of Open is item fiels in Dataset2 and this value only for first month (january). But for other month Open value get from Close in previous month.
    * I have 2 Dataset , Dataset1 is all data for show in my report. Dataset2 is only first Open for first month
    2. the picture for detail of my report
    Detail for Red number:
    1. tb_Open -> tb_Close in previous month but first month from item field in Dataset2
    espression =FormatNumber(Code.GetOpening(Fields!month.Value,First(Fields!open.Value, "Dataset2")))
    2. tb_TOTAL1 group on item_part = 1
    expression =FormatNumber(Sum(CDbl(Fields!budget.Value)))
    3. tb_TOTAL2 group on item_part = 3 or item_part = 4
    expression =FormatNumber(Sum(CDbl(Fields!budget.Value)) + ReportItems!tb_TOTAL1.Value )
    4. tb_TOTAL3 group on item_part = 2
    expression =FormatNumber(Sum(CDbl(Fields!budget.Value)) - ReportItems!tb_TOTAL2 .Value)
    5. tb_Close -> calculate from tb_TOTAL3 - tb_Open
    expression =FormatNumber(Code.GetClosing(ReportItems!tb_TOTAL3.Value,ReportItems!tb_Open.Value))
    I want to calculate the value of tb_Open and tb_Close. I try to use custom code for calculate them. tb_close is correct but tb_Open is not correct that show value = 0 .
    My custom code:
    Dim Shared prev_close As Double
    Dim Shared now_close As Double
    Dim Shared now_open As Double
    Public Function GetClosing(TOTAL3 as Double,NowOpening as Double)
        now_close = TOTAL3 + NowOpening
        prev_close = now_close
        Return now_close
    End Function
    Public Function GetOpening(Month as String,NowOpen as Double)
        If Month = "1" Then
            now_open = NowOpen
        Else    
            now_open = prev_close
        End If
        Return now_open
    End Function
    Thanks alot for your help!
    Regards
    Panda A

  • Selecting Row in JTable

    Dear friends,
    When i select a whole row in JTable it gets selected but the background color of the row selected does not change. i.e. Its not highlighted as in MS-Excel.
    How can i overcome this problem?
    Kindly reply
    Thanks.

    Hi,
    Thanx for ur inputs. This is what the code i wrote. When u run this code,
    If we select row1 column1 the cells highlighted will be on row 2, 3 and 4. If we select row1 column 2 the selected cells will be on row 1, 3 and 4. I want the row to be selected fully when we select coumn 1 only.
    For eg. if i select row 200 from column 1 the 200 th row should only be fully highlighted
    Anyway i'll try the above code and check
    Here is the code
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class table1 extends JFrame
         // Variables declaration
         private JTable jTable1;
         private JScrollPane jScrollPane1;
         private JPanel contentPane;
         // End of variables declaration
         public table1()
              super();
                this.setVisible(true);
         private void initializeComponent()
              jTable1 = new JTable();
              jScrollPane1 = new JScrollPane();
              contentPane = (JPanel)this.getContentPane();
              jTable1.setModel(new DefaultTableModel(4, 4));
              jScrollPane1.setViewportView(jTable1);
              contentPane.setLayout(null);
              addComponent(contentPane, jScrollPane1, 58,65,301,207);
              this.setTitle("table1 - extends JFrame");
              this.setLocation(new Point(0, 0));
              this.setSize(new Dimension(473, 539));
         private void addComponent(Container container,Component c,int x,int
    y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         } Thanks again

Maybe you are looking for