Cells and JTable

Yes! I'm back again...
This time, I will like to know how to get the text in a cell of a JTable component wrapping on to multiple lines as the escape characters \n and \r ain't working.
Thank you.
William

First, you're supposed to use the line-separator system property anyway. Second, you might need a custom cell renderer. Maybe you should rather ask a Swing question at the Swing forum.

Similar Messages

  • How to know the row and col numbers of a cell in JTable at mouseclicked

    Hi, I'm coding an app using swing and JTable, in this table I will display the records from a database, now, each time the user has click in any cell I want to display it value, whit this method:
        private void setpuntero(JTable table, int row, int col){
            Object o = table.getValueAt(row, col);
            System.out.println("Valor de la celda: "+o.toString());
    }The mouseclick event was coded like this:
                table.addMouseListener(new MouseAdapter() {
                    public void mouseClicked(MouseEvent e) {
                        setpuntero(table, 1, 3);
                });My question is:
    how in the mouseClicked I can pass to setpuntero() method the dynamic values of the cell that the user clicked?
    In this example, setpuntero(table, 1, 3); I have chosen the cell(1,3) to display the value, but really I don't know how to capture those values dinamically using the mouse click
    Regards
    Herbert

    perhaps:
          public void mouseClicked(MouseEvent e)
            int row = table.getSelectedRow();
            int col = table.getSelectedColumn();
            String selected = table.getValueAt(row, col).toString(); // this will need to be changed if not String data
          }

  • Tab between cells and Editor in JTable

    I placed a cell editor in a JTable column JTextField.
    After I type something in this editor and press tab it stays in the same cell and when I press tab again then it goes to the next column.
    How can I correct this so that after I type something in the cell and press tab I want it to go to the next column directly in JTable.
    Thanks.

    I'd have to see your code to tell you what's wrong. I tried it this way and had no problem.
    TableColumn tc = table.getColumnModel().getColumn(2);
    tc.setCellEditor(new DefaultCellEditor(new JTextField()));by the way, I don't think you need to explicitly set the cell editor component to JTextField. It uses that by default.

  • Tab between cells and celleditor in JTable

    I placed a cell editor in a JTable column JTextField.
    After I type something in this editor and press tab it stays in the same cell and when I press tab again then it goes to the next column.
    How can I correct this so that After I type something in the cell and press tab I want it to go to the next column directly in JTable.
    Thanks.

    I'd have to see your code to tell you what's wrong. I tried it this way and had no problem.
    TableColumn tc = table.getColumnModel().getColumn(2);
    tc.setCellEditor(new DefaultCellEditor(new JTextField()));by the way, I don't think you need to explicitly set the cell editor component to JTextField. It uses that by default.

  • Problem with setCursor for JButton in cell on JTable

    i have a problem with setCursor to JButton that is in a cell of the JTable}
    this is the code
    public class JButtonCellRenderer extends JButton implements TableCellRenderer {
    public JButtonCellRenderer() {
    setOpaque(true);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    if (isSelected) {
    setForeground(table.getSelectionForeground());
    setBackground(table.getSelectionBackground());
    else {
    setForeground(table.getForeground());
    setBackground(Color.WHITE);
    setBorder(null);
    if(table.getValueAt(row,column) == null){
    setText("");
    if(isSelected){
    setBackground(table.getSelectionBackground());
    }else{
    setBackground(Color.WHITE);
    }else{
    if(table.getValueAt(row,column) instanceof JButton){
    JButton _button = (JButton)table.getValueAt(row,column);
    if(_button.getText().trim().equals("")){
    setText("<html>"+ "<font size=\"3\" COLOR=\"#0000FF\"><u><b>Ver...</b></u></font>"+"");
    }else{
    setText("<html>"+ "<font size=\"3\" COLOR=\"#0000FF\"><u><b>" + _button.getText() + "</b></u></font>"+"");
    return this;
    }

    Not quite sure I understand the problem, but I guess you have tried to call setCursor on your renderer and found it didn't work? The reason, I think, is that the renderer only renders a JButton. The thing that ends up in the table is in fact only a "picture" of a JButton, and among other things it won't receive and interact with any events, such as MouseEvents (so it wouldn't know that the cursor should change).
    There are at least two alternatives for you: You can perhaps use a CellEditor instead of a CellRenderer. Or you can add a MouseListener to the table and then use the methods column/rowAtPoint to figure out if the cursor is over your JButton cell and change the cursor yourself if it is.

  • How to change the Background color of a cell in JTable

    hi!
    Actually i want to change the background color of few cells in JTable
    is there any method to make this change in JTable ?
    and also is it possible to have 5 rows with single column and 5 rows with 3 columns in a single JTable

    i want to change the background color of few cells in JTableDepending on your requirements for the coloring of cells it may be easier to override the prepareRenderer() method of JTable:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=610474

  • Setting Focus to a particular cell in JTable

    Hi, can i know how to set the focus to a particular cell in JTable.
    Say I have a table with 2 rows and 10 columns. The focus now is at position (1, 9) which is the last cell in the table. But I want to set the focus to (1, 3). How can i achieve this ? Pls help. Thanks

    OK. It's partially working. The right methods to use are setRowSelectionInterval and setColumnSelectionInterval. Jeanette was right. Mine didn't work because of a thread issue. I put the those two methods in a block such as:
    SwingUtilities.invokeLater(new Runnable(){
    public void run()
    table.setRowSelectionInterval(tblLineItem.getRowCount()-1,
    table.getRowCount()-1);
    table.setColumnSelectionInterval(0,0);
    Then it worked.
    But after I finished editing the first cell of the newly created row and press ENTER, the selection went back to the cell that's next to the originally editing cell on the first(old) row, instead of staying at the current row and going to the second cell.
    Can anybody shed a light on what I'm missing?

  • How to disable a particular cell in JTable ?

    I having a problem on how to set disable a particular cell in JTable. At the first place to load the JTable, I want to set some of the cell to disabled, it only will run at the first time, is there anyway to do it ?

    This is the function that disable/enable cells in JTables.
    Are you looking for this?
    public boolean isCellEditable(int row, int col)
      if(((new Integer((String)(getValueAt(row,0)).toString()).intValue()>9))&&(col==1))
        return true;
      if(row!=4&&col!=5)
        return true;
      return false;
         this metod belong to the TableModel function
    and what I gave you is only an example of what you can do with it.
    if it return false it disable and if true it enable the cell...but I think this you allready know!
    Regards Amnon

  • Default behaviour of the Escape key while editing a cell in JTable??

    Hi all,
    i have a Jtable which get its data from an own model object which extends DefaultTableModel.
    If i overwrite the isCellEditable(row, col) method within the tablemodel object and set a specific column to editable, then i notice while editing a cell in that column that the default behaviour of the Escape key is that independet from what you have entered before in to the cell the editing stops and the cell gets the value it had before editing.
    This is the case for me even if i apply a custom editor to a column (one that extends DefaultCellEditor). It is just a JTextField that limits the number of digits a user can enter. Everything works fine. If the user edits the cell and presses ENTER or the "down arrow key" i can check what he has entered with the help of the getCellEditorValue() method. But if the user hits the ESC key after editing a cell this method is not invoked!!!
    My question is :
    is there any way to detect that the user cancels editing with the ESC-key.
    this is very important for me because if the user goes editing the cell i lock the related record in the database, if i cannot detect this it is locked till the application terminates.
    Thanks for any help in advance

    I try override the JTable editingCanceled() ==> does not work.
    I try the addCellEditorListener( CellEditorListener l ) ==> does not work.
    Finally, I try the addKeyListener ==> it works.
    Here is a quick demo. program:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class Test {
    public static void main(String[] args){
    JFrame f = new JFrame();
    String[] colName = {"a", "b"};
    String[][] rowData = {{"1", "2"}, {"3", "4"}};
    JTable table = new JTable(rowData, colName);
    JTextField t = new JTextField(10);
    t.setBackground(Color.red);
    t.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
    // do what ever you want ex. un-lock table
    System.out.println("ESCAPE");
    DefaultCellEditor editor = new DefaultCellEditor(t);
    TableColumnModel colModel = table.getColumnModel();
    for (int i = colModel.getColumnCount()-1; i >= 0; i--) {
    colModel.getColumn(i).setCellEditor(editor);
    f.setContentPane(new JScrollPane(table));
    f.pack();
    f.setVisible(true);

  • What component is placed default in each cell of JTable?

    Hi,
    What component is placed default in each cell of JTable?

    It depends on the content, see How to Use Tables - Concepts: Editors and Renderers for details.

  • Setting the backgroundcolor of cell of JTable

    Hi
    My Problem is.
    I have a JTable with 2 columns ( Rows can be 1-10 depending upon the size of
    input vector)
    I have provided two button in my Frame
    1)Update Row
    2) Update whole Table.
    Now i want I want that if a user makes a change in any cell say cell( row
    3,Col 1) ;and moves to next row , then the color (background/foreground) of
    that cell should change to any other color .Again if he presses any of the
    button then the default color of the cell should be restored.Basically i
    want to indicate the user that he has made changes in the cell and he needs
    to press the button for updation
    Regards
    Aminur

    You need to write your own TableCellRenderer if you want to control how individual table cells appear. Look in the How to Use Table tutorial if you haven't already done that; you'll find a link to it in the API documentation for the JTable class. And in that renderer, if you use a JLabel to render the cell, remember that a JLabel defaults to being transparent, i.e. you can't see its background. Use "setOpaque(true)" if you want to control the background colour.

  • Problem with select all cells in JTable

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

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

  • Merge cells in JTable.......

    Plz some help me out ......i want to merge two consecutive cells of a row in one cell in JTable......... how to do that.....give some code if possible....

    Well, as a new member you should learn to search the forum first before posting questions. Using keywords like "jtable merge cell" will find other postings on this topic. Some with solutions some without, so you will need to read a few and decide on the approach you want to take.

  • Aligning the Text in Centre for MultiLine Cells in JTable

    Hi;
    Does anyone know how I could make a java table that has multiline text cells AND this multiline text is aligned to center? I tried to extend JTextArea and to implement TableRenderer - multiline was OK but it did not do anything on setHorizontalAlign. If I extend DefaultTableRender than I can align the text to center but I got no multiline...
    Any ideas?
    Kindly to provide me a solution for this its urgent.

    Hi;
    Thanks for the reply,on using Text Area as renderer i.e using Multi-Line cells in JTable, i achieved the objective of displaying the text on multiple lines in the cell."In my Table there are 5 columns and i'm setting renderer on 3rd and 5th column,If the text is too large in column 5 it automatically gets wrapped off for all the cells in column 5.For column 3 my text is not so large as compared to column 5 and due to which the Text in the column 3 starts from the top for all the cells i.e (the first row in column 3 is parallel to first row in column 5 ),Now the problem is i can't display the text in the center of all cells for Column 3 .
    Thanks in advance

  • Text position in a cell in JTable?

    hello experts!!
    how can i center(horizontal) position/left/right justified a text in a cell in JTable?
    plz help.. tnx in advance!

    kagaw3000 wrote:
    ok i got it!
    But i am really confuse in JTable tutorial. it uses JLable as a CellRenderer and JButton as a CellEditor
    then it returns a Color.
    for clarification, when i am editing a cell, CellEditor will takes place, right? and when customizing the display of a cell, CellRendere will takes place, right?
    There is a very good explanation at the beginning of the Concepts: Editors and Renderers section in the tutorial.
    can you show me code that get and return a String not a Color.class?The default editor GenericEditor of JTable uses a JTextField which returns a String:
    static class GenericEditor extends DefaultCellEditor {
        Class[] argTypes = new Class[]{String.class};
        java.lang.reflect.Constructor constructor;
        Object value;
        public GenericEditor() {
            super(new JTextField());
            getComponent().setName("Table.editor");
        public boolean stopCellEditing() {
            String s = (String)super.getCellEditorValue();
            // Here we are dealing with the case where a user
            // has deleted the string value in a cell, possibly
            // after a failed validation. Return null, so that
            // they have the option to replace the value with
            // null or use escape to restore the original.
            // For Strings, return "" for backward compatibility.
            if ("".equals(s)) {
                if (constructor.getDeclaringClass() == String.class) {
                    value = s;
                super.stopCellEditing();
            try {
                value = constructor.newInstance(new Object[]{s});
            catch (Exception e) {
                ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));
                return false;
            return super.stopCellEditing();
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected,
                int row, int column) {
            this.value = null;
            ((JComponent)getComponent()).setBorder(new LineBorder(Color.black));
            try {
                Class type = table.getColumnClass(column);
                // Since our obligation is to produce a value which is
                // assignable for the required type it is OK to use the
                // String constructor for columns which are declared
                // to contain Objects. A String is an Object.
                if (type == Object.class) {
                    type = String.class;
                constructor = type.getConstructor(argTypes);
            catch (Exception e) {
                return null;
            return super.getTableCellEditorComponent(table, value, isSelected, row, column);
        public Object getCellEditorValue() {
            return value;
    }

Maybe you are looking for

  • How to contact the author of an application on the iPhone AppStore?

    Is there a link on the iPhone AppStore to send questions or suggestions to the developer of an application? (If not, why isn't there one? )

  • FRM 40034: cannot attach the library file

    I got this message when try to run the DEVELOPER 2000 demo program after installed it on a NTserver,how can i solve this problem? thanks null

  • BPC Standard Naming Convention

    Hi Gurus, Could you please share BPC naming conventions standards? I am looking for prefix for objects such as: Environment Model Dimension Team Task Profile Data Access Profile Member Formulas Logic Script Business Rule Controls Input Screen Report

  • N95 8gb switches off while taking a backup with co...

    Hi All, I have Nokia N95 8gb with FW 30.x. There is some problem when I try to backup my phone using the content copier on PC suite. The phone just switches off when it reaches the point of backing up device specific settings. It shows a green tick f

  • Sales Order in PCUI: Search for products based on BP?

    Hello, my customer wants to migrate to PC-UI and has the requirement that when creating a new sales order the search for products only returns those products that are defined by a partner-product relation PPR, as is possible in standard SAPGui. Unfor