About row selection in JTable

This is also a question about JTable, when type the key "ENTER", the row selection will focus on the next line, how can I stop this default action? Can I make the default action of pressing "ENTER" to be activate a cell in the JTable to editing state?
Thanks for any help.

Sorry, I need to ask for help again, yes, in your case, the method works,
but I am afraid this method does not help me, because I don't know HOW TO MAKE THE F2 FUNCTION in my case.
I use the method you recommend, and yes I can stop the default response of pressing ENTER, it means when I stroke ENTER in my table, the selection won't go to the next line, but it just up to my half purpose, how can I use Enter to editing a cell then? My silly question is I even don't know how to make F2 works?

Similar Messages

  • Disabling multiple row selection in JTable

    hi,
    I have a JTable and I want to disable the multiple row selection.
    I used
    getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);and this working fine with ctr+clicking on a row
    but if i am using shift key instead of Ctrl key multiple selection is possible....
    Any idea y?and how to resolve it??
    thnx
    ~neel

    Use table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);I don't know if it differs but I use it and I don't have the problems you describe. Might be a bug in your Java version?!
    Message was edited by:
    pholthuizen

  • How can I make a row selected in JTable?

    I want to make a row selected and highlighted in JTable programmatically.
    But, I couldn't find method like setSelected(int row).
    How can I do this?

    try this ....
    private void makeRowVisible(JTable table, int row) {
         java.awt.Rectangle cellRect = table.getCellRect(row, 0, true);
         if (cellRect != null) {
              table.scrollRectToVisible(cellRect);
    }

  • Multiple Row selection In JTable

    I am working with JTable and JList, I can transfer element from table to list and vise versa on clicking on button, my problem is that when i transferred element to either of them that should be selected. i can also transfer multiple item at time and doing sorting with table if i am adding element of 1st row and last row of table, both the rows should be selected.
    Any thoughts!!!!!!!!!!!
    ThnX
    Prashant_SDN

    Thnx for response and selection in list is done sucessfully.
    I have one additional query, I am transfering element from list to table and did use sorting so rows did not get added after existing row of table but added as per sorting.
    so how do i get the index of newly added row after sorting.
    Any thoughts!!!!

  • To get the unique id of the selected row in a JTable as in Database

    Hi,
    After fetching the recodrs from the Database, I have displayed them in a JTable. Though I fetched all the columns from db, I am displying only only 2 columns, say Name and Number neither of which is unique, however I have a unique ID for each record in the db. Now when I select some row in the JTable, I need to know its unique ID (the one which is in the db) which i have not displayed in the JTable.
    Is there any API method that can store the unique ids of a table? Or how can this be done?
    Thanks in Advance.

    Although, if you don't want the Id visible in the table, then you need to remove its TableColumn from the TableColumnModel.
    Then when you want to reference the id you need to use:
    table.getModel.getValueAt(...);

  • 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);
    }

  • 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

  • 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_                                                                                                                                                                                                                                                                                                           

  • A Listener For JTable Row Selection Changed?

    Never mind... Thought of a couple other things after I posted and found ListSelectionListener. This looks like it fulfills my requirement nicely. - cimmerian76
    >>>
    TableModelListener isn't what I am looking for here. Basically, I'm looking for something that behaves in a way that is analogous to
    TreeSelectionListener's valueChanged(...). Perhaps I'm looking in the wrong places, but the only things I've found were RowSet listener (not even close)
    and TableModelListener (not exactly what I'm looking for - I'm not concerned about data in the table changing).
    The tool I'm writing displays additional information about the object in the row selected in an adjacent panel.
    This display should change every time a user selects a different row.
    I can mimic the behavior I want using a mouse listener on the table, so this isn't an emergency.
    It's more about curiosity. If I can find something that produces this functionality directly, I would prefer to use that.
    <<<
    Message was edited by:
    cimmerian76

    Hi,
    you can use this to handle selection events for the table:
    yourTable.getSelectionModel().addListSelectionListener(... );
    Now e.g. the class containing your main can implement interface ListSelectionListener.

  • Custom JTable column (JCheckBox) not included in row selection.

    I am trying to use JCheckBox (for display only data) as one of my JTable columns. I have written custom cell renderer for the same. Every thing is working fine except that when I select a row, the new custom JCheckBox column is not included in selection. Here is the code that I am using.
        protected class CheckBoxColumnRenderer extends DefaultTableCellRenderer {
            JCheckBox ckb = new JCheckBox();
            public Component getTableCellRendererComponent(JTable table, Object value,
                        boolean isSelected, boolean hasFocus, int row, int column) {
                if (value instanceof Boolean) { // Boolean
                  ckb.setSelected(((Boolean) value));
                  ckb.setHorizontalAlignment(JLabel.CENTER);
                  ckb.setBackground(super.getBackground());
                  if (isSelected || hasFocus) {
                      ckb.setBackground(table.getSelectionBackground());
                return ckb;
        }How can I include the custom cell in the row selection.
    regards,
    nirvan.

    they have lots of dependencies and it is not always easy to strip out an SSCCE without a considerable effort.Exactly. And is the cause of the problem the dependencies or something else. The only way to know for sure is to strip out the code and simplify the problem, that way you truly understand what the problem is.
    The majority of time this can be done with minimal effort as in this case.
    Some times we are sure that the problem is with certain part of the code Is the problem the code or the way the code is invoked? How do we know the TableModel is created properly or that the column class is overwritten correctly when we can't see it?
    someone having a third look at it may actually find the enhancement required with ease.Exactly, but we need to see the big picture.
    So are you sure that I should post an SSCCE with every possible question where coding is involved ?In the majority of cases a SSCCE is easily created in 5-10 minutes, so if you want the fastest help then yes.
    Just twice this past week I was ready to ask a question on the forum and was preparing a SSCCE to post and sure enough both times the creation of the SSCCE caused me to look at the problem differently and I solved it. I would much rather solve a problem on my own then post a question and wait for hours (days) hoping someone else knows the answer.

  • How to select more than one row in a JTable swing adf adf?

    how to select more than one row in a JTable swing adf adf?

    // Allow selection to span one contiguous set of rows, visible columns, or block of cells
    table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    // Allow multiple selections of rows, visible columns, or cell blocks
    table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

  • How to select a particular row in a JTable?

    I want to select a particular row in a JTable. i.e something like
    table.setSelectedRow(arg)how can i do it.

    You can use
    table.getSelectionModel().setwhateverIsInTheAPI(...)
    depending on your selection mode.Thanx,
    but i don't want to change the selectionMode, i
    want to select a particular row thro program.
    This is like list.setSelected(index) in
    JListThe original poster was pointing you in the right direction. You have to use the SelectionModel when you want to work with the selected indexes of a JTable. It will return a ListSelectionModel, which will be an instance of DefaultListSelectionModel unless you implemented your own. Refer to the API for the appropiate method(s).
    http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/ListSelectionModel.html

  • Multi Jtable row selection

    I am trying to allow a multi Jtable selection :
    In a JPanel, boxlayout, I have many Jtables aligned with the Y AXIS (one below the other). They have the same model and what I want is to be able, when I drag an area with the mouse, to select all the rows that are into this area event if the area covers many JTables.
    In other words, the user must be able to select rows from differents Jtables as if there was only one Jtable at all.
    Do seomeone has an Idea ?
    chmurb

    I must be doing something wrong as both not working for me...:
    On the change width - no effect at all:
            Table temp = new Table(cust.getData() , vtrColumn );
            TableColumnModel col = temp.getColumnModel();
            TableColumn tcol = col.getColumn(0) ;
            tcol.setPreferredWidth(10); // tried any other number as well...
            rtrvTable.setModel(temp.getModel());
            rtrvTable.repaint();and on the remove column - it removes it completly - not only hiding it, so I cannot get the value at the column (which I need as it is the PK of the tabe)
            JTable temp = new JTable(cust.getData() , vtrColumn );
            rtrvTable.setModel(temp.getModel());
            TableColumn col0a = rtrvTable.getColumnModel().getColumn(0);
            rtrvTable.removeColumn(0);
            System.out.println(temp.getWidth());
            rtrvTable.repaint();Is there a way only to hide it? if I can set the with to very nerrow - that can be good enough I think....

  • JTable - make 1st row selected by default

    hi,
    i have a JTable, how can i make the 1st row selected by default?
    thanks.

    try table.getSelectionModel().setSelectionInterval(0, 0)
    You need to check and make sure there is at least one row in the table before you do this, otherwise exception will throw.
    Hope this will help.

  • Select multiple rows on a JTable

    Hi!
    Given: JTable, multiple selection allowed
    Wanted: a way to be able to set multiple non-continuous rows selected
    eg. on a JTable with 5 rows,
    I want to set rows 1, 3 and 5 selected
    Anyone?
    Stoffel.

    table.setSelectionMode(ListSelectionModel.MULTIPLE_INTE
    VAL_SELECTION);
    select rows using <ctrl> and/or <shift>Or if you want to set programaticly use this methods, see the api
    for explanation.
    table.changeSelecton(int row, int column, boolean toogle, boolean extend);
    table.addRowSelection(int index0, int index1);
    table.addColumnSelectionInterval(int index0, int index1)
    ...

Maybe you are looking for