Selecting Text in a JTable

Hi,
I have an application that uses a JTable with editable cells. When the user clicks a cell, I would like the cell's data to become highlighted. In other words, I don't just want the cell to get focus, I want the existing text within the cell to be selected.
Any thoughts on this? I'd be forever grateful (or at least for a few hours...)
Thanks,
-sheepy.

Just in case anybody is interested, when you click on a table cell, the table cell editor is being used, not the cell editor.
Its simply a matter of setting a textfield for that cell editor and setting setEditable to false.
The user can then select the text, but not edit it. Works perfectly.
J

Similar Messages

  • Selecting text in a JTable renderer?

    Hi all,
    I have a JTable with some non-editable cells. I don't want the user to be able to change these values, but I want the user to be able to select the text and copy it. I can''t seem to be able to do this with the default cell renderers, as they subclass JLabel and you can't select text in the JLabel (or can you?)
    Anybody else have this problem?
    I also tried to create my own table renderer by subclassing a JTextField, but when I call setText in the "getTableCellRendererComponent" method, it doesn't seem to set the text of the text field. Well it does, because I can then call getText() and that works fine, but it doesn't appear in the JTable.
    any suggestions greatly appreciated,
    J

    Just in case anybody is interested, when you click on a table cell, the table cell editor is being used, not the cell editor.
    Its simply a matter of setting a textfield for that cell editor and setting setEditable to false.
    The user can then select the text, but not edit it. Works perfectly.
    J

  • How to catch selected text in JTable Column

    Hi there,
    I am learning JTable. Need help for How to get the selected text from the JTable Column which is set to be editable.
    for example in JTextFiled you have method on getSelectedText(), is there any method for tracking the selected text.
    Thanks in advance
    Minal

    Here's an example of the model I used in my JTable. Not the "getValueAt" method & "getRecordAt" method. You will have to have a Record object - but it only contains the attributes of an inserted record (with appropriate getters & setters). Hope this helps.
    public class FileModel5 extends AbstractTableModel
    public boolean isEditable = false;
    protected static int NUM_COLUMNS = 3;
    // initialize number of rows to start out with ...
    protected static int START_NUM_ROWS = 0;
    protected int nextEmptyRow = 0;
    protected int numRows = 0;
    static final public String file = "File";
    static final public String mailName = "Mail Id";
    static final public String postName = "Post Office Id";
    static final public String columnNames[] = {"File", "Mail Id", "Post Office Id"};
    // List of data
    protected Vector data = null;
    public FileModel5()
    data = new Vector();
    public boolean isCellEditable(int rowIndex, int columnIndex)
    // The 2nd & 3rd column or Value field is editable
    if(isEditable)
    if(columnIndex > 0)
    return true;
    return false;
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c)
    return getValueAt(0, c).getClass();
    * Retrieves number of columns
    public synchronized int getColumnCount()
    return NUM_COLUMNS;
    * Get a column name
    public String getColumnName(int col)
    return columnNames[col];
    * Retrieves number of records
    public synchronized int getRowCount()
    if (numRows < START_NUM_ROWS)
    return START_NUM_ROWS;
    else
    return numRows;
    * Returns cell information of a record at location row,column
    public synchronized Object getValueAt(int row, int column)
    try
    FileRecord5 p = (FileRecord5)data.elementAt(row);
    switch (column)
    case 0:
    return (String)p.file;
    case 1:
    return (String)p.mailName;
    case 2:
    return (String)p.postName;
    catch (Exception e)
    return "";
    public void setValueAt(Object aValue, int row, int column)
    FileRecord5 arow = (FileRecord5)data.elementAt(row);
    arow.setElementAt((String)aValue, column);
    fireTableCellUpdated(row, column);
    * Returns information of an entire record at location row
    public synchronized FileRecord5 getRecordAt(int row) throws Exception
    try
    return (FileRecord5)data.elementAt(row);
    catch (Exception e)
    throw new Exception("Record not found");
    * Used to add or update a record
    * @param tableRecord
    public synchronized void updateRecord(FileRecord5 tableRecord)
    String file = tableRecord.file;
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    boolean addedRow = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    { //update
    data.setElementAt(tableRecord, index);
    else
    if (numRows <= nextEmptyRow)
    //add a row
    numRows++;
    addedRow = true;
    index = nextEmptyRow;
    data.addElement(tableRecord);
    //Notify listeners that the data changed.
    if (addedRow)
    nextEmptyRow++;
    fireTableRowsInserted(index, index);
    else
    fireTableRowsUpdated(index, index);
    * Used to delete a record
    public synchronized void deleteRecord(String file)
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    data.removeElementAt(i);
    nextEmptyRow--;
    numRows--;
    fireTableRowsDeleted(START_NUM_ROWS, numRows);
    * Clears all records
    public synchronized void clear()
    int oldNumRows = numRows;
    numRows = START_NUM_ROWS;
    data.removeAllElements();
    nextEmptyRow = 0;
    if (oldNumRows > START_NUM_ROWS)
    fireTableRowsDeleted(START_NUM_ROWS, oldNumRows - 1);
    fireTableRowsUpdated(0, START_NUM_ROWS - 1);
    * Loads the values into the combo box within the table for mail id
    public void setUpMailColumn(JTable mapTable, ArrayList mailList)
    TableColumn col = mapTable.getColumnModel().getColumn(1);
    javax.swing.JComboBox comboMail = new javax.swing.JComboBox();
    int s = mailList.size();
    for(int i=0; i<s; i++)
    comboMail.addItem(mailList.get(i));
    col.setCellEditor(new DefaultCellEditor(comboMail));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for mail Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Mail Id to see a list of choices");
    * Loads the values into the combo box within the table for post office id
    public void setUpPostColumn(JTable mapTable, ArrayList postList)
    TableColumn col = mapTable.getColumnModel().getColumn(2);
    javax.swing.JComboBox combo = new javax.swing.JComboBox();
    int s = postList.size();
    for(int i=0; i<s; i++)
    combo.addItem(postList.get(i));
    col.setCellEditor(new DefaultCellEditor(combo));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for post office Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Post Office Id to see a list of choices");
    }

  • How to get selected text values in a textarea by mouse click?

    Hi Everyone,
    What I am trying to do is to click on some texts in a textarea, then get the selected text value.
    If you guys have used an accounting software called Simply Accounting, you might understand better.
    I list all my customer names in a textarea. What I want is, when I click on one customer, another GUI pops up with this customer's information. My problem is that I don't know how to get the selected text value from a textarea.
    Could anyone give a hand here? Thank you in advance.

    Is there some reason you aren't using a JList or
    JTable to display
    the user names/information?Thank you for es5f2000's reply. You just gave me a better idea! There is not a particular reason I have to use TextArea to list my customers. As long as the component can make my idea alive, I definitely use it. Still, if there is any way to get a selected text value, it will help me a lot with my project. Thank you.

  • 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

  • Can no longer select text in email template or read only field with mouse using IE or Firefox?

    Hi Guys,
    I can no longer select text in email template or read only field using my mouse in IE or Firefox anymore. We are using CRM 2011 rollup 18 applied with IE 11 and the latest version of Firefox. We only applied roll up 18 in Feb when this issue began.
    Thanks
    Dave
    David Kelly

    When you have a problem with one particular site, a good "first thing to try" is clearing your Firefox cache and deleting your saved cookies for the site.
    (1) Bypass Firefox's Cache
    Use Ctrl+Shift+r to reload the page fresh from the server.
    (You also can clear Firefox's cache completely using:
    orange Firefox button ''or'' Tools menu > Options > Advanced
    On the Network mini-tab > Cached Web Content : "Clear Now")
    (2) Remove the site's cookies (save any pending work first) using either of these. While viewing a page on the site:
    * right-click and choose View Page Info > Security > "View Cookies"
    * Alt+t (open the classic Tools menu) > Page Info > Security > "View Cookies"
    Then try reloading the page. Does that help?
    These features rely on JavaScript, and it sounds as though you have scripting enabled if you get (the wrong) color changes. Some add-ons might alter the way scripts operate, so a standard diagnostic to bypass interference by extensions (and some custom settings) is to try Firefox's Safe Mode.
    First, I recommend backing up your Firefox settings in case something goes wrong. See [[Backing up your information]]. (You can copy your entire Firefox profile folder somewhere outside of the Mozilla folder.)
    Next, restart Firefox in Firefox's Safe Mode ([[Safe Mode]]) using
    Help > Restart with Add-ons Disabled
    In the dialog, click "Start in Safe Mode."
    If those features work correctly, this points to one of your extensions or custom settings as the problem.
    To also disable plugins, you can use this page:
    orange Firefox button ''or'' classic Tools menu > Add-ons > Plugins category
    Any change?

  • Select text from all_views returns an empty string

    My application allows the user to select between the Data Provider for ODBC and the Data Provider for Oracle. (ODP)
    When using the ODBC provider the statement:
    Select text from all_views where view_name='MYVIEW'
    returns the expected string.
    If I connect via ODP however it returns an empty string.
    (If I use 'Select *' it tells me the text_length is 154 in this specific case - so there is definately text available.)
    I'm thinking it has something to do with the fact that the data type is LONG.
    In both cases I retreive the data using rdr.GetChars(), which should work.
    If I use the dbms_metadata.get_ddl function instead, it does return the string (Probably because the return type is not LONG)
    Unfortunately that function only works for Views in the current schema, while the original Select works for any view.
    (And I dont know what version of Oracle this function was added in - I have to support older versions too.)
    Similarly, if I use one of the XML functions to retreive the text as XML it works fine.
    (Again it is probably returned as a VARCHAR2 instead of a LONG.)
    The strange thing is that when I created my own table containing a LONG column I was able to load and retreive data without any problems.
    The problem appears to be specific to this column in all_views.
    Anyone know a solution to this?
    Thanks
    Mike

    Thanks that was it.
    I had not seen those properties since I am working with the 'generic' objects (DbCommand rather than OracleCommand, etc.)
    What is strange is that I was able to retreive data from my own LONG column WITHOUT setting this value to -1.
    (It defaulted to 0 in both cases.)
    The only difference was that when I retreived data from my own column I specified CommandBehaviour.SequentialAccess.
    When I retreived the all_views.text column I did not specify a behaviour at all.
    However the Oracle docs said that SequentialAccess is not supported ... so I guess that is not correct.
    (Maybe it doesn't 'work', but it certainly seems to cause things to work differently)
    Thanks
    Mike

  • Print/Save Selected Text to PDF

    I want to use Mozilla Firefox very much for a long time. I like it because the UI is very clean, easy to use, the icon vey pretty. When I use in my Android Mobile, it is very easy and intelligent to select content of page site. Very good!
    But I had to install Chrome instead so I've always been using "Print a selected content to PDF" but I couldn't find ways to do that with Firefox. Chrome is doing very good.
    I searched all add-ons, pdf printer software but they are only saving or printing all the page (website) to PDF.
    Please help me the ways to save a selected content to PDF. Thanks very much.

    Hii hanh01001..
    I think i know one solution to the problem
    https://addons.mozilla.org/en-US/firefox/addon/print-selected-text/?src=api
    this is an add on that is used to print the selected text only..
    have a nice day :) :)
    ---Thanks tracy :)

  • Create a dynamic form where selected text boxes appears, based on options chosen in a drop-down box

    HELP!!! Can anyone please provide some guidance on how to create a dynamic form where selected text boxes appears, based on options chosen in a drop-down box.
    I have a form which – based on the department that's selected from a drop-down box – will have different form fields/text boxes, etc, made available.
    Is this possible in LiveCycle, if so, can you please provide the script/info - as needed.
    Thanks,

    In the preOpen event of the second dropdown list you put something like (in formCalc):
    if (dropdown1 == 1) then
    $.clearItems()
    $.setItems("Year, 2 Year,  3 Year")
    elseif (dropdown1 == 2) then
    $.clearItems()
    $.setItems("3 Year,  4 Year")
    endif

  • How to select text from a webpage

    hi. i have firefox for my n900. i would like to know how to select some text from a webpage so i can copy and paste it. thanks for the help. i couldn't it anywhere.

    First tap where you want the selection to start. (It might help to zoom in as far as possible first. You can do this using the volume buttons in the newly-released Firefox 1.1rc1.) Then hold the Shift key while pressing the arrow keys on the N900 keyboard to select text.
    Note: We are aware that this is not a very user-friendly way to select text, and we hope to include a better design in a future version of mobile Firefox.

  • Get selected text from af:inputText

    Hi,
    I am using an <af:inputText> component, within which I would want to know if any text has been selected.
    InputText.getValue() would give me the total value that is there within the inputText component. But if I have selected a part of the text, I would like to get hold of that.
    Is there a way in ADF, to get that selected Text ?
    Thanks,
    Pawan.

    Hi,
    If I am to use javascript, can i directly use the IE/FF (browser-specific) code to get hold of the selected text ?
    The ADF javascript API doesn't seem to have a way to get the selected text.
    Thanks,
    Pawan.

  • Why does my cursor not automatically select the entire word when I try to select text by starting/ending in the middle of a word?

    In any other browser I've used (or word processor, for that matter) when I select text using my mouse cursor, if I start and/or end in the middle of a word, it automatically selects the whole word when I'm selecting more than one word. But for some reason this is not happening in Firefox. If I try to select say 3 words, and I start in the middle of the first word and end in the middle of the last word, it will only select those parts, not all 3 words entirely.

    Firefox allows to select part of a word. You can select a word with a double click and use Shift + left click to set the end of the selection, so you need to click at the end of the last word instead of in it.

  • Problem with focus and selecting text in jtextfield

    I have problem with jtexfield. I know that solution will be very simple but I can't figure it out.
    This is simplified version of situation:
    I have a jframe, jtextfield and jbutton. User can put numbers (0-10000) separated with commas to textfield and save those numbers by pressing jbutton.
    When jbutton is pressed I have a validator which checks that jtextfield contains only numbers and commas. If validator sees that there are invalid characters, a messagebox is launched which tells to user whats wrong.
    Now comes the tricky part.
    When user presses ok from messagebox, jtextfield should select the character which validator said was invalid so that user can replace it by pressing a number or comma.
    I have the invalid character, but how can you get the focus to jtextfield and select only the character which was invalid?
    I tried requestFocus(), but it selected whole text in jtextfield and after that command I couldn't set selected text. I tried with commands setSelectionStart(int), setSelectionEnd(int) and select(int,int).
    Then I tried to use Caret and select text with that. It selected the character I wanted, but the focus wasn't really there because it didn't have keyFocus (or something like that).
    Is there a simple way of doing this?

    textField.requestFocusInWindow();
    textField.select(...);The above should work, although read the API on the select(...) method for the newer recommended approach on how to do selection.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)",
    see http://homepage1.nifty.com/algafield/sscce.html,
    that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the "Code Formatting Tags",
    see http://forum.java.sun.com/help.jspa?sec=formatting,
    so the posted code retains its original formatting.

  • How can I make a fillable table that allows me to select text in bulk yet retains tab over ability?

    I'm working on a form in livecycle and am trying to make a form which is easy for my client to fill out and easy for me to extract the data from.
    Basically I am desiging a form that my clent fills out by entering data into 4 X 3 table (four rows, three columns).  In this form they will put names in the first column,  countries in the second column, and account numbers in the third coloumn.
    While this is not too hard to do, what I would really like to do is make it so that when I extract this data from the form I can easily select all the names in the first column at once, all the countries listed in column two at once, and then the same for column three. I'm placing this data into a word file for use in a mail merge table, so it just streamlines it all if I can highlight everything in one column at once rather than having to select every name/country/account number separately. (And before I get criticized for being lazy, haha, I will be duplicating this 4X3 table at least 7-8 times, as each table will have information specific to other criteria in the form.)
    I've realized that Adobe doesn't seem to let me bulk select text in multiple text boxes, yet because I'm working with a table I'm wondering if there's something I'm missing that would allow me to do this, or perhaps there's even another better way to do this job.
    Thank you for your help and I apologize if this is a bit confusing!

    You may have already gotten an answer for this since it was a bit ago, but if you have Adobe Acrobat Pro you can save all of your forms you collect into one folder, saved with individual file names so they will not over-write one another and then in Acrobat click Forms>Manage Form Data>Merge Data Files into Spreadsheets. It walks you through it from there and you can Select All of your saved files and it will generate the spreadsheet for you and you can do what you wish in Excel. Hope this helps!

  • Why selecting text and hitting F1 doesn't go to specific help page anymore?

    Hi. Up until a while ago I was able to, while working on some code,  select a particular actionscript component such as a Class, function or  property and hit the F1 key which would immediately bring up Adobe Help  in my internet browser already showing the page relevant to my  selection. For example, if I had selected the word "MovieClip" in my  code and hit F1, the Adobe Help page describing the MovieClip class  would come up, without me having to navigate to it.
    Now (for some weeks actually), it no longer does that. When I hit F1,  Adobe Help comes up in my browser, but opens at a general menu page  regardless of what text I select, which in fact makes selecting text  before hitting F1 redundant anyways.
    Does anyone know anything about this?
    It was so much more convenient before! Now I have to search for what I'm  looking for every time. I'm learning on my own, so I find myself going  to the Help pages quite often. At the end of the day, it sums up to be a  lot of typing and searching and pages to navigate through. Also, it  seems that navigating through the Adobe Help pages is kind of slow which  just makes it even more of a drag.
    I'd appreciate any information on this, or possibly some help in how to get things back to how they were.
    Thanks!

    try to install :
    http://www.adobe.com/support/chc/

Maybe you are looking for