Multiline cells in JTable

Hi all,
Im created a JTable,but im not able to read the lengthy text when it is bigger than the cell width.So, i want the text to be be align in the next line of that cell same as in excel sheet.
Can anyone help me in this.
Thank you

Im created a JTable,but im not able to read the lengthy text when it is bigger than the cell width.So, i want the text to be be align in the next line of that cell same as >in excel sheet.You should look at using your own cellRenderer ( TableCellRenderer)
Regards,
Alan Mehio
London,UK

Similar Messages

  • 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

  • Help with multilined cells in JTable?

    Can someone plz help me with this class, I want to make cells multilined. I tried cellrenderer but without succes... :-(
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    public class GK_Styringspunkter extends JFrame
         Container panel = getContentPane();
         JTable tabel;
         DataModel model;
         JScrollPane scroll;
    GK_Styringspunkter()
              model = new DataModel();
              tabel = new JTable(model);
              scroll = new JScrollPane(tabel);
              panel.add("Center",scroll);
              setSize(1024,768);
              setVisible(true);
    class DataModel extends AbstractTableModel
         String hoved[];
         Object data[][];
         DataModel()
              hoved = new String[]{"Processtrin","Kritisk styringspunkt","Risikofaktor","Styrende foranstaltning",
              "Kritisk gr�nse","Overv�gning","Afhj�lpende foranstaltning","Ansvarlig"};
              data = new Object[1][8];
              data[0][0] = "Fiskeafdelingen";
              data[0][1] = "Temperatur";
              data[0][2] = "Opformering af mikroorganismer";
              data[0][3] = "Temperatur kontrol ved modtagelse";
              data[0][4] = "Frisk fisk:2C R�get fisk: 5C";
    void opdater()
    public int getColumnCount()
    return hoved.length;
    public int getRowCount()
    return data.length;
    public String getColumnName(int col)
    return hoved[col];
    public Object getValueAt(int row, int col)
    return data[row][col];
    public boolean isCellEditable(int row, int col)
    return true;
    public void setValueAt(Object value, int row, int col)
    data[row][col] = value;
    fireTableCellUpdated(row,col);      
    public static void main(String[] aslan)
         new GK_Styringspunkter();
    }

    sorry my fault... but when I try like this am still not getting the multilines in cells?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    public class GK_Styringspunkter extends JFrame
         Container panel = getContentPane();
         JTable tabel;
         DataModel model;
         JScrollPane scroll;
    GK_Styringspunkter()
              model = new DataModel();
              tabel = new JTable(model);
              tabel.setRowHeight(0, 60);
              tabel.setDefaultRenderer(String.class, new MultiLineRenderer());
              scroll = new JScrollPane(tabel);
              panel.add("Center",scroll);
              setSize(1024,768);
              setVisible(true);
    class DataModel extends AbstractTableModel
         String hoved[];
         Object data[][];
         DataModel()
              hoved = new String[]{"Processtrin","Kritisk styringspunkt","Risikofaktor","Styrende foranstaltning",
              "Kritisk gr�nse","Overv�gning","Afhj�lpende foranstaltning","Ansvarlig"};
              data = new Object[1][8];
              data[0][0] = "Fiskeafdelingen";
              data[0][1] = "Temperatur";
              data[0][2] = "Opformering \n af mikroorganismer";
              data[0][3] = "Temperatur kontrol \n ved modtagelse";
              data[0][4] = "Frisk fisk:2C \n R�get fisk: 5C";
    void opdater()
    public int getColumnCount()
    return hoved.length;
    public int getRowCount()
    return data.length;
    public String getColumnName(int col)
    return hoved[col];
    public Object getValueAt(int row, int col)
    return data[row][col];
    public boolean isCellEditable(int row, int col)
    return true;
    public void setValueAt(Object value, int row, int col)
    data[row][col] = value;
    fireTableCellUpdated(row,col);      
    class MultiLineRenderer extends JTextArea implements javax.swing.table.TableCellRenderer
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
         setLineWrap(true);
         setText((String)value);
         if (isSelected)setBackground(Color.BLUE);
         else setBackground(Color.WHITE);
         return this;
    public static void main(String[] aslan)
         new GK_Styringspunkter();

  • How do i do that? MultiLine in a cell of JTable !!!

    Dear friends,
    I am trying to add multiline in a cell of JTable. For that bellow code i have written, but my statement in cell displays in a line only. Code is given bellow (copy/paste/run), could anyone help me how to do that?
    Regards..
    Jaya.
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.sql.*;
    public class OtL extends JFrame {
        public OtL()
          initComponents();
        private void initComponents() {
            model1 = new DefaultTableModel();
            btnClose  = new javax.swing.JButton();
            tblOt       = new javax.swing.JTable(model1);
            scrOt   = new javax.swing.JScrollPane();
            TableCellRenderer renderer = new TableRenderer();
            tblOt.setDefaultRenderer(Object.class,renderer);
            tblOt.setRowHeight(tblOt.getRowHeight()*3);
            tblOt.setBackground(new java.awt.Color(250,225,162));
            getContentPane().setLayout(null);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            btnClose.setText("CLOSE");
            btnClose.setToolTipText("Close This Screen");
            btnClose.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.RAISED));
            btnClose.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                  System.exit(0);
            getContentPane().add(btnClose);
            btnClose.setBounds(380, 470, 110, 25);
            tblOt.setToolTipText("Operation Theatre Booking List");
            scrOt.setViewportView(tblOt);
            tableSize();
            scrOt.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0)));
            scrOt.setToolTipText("Operation Theatre Booking List");
            getContentPane().add(scrOt);
            scrOt.setBounds(15, 150, 770, 300);
            displayOtList();
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
        public static void main(String args[]) {
            JFrame j  = new OtL();
            j.setSize(800,560);
            j.show();
    /**********Code for displaying Operation Theater Booking List****Start Here*************/
        public void displayOtList(){
    Here i fire a sql query and i populate data in table.
    Sometime i get more than 1 value for some column e.g Surgery Name and Surgeon Name, so
    i want to display more than 1 value in the same cell. like bellow i have mentiond for
    5th and 6th column. But its displayin in one line only, how can i display that in multiple line!!
    I know that can be taken care with  Renderer, i tried but couldn't go through. I have written TableRenderer
    class for that, please help me what should i do in Renderer class.
          int row1=0;
          tableSize();
          DefaultTableModel model1 = (DefaultTableModel)tblOt.getModel();
          Object[] newRow = new Object[6];
            for(int i=0;i<1;i++){
              row1 = tblOt.getRowCount() + 1;
              newRow[0] = "1";
              newRow[1] = "10:10";
              newRow[2] = "11:30";
              newRow[3] = "Name Here";
              newRow[4] = "Surgery Name1 \n Surgery Name2";
              newRow[5] = "Dr. Amit \n Dr. Johnson";
              model1.addRow(newRow);
    /**********Code for displaying Operation Theater Booking List****End Here*************/
       class TableRenderer 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);
          setOpaque(true);
           return this;
    /******tableSize()*****code for sizing table******start here()********/
      public void tableSize(){
        tblOt.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {},
            new String [] {"Ot No.", "Start Time","End Time", "Patient Name", "Surgery Name","Surgeon Name"}
        TableColumn column = null;
        for (int i = 0; i < 6; i++) {
          column = tblOt.getColumnModel().getColumn(i);
          if (i == 0) {
            column.setPreferredWidth(5);
          if (i == 1) {
            column.setPreferredWidth(15);
          if (i == 2) {
          column.setPreferredWidth(15);
          if (i == 3) {
            column.setPreferredWidth(130);
          if (i == 4) {
            column.setPreferredWidth(130);
          if (i == 5) {
            column.setPreferredWidth(130);
    /******tableSize()*****code for sizing table******end here()********/
        private javax.swing.JButton btnClose;
        private javax.swing.JScrollPane scrOt;
        private javax.swing.JTable tblOt;
        private DefaultTableModel model1;
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    OK Filne, Thanx .. its displaying data in multiple line now.
    But still there is a problem, whenever i move mouse over the table row it returns error like bellow. I am not able to findout the reason of error. I tried to put code in try{} catch{} block to avoid this error, but still its coming. Help me.....!!!!!!!!
    java.lang.NullPointerException
            at javax.swing.text.View.getViewIndex(View.java:1060)
            at javax.swing.text.View.getToolTipText(View.java:1031)
            at javax.swing.plaf.basic.BasicTextUI.getToolTipText(BasicTextUI.java:1057)
            at javax.swing.text.JTextComponent.getToolTipText(JTextComponent.java:1533)
            at javax.swing.JTable.getToolTipText(JTable.java:2380)
            at javax.swing.ToolTipManager$insideTimerAction.actionPerformed(ToolTipManager.java:669)
            at javax.swing.Timer.fireActionPerformed(Timer.java:256)
            at javax.swing.Timer$DoPostEvent.run(Timer.java:190)
            at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:167)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:437)
            at java.awt.EventDispatchThread.pumpOneEvent(EventDispatchThread.java:150)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:131)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)my latest programe code is here :
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    public class OtL extends JFrame {
        public OtL()
          initComponents();
        private void initComponents() {
            model1 = new DefaultTableModel();
            btnClose  = new javax.swing.JButton();
            tblOt       = new javax.swing.JTable(model1);
            scrOt   = new javax.swing.JScrollPane();
            TableCellRenderer renderer = new TableRenderer();
            tblOt.setDefaultRenderer(Object.class,renderer);
            tblOt.setRowHeight(tblOt.getRowHeight()*3);
            tblOt.setBackground(new java.awt.Color(250,225,162));
            getContentPane().setLayout(null);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            btnClose.setText("CLOSE");
            btnClose.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.RAISED));
            btnClose.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                  System.exit(0);
            getContentPane().add(btnClose);
            btnClose.setBounds(380, 470, 110, 25);
            scrOt.setViewportView(tblOt);
            tableSize();
            scrOt.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0)));
            getContentPane().add(scrOt);
            scrOt.setBounds(15, 150, 770, 300);
            displayOtList();
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
        public static void main(String args[]) {
            JFrame j  = new OtL();
            j.setSize(800,560);
            j.show();
        public void displayOtList(){
          int row1=0;
          tableSize();
          DefaultTableModel model1 = (DefaultTableModel)tblOt.getModel();
          Object[] newRow = new Object[6];
            for(int i=0;i<1;i++){
              row1 = tblOt.getRowCount() + 1;
              newRow[0] = "1";
              newRow[1] = "10:10";
              newRow[2] = "11:30";
              newRow[3] = "Name Here";
              newRow[4] = "Surgery Name1 \n Surgery Name2";
              newRow[5] = "Dr. Amit \n Dr. Johnson";
              model1.addRow(newRow);
       class TableRenderer extends JTextArea implements TableCellRenderer{
          public TableRenderer(){
            setLineWrap(true);
            setWrapStyleWord(true);
            setOpaque(true);
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean
    hasFocus, int row, int column)
          if (isSelected) {
            setForeground(tblOt.getSelectionForeground());
            setBackground(tblOt.getSelectionBackground());
          } else {
            setForeground(tblOt.getForeground());
          setFont(tblOt.getFont());
          if (hasFocus) {
            setBorder( UIManager.getBorder("Table.focusCellHighlightBorder") );
              if (tblOt.isCellEditable(row, column)) {
                setForeground( UIManager.getColor("Table.focusCellForeground") );
                setBackground( UIManager.getColor("Table.focusCellBackground") );
              } else {
            setBorder(new EmptyBorder(1, 2, 1, 2));
          setText((value == null) ? "" : value.toString());
          return this;
    /******tableSize()*****code for sizing table******start here()********/
      public void tableSize(){
        tblOt.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {},
            new String [] {"Ot No.", "Start Time","End Time", "Patient Name", "Surgery Name","Surgeon Name"}
        TableColumn column = null;
        for (int i = 0; i < 6; i++) {
          column = tblOt.getColumnModel().getColumn(i);
          if (i == 0) {
            column.setPreferredWidth(5);
          if (i == 1) {
            column.setPreferredWidth(15);
          if (i == 2) {
          column.setPreferredWidth(15);
          if (i == 3) {
            column.setPreferredWidth(130);
          if (i == 4) {
            column.setPreferredWidth(130);
          if (i == 5) {
            column.setPreferredWidth(130);
    /******tableSize()*****code for sizing table******end here()********/
        private javax.swing.JButton btnClose;
        private javax.swing.JScrollPane scrOt;
        private javax.swing.JTable tblOt;
        private DefaultTableModel model1;
    }

  • Problem with addRow and MultiLine Cell renderer

    Hi ,
    Ive a problem with no solution to me .......
    Ive seen in the forum and Ivent found an answer.......
    The problem is this:
    Ive a JTable with a custom model and I use a custom multiline cell renderer.
    (becuse in the real application "way" hasnt static lenght)
    When I add the first row all seem to be ok.....
    when I try to add more row I obtain :
    java.lang.ArrayIndexOutOfBoundsException: 1
    at javax.swing.SizeSequence.insertEntries(SizeSequence.java:332)
    at javax.swing.JTable.tableRowsInserted(JTable.java:2926)
    at javax.swing.JTable.tableChanged(JTable.java:2858)
    at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableMo
    del.java:280)
    at javax.swing.table.AbstractTableModel.fireTableRowsInserted(AbstractTa
    bleModel.java:215)
    at TableDemo$MyTableModel.addRow(TableDemo.java:103)
    at TableDemo$2.actionPerformed(TableDemo.java:256)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:17
    64)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Abstra
    ctButton.java:1817)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:419)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
    istener.java:245)
    at java.awt.Component.processMouseEvent(Component.java:5134)
    at java.awt.Component.processEvent(Component.java:4931)
    at java.awt.Container.processEvent(Container.java:1566)
    at java.awt.Component.dispatchEventImpl(Component.java:3639)
    at java.awt.Container.dispatchEventImpl(Container.java:1623)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
    at java.awt.Container.dispatchEventImpl(Container.java:1609)
    at java.awt.Window.dispatchEventImpl(Window.java:1590)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
    read.java:197)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    This seems to be caused by
    table.setRowHeight(row,(getPreferredSize().height+2)); (line 164 of my example code)
    About the model I think its ok.....but who knows :-(......
    Please HELP me in anyway!!!
    Example code :
    import javax.swing.*;
    import javax.swing.table.*;
    import java.text.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class TableDemo extends JFrame {
    private boolean DEBUG = true;
    MyTableModel myModel = new MyTableModel();
    MyTable table = new MyTable(myModel);
    int i=0;
    public TableDemo() {
    super("TableDemo");
    JButton bottone = new JButton("Aggiungi 1 elemento");
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(bottone,BorderLayout.NORTH);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    bottone.addActionListener(Add_Action);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    class MyTable extends JTable {
    MultiLineCellRenderer multiRenderer=new MultiLineCellRenderer();
    MyTable(TableModel tm)
    super(tm);
    public TableCellRenderer getCellRenderer(int row,int col) {
              if (col==1) return multiRenderer;
              else return super.getCellRenderer(row,col);
    class MyTableModel extends AbstractTableModel {
    Vector data=new Vector();
    final String[] columnNames = {"Name",
    "Way",
    "DeadLine (ms)"
    public int getColumnCount() { return 3; }
    public int getRowCount() { return data.size(); }
    public Object getValueAt(int row, int col) {
    Vector rowdata=(Vector)data.get(row);
                                                                return rowdata.get(col); }
    public String getColumnName(int col) {
    return columnNames[col];
    public void setValueAt (Object value, int row,int col)
         //setto i dati della modifica
    Vector actrow=(Vector)data.get(row);
    actrow.set(col,value);
         this.fireTableCellUpdated(row,col);
         public Class getColumnClass(int c)
              return this.getValueAt(0,c).getClass();
         public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col == 1)
    return false;
    else
    return true;
    public void addRow (String name,ArrayList path,Double dead) {
         Vector row =new Vector();
         row.add(name);
         row.add(path);
         row.add(dead);
         row.add(name); //!!!Mi tengo questo dato da utilizzare come key per andare a
         //prendere il path nella lista dei paths di Project
         //(needed as key to retrive data if name in col. 1 is changed)
         data.add(row);
         //Inspector.inspect(this);
         System.out.println ("Before firing Adding row...."+this.getRowCount());
         this.fireTableRowsInserted(this.getRowCount(),this.getRowCount());
    public void delRow (String namekey)
    for (int i=0;i<this.getRowCount();i++)
    if (namekey.equals(this.getValueAt(i,3)))
    data.remove(i);
    this.fireTableRowsDeleted(i,i);
    //per uscire dal ciclo
    i=this.getRowCount();
    public void delAllRows()
    int i;
    int bound =this.getRowCount();     
    for (i=0;i<bound;i++)     
         {data.remove(0);
         System.out.println ("Deleting .."+data);
    this.fireTableRowsDeleted(0,i);          
    class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {
    private Hashtable rowHeights=new Hashtable();
    public MultiLineCellRenderer() {
    setEditable(false);
    setLineWrap(true);
    setWrapStyleWord(true);
    //this.setBorder(new Border(
    public Component getTableCellRendererComponent(JTable table,Object value,                              boolean isSelected, boolean hasFocus, int row, int column) {
    //System.out.println ("Renderer called"+value.getClass());
    if (value instanceof ArrayList) {
    String way=new String     (value.toString());
    setText(way);
    TableColumn thiscol=table.getColumn("Way");
    //System.out.println ("thiscol :"+thiscol.getPreferredWidth());
    //setto il size della JTextarea sulle dimensioni della colonna
    //per quanto riguarda il widht e su quelle ottenute da screen per l'height
    this.setSize(thiscol.getPreferredWidth(),this.getPreferredSize().height);
    // set the table's row height, if necessary
    //System.out.println ("Valore getPreferred.height"+getPreferredSize().height);
         if (table.getRowHeight(row)!=(this.getPreferredSize().height+2))
         {System.out.println ("Setting Row :"+row);
             System.out.println ("Dimension"+(getPreferredSize().height+2));
             System.out.println ("There are "+table.getRowCount()+"rows in the table ");
             if (row<table.getRowCount())
             table.setRowHeight(row,(getPreferredSize().height+2));
    else
    setText("");
    return this;
    /**Custom JTextField Subclass che permette all'utente di immettere solo numeri
    class WholeNumberField extends JTextField {
    private Toolkit toolkit;
    private NumberFormat integerFormatter;
    public WholeNumberField(int value, int columns) {
    super(columns);
    toolkit = Toolkit.getDefaultToolkit();
    integerFormatter = NumberFormat.getNumberInstance(Locale.US);
    integerFormatter.setParseIntegerOnly(true);
    setValue(value);
    public int getValue() {
    int retVal = 0;
    try {
    retVal = integerFormatter.parse(getText()).intValue();
    } catch (ParseException e) {
    // This should never happen because insertString allows
    // only properly formatted data to get in the field.
    toolkit.beep();
    return retVal;
    public void setValue(int value) {
    setText(integerFormatter.format(value));
    protected Document createDefaultModel() {
    return new WholeNumberDocument();
    protected class WholeNumberDocument extends PlainDocument {
    public void insertString(int offs,
    String str,
    AttributeSet a)
    throws BadLocationException {
    char[] source = str.toCharArray();
    char[] result = new char[source.length];
    int j = 0;
    for (int i = 0; i < result.length; i++) {
    if (Character.isDigit(source))
    result[j++] = source[i];
    else {
    toolkit.beep();
    System.err.println("insertString: " + source[i]);
    super.insertString(offs, new String(result, 0, j), a);
    ActionListener Add_Action = new ActionListener() {
              public void actionPerformed (ActionEvent e)
              System.out.println ("Adding");
              ArrayList way =new ArrayList();
              way.add(new String("Uno"));
              way.add(new String("Due"));
              way.add(new String("Tre"));
              way.add(new String("Quattro"));
              myModel.addRow(new String("Nome"+i++),way,new Double(0));     
    public static void main(String[] args) {
    TableDemo frame = new TableDemo();
    frame.pack();
    frame.setVisible(true);

    In the addRow method, change the line
    this.fireTableRowsInserted(this.getRowCount(),this.getRowCount()); to
    this.fireTableRowsInserted(data.size() - 1, data.size() - 1);Sai Pullabhotla

  • Multiline cell table problem

    hi all
    i found in this forum a class that implements TableCellRenderer and that should allow my table to have multiline cells. i need it because if the content of my cell (retrieved via jdbc from a db) exceeds the cell width is truncated and a "..." appears.
    so i searched, i founded and i tried some example but with no results. i don't know where is the mistake, also because the code should work.
    i'll post the class code and my table's code and i hope someone could help me!!!
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    import java.awt.*;
    * @version 1.0 11/09/98
    public class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {
      public MultiLineCellRenderer() {
        setLineWrap(true);
        setWrapStyleWord(true);
        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(table.getBackground());
        setFont(table.getFont());
        if (hasFocus) {
          setBorder( UIManager.getBorder("Table.focusCellHighlightBorder") );
          if (table.isCellEditable(row, column)) {
            setForeground( UIManager.getColor("Table.focusCellForeground") );
            setBackground( UIManager.getColor("Table.focusCellBackground") );
        } else {
          setBorder(new EmptyBorder(1, 2, 1, 2));
        setText((value == null) ? "" : value.toString());
        return this;
    }i set the new tablecellrenderer in this way:
    table.setDefaultRenderer(String.class, new MultiLineCellRenderer() );
            Object[] columns=new Object[]{"Data","Ora","Nome","Referente","Indirizzo","Citt�","Telefono","Motivazione","App. con"};
            JTableHeader k=new JTableHeader();
            table.setTableHeader(k);
            table.setModel(new javax.swing.table.DefaultTableModel (o,columns)
                    Class[] types = new Class [] {
                        java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
             anyone could help me?
    thanx a lot

    thanx to all my friends, but i still have my problem..
    viravan, i'm using the same MultiLineCellRenderer class as the example, the only thing different is my class from where i set the MultiLineCellRenderer the default Renderer for my table
    this is the code: (i post it because i didn't found any significant difference between the example class and the one of mine...) i suspect there is some problem in the table setting... but i don't know where...
    import java.lang.Thread;
    import java.sql.*;
    import java.util.Vector;
    import java.text.*;
    import javax.swing.table.*;
    public class AppTablePainter implements Runnable
        Thread t;
        DateFormat date;
        public AppTablePainter()
            t=new Thread(this);
            t.start();
        public void run()
            paint();
        void paint()
            Statement s=null;
            Vector clienti=new Vector();
            Vector appIl=new Vector();
            Vector hours=new Vector();
            Vector referenti=new Vector();
            Vector indirizzi=new Vector();
            Vector telefoni=new Vector();
            Vector citta=new Vector();
            Vector motivazioni=new Vector();
            Vector appCon=new Vector();
            Vector commerciali=new Vector();
            Vector commenti=new Vector();
            Vector ids=new Vector();       
            Vector tempCommerciali= new Vector();
            date=Jtm.date;
            String action="SELECT * FROM CONTATTI WHERE COMMERCIALE='"+Appuntamenti.cCommerciale.getSelectedItem()+"' AND APPUNTAMENTO_IL IS NOT NULL";
            //System.out.println(action);
            try
                s=Jtm.tmc.createStatement();
                ResultSet rs=s.executeQuery(action);           
                java.util.Date appDate;
                DateFormat appHour=new SimpleDateFormat("HH:mm");
                appHour.setLenient(false);
                String get=null;
                Appuntamenti.sp.set("Recupero appuntamenti in corso...");
                int maximum=0;
                while(rs.next())
                     try
                        maximum++;
                        get=rs.getString("appuntamento_il");                     
                        appDate=date.parse(get);               
                        String stringDate=date.format(appDate);                                       
                        if(!appDate.before(Jtm.now))
                            String id=rs.getString("id");
                            ids.add(id);  
                            appIl.add(get);                       
                            try
                                hours.add(appHour.format(appHour.parse(rs.getString("ore"))));                       
                            catch(ParseException p)
                                hours.add("23:00");
                            catch (NullPointerException np)
                                hours.add("23:01");
                    catch(SQLException sq)
                        //JOptionPane.showMessageDialog(this, sq.getMessage(), "",JOptionPane.ERROR_MESSAGE);
                        sq.printStackTrace();
                    catch(NullPointerException n){}
                    catch(ParseException p)  //se la data non � parseable � perch� � nulla visto che c'� un controllo all'inserimento
                        //System.out.println("parseException "+get);
                        //JOptionPane.showMessageDialog(this, p.getMessage(), "",JOptionPane.ERROR_MESSAGE);
                        //p.printStackTrace();
                Appuntamenti.sp.progBar.setMaximum(maximum);
            catch(SQLException sq)
                sq.printStackTrace();
            catch(NullPointerException n)
                n.printStackTrace();
            /*System.out.println("prima ordinamento:");
            for(int i=0; i<ids.size();i++)
                System.out.println("id "+ids.get(i).toString()+", data app "+appIl.get(i).toString()+", ore "+hours.get(i).toString());
            for(int i=0; i<ids.size(); i++)
                System.out.println("ids("+i+")= "+ids.get(i).toString());
            for(int i=0; i<appIl.size(); i++)
                System.out.println("appIl("+i+")= "+appIl.get(i).toString());
            for(int i=0; i<hours.size(); i++)
                System.out.println("hours("+i+")= "+hours.get(i).toString());
            myAppArray[] dateArr=new myAppArray[appIl.size()];
            Appuntamenti.sp.set("Inizio ordinamento in corso");
            Appuntamenti.sp.progBar.setMaximum(appIl.size());
            for(int i=0; i<dateArr.length; i++)
                Appuntamenti.sp.progBar.setValue(i);
                dateArr=new myAppArray(ids.get(i).toString(),appIl.get(i).toString(),hours.get(i).toString());
    java.util.Arrays.sort(dateArr, new ArrayAppDateComparator());
    Vector newIds=new Vector();
    for(int i=0; i< dateArr.length; i++)
    myAppArray temp=dateArr[i];
    //System.out.println("data: "+temp.getDate()+", ora: "+temp.getHour()+" id: "+temp.getId());
    newIds.add(temp.getId());
    appIl.clear();
    hours.clear();
    commerciali.clear();
    clienti.clear();
    commenti.clear();
    try
    Appuntamenti.sp.set("Recupero informazioni...");
    Appuntamenti.sp.progBar.setValue(0);
    Statement s1=Jtm.tmc.createStatement();
    for(int i=0; i<newIds.size(); i++)
    Appuntamenti.sp.progBar.setValue(i);
    String tempId=newIds.get(i).toString();
    //System.out.println("tempId: "+tempId);
    ResultSet rs1=s1.executeQuery("select * from contatti where id="+tempId);
    if(rs1.next())
    appIl.add(rs1.getString("appuntamento_il"));
    hours.add(rs1.getString("ore"));
    clienti.add(rs1.getString("nome"));
    referenti.add(rs1.getString("referente"));
    indirizzi.add(rs1.getString("indirizzo"));
    citta.add(rs1.getString("citta"));
    telefoni.add(rs1.getString("telefono"));
    motivazioni.add(rs1.getString("motivazione"));
    appCon.add(rs1.getString("appuntamento_con"));
    catch(SQLException sq)
    sq.printStackTrace();
    Object[][] o=new Object[ids.size()][9];
    System.out.println("o.length: "+o.length);
    String dataAppuntamento="";
    for(int i=0; i<o.length; i++)
    try
    String tempData=appIl.get(i).toString();
    if(tempData.equals(dataAppuntamento))
    o[i][0]="";
    else
    dataAppuntamento=tempData;
    o[i][0]=dataAppuntamento;
    catch(NullPointerException n){o[i][0]="";}
    for(int i=0; i<o.length; i++)
    try
    o[i][1]=hours.get(i).toString();
    catch(NullPointerException n){o[i][1]="";}
    for(int i=0; i<o.length; i++)
    try
    o[i][2]=clienti.get(i).toString();
    catch(NullPointerException n){o[i][2]="";}
    for(int i=0; i<o.length; i++)
    try
    o[i][3]=referenti.get(i).toString();
    catch(NullPointerException n){o[i][3]="";}
    for(int i=0; i<o.length; i++)
    try
    o[i][4]=indirizzi.get(i).toString();
    catch(NullPointerException n){o[i][4]="";}
    for(int i=0; i<o.length; i++)
    try
    o[i][5]=citta.get(i).toString();
    catch(NullPointerException n){o[i][5]="";}
    for(int i=0; i<o.length; i++)
    try
    o[i][6]=telefoni.get(i).toString();
    catch(NullPointerException n){o[i][6]="";}
    for(int i=0; i<o.length; i++)
    try
    o[i][7]=motivazioni.get(i).toString();
    catch(NullPointerException n){o[i][7]="";}
    for(int i=0; i<o.length; i++)
    try
    o[i][8]=appCon.get(i).toString();
    catch(NullPointerException n){o[i][8]="";}
    System.out.println("height: "+Appuntamenti.table.getRowHeight());
    System.out.println("olenght: "+o.length);
    System.out.println("risultato: "+ (Appuntamenti.table.getRowHeight() * o.length));
    Appuntamenti.table.setRowHeight( Appuntamenti.table.getRowHeight());
    //Appuntamenti.table.setRowHeight(16);
    Appuntamenti.table.setDefaultRenderer(String.class, new MultiLineCellRenderer() );
    Object[] columns=new Object[]{"Data","Ora","Nome","Referente","Indirizzo","Citt�","Telefono","Motivazione","App. con"};
    JTableHeader k=new JTableHeader();
    Appuntamenti.table.setTableHeader(k);
    Appuntamenti.table.setModel(new javax.swing.table.DefaultTableModel (o,columns)
    Class[] types = new Class [] {
    java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
    TableColumnModel tcm = Appuntamenti.table.getColumnModel();
    TableColumn data = tcm.getColumn(0);
    TableColumn ora = tcm.getColumn(1);
    TableColumn cliente = tcm.getColumn(2);
    TableColumn referente = tcm.getColumn(3);
    TableColumn indirizzo = tcm.getColumn(4);
    TableColumn citt = tcm.getColumn(5);
    TableColumn telefono = tcm.getColumn(6);
    TableColumn motivazione = tcm.getColumn(7);
    TableColumn appcon = tcm.getColumn(8);
    System.out.println("data "+data.getPreferredWidth());
    System.out.println("ora "+ora.getPreferredWidth());
    System.out.println("cliente "+cliente.getPreferredWidth());
    System.out.println("referente "+referente.getPreferredWidth());
    System.out.println("indirizzo "+indirizzo.getPreferredWidth());
    System.out.println("citt "+citt.getPreferredWidth());
    System.out.println("telefono "+telefono.getPreferredWidth());
    System.out.println("motivazione "+motivazione.getPreferredWidth());
    System.out.println("appcon "+appcon.getPreferredWidth());
    data.setPreferredWidth(700);
    ora.setPreferredWidth(350);
    cliente.setPreferredWidth(1000);
    referente.setPreferredWidth(1000);
    indirizzo.setPreferredWidth(1300);
    citt.setPreferredWidth(1000);
    telefono.setPreferredWidth(1000);
    motivazione.setPreferredWidth(1500);
    appcon.setPreferredWidth(1000);
    //data.setCellRenderer(new MultiLineTableCellRenderer());
    //cliente.setCellRenderer(new MultiLineTableCellRenderer().getTableCellRendererComponent());
    Appuntamenti.lTotale.setText(Integer.toString(o.length));
    Appuntamenti.ids=newIds;
    Appuntamenti.sp.mostra();
    Appuntamenti.sp.dispose();
    //Integer[] integerIds=Integer.ids.toArray();
    for(int i=0; i<dateArr.length; i++)
    System.out.println("dateArr["+i+"]= "+date.format(dateArr[i]));
    java.util.Arrays.sort(dateArr);
    for(int i=0; i<dateArr.length; i++)
    System.out.println("ordinato dateArr["+i+"]= "+date.format(dateArr[i]));
    class myAppArray
    private String id;
    private String date;
    private String hour;
    public myAppArray(String id, String date, String hour)
    this.id=id;
    this.date=date;
    this.hour=hour;
    public String getDate()
    return date;
    public String getHour()
    return hour;
    public String getId()
    return id;
    class ArrayAppDateComparator implements java.util.Comparator
    private DateFormat date=Jtm.date;
    private DateFormat hour=new SimpleDateFormat("HH:mm");
    public int compare(Object o1, Object o2)
    hour.setLenient(false);
    myAppArray s1 = (myAppArray)o1;
    myAppArray s2 = (myAppArray)o2;
    java.util.Date d1=null;
    java.util.Date d2=null;
    java.util.Date h1=null;
    java.util.Date h2=null;
    try
    d1 = date.parse(s1.getDate());
    d2 = date.parse(s2.getDate());
    catch(ParseException pe)
    pe.printStackTrace();
    if(!d1.equals(d2))
    return d1.compareTo(d2);
    else
    try
    h1 = hour.parse(s1.getHour());
    h2 = hour.parse(s2.getHour());
    catch(ParseException pe)
    pe.printStackTrace();
    return h1.compareTo(h2);

  • 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

  • Change the background color of a cell in JTable

    Hi all,
    How can I change the background color of individual cell in JTable. I need to construct my own TableCellRenderer or not? I'm now using the DefaultTableCellRenderer now.
    Thx

    You could create your own renderer or you could try something like:
    table = new JTable(model)
         public TableCellRenderer getCellRenderer(int row, int column)
              DefaultTableCellRenderer tcr =
               (DefaultTableCellRenderer)super.getCellRenderer(row, column);
              if (row == 1 && column == 1)
                   tcr.setBackground(Color.green);
              else
                   tcr.setBackground(Color.red);
              return tcr;
    };

  • How can I get right data in a cell of JTable when table  enter editing

    how can I get right data in a cell of JTable when table enter editing

    how can I get right data in a cell of JTable when table enter editing

  • 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

  • Unable to edit cells in JTable on single click of the cell.

    Hi,
    I am unable to edit a cell in JTable on single click of the cell. If I double click on the cell, I am able to edit it. Please help me.
    Thanks
    Subbu

    Thanks for all replies. Now, i am able to edit the cell on single click.

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

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

Maybe you are looking for