4 Replies Latest reply: Aug 1, 2012 11:14 PM by 953411 RSS

    how do i add a text area to table column

    Murray9654
      Hi I have added a JTextArea to JTable column as below
      DefaultTableModel model=new DefaultTableModel ();
      Object rowdata={"",new JTextArea(),""};
      model.addRow(rowData);
      when i did the above it did not added text area to column. Instaed it added a string which is obtained by toString method. How do i add a component to the JTable column. Thanks in advance.
        • 1. Re: how do i add a text area to table column
          Nitin Khare
          DefaultTableModel model=new DefaultTableModel ();
          Object rowdata={"",new JTextArea(),""};
          model.addRow(rowData);
          You have added a JTextArea object as table data so it is always going to be its string representation which you will see. You would need to create a custom renderer and editor for the table column where you want to use text area.
          • 2. Re: how do i add a text area to table column
            gimbal2
            The swing tutorial has plenty of examples on advanced usage of the table, including adding input components to it:

            http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
            • 3. Re: how do i add a text area to table column
              Murray9654
              Hi I have read the tutorial. I have somewhat understood how to write custom renderers. but If somebody can post an example for JTextArea it will be very much helpfull. Thanks in advance.
              • 4. Re: how do i add a text area to table column
                953411
                i know that by posting this would be a lil bit too late..but i also faced the same situation. not many sharing the example. so here is the coding, i got on several sites and do a lil alteration in it. about on how to add jtextarea & button to jtable.

                this is not in a very good shape example but worth trying

                Its contain two file. First ,TextAreaRenderer.java and Second, TextAreaRendererInTable.java
                package components;
                
                import javax.swing.JTable; 
                import javax.swing.JTextArea; 
                import javax.swing.table.DefaultTableCellRenderer; 
                import javax.swing.table.TableCellRenderer; 
                import javax.swing.table.TableColumn; 
                import javax.swing.table.TableColumnModel; 
                import java.awt.Component; 
                import java.util.Enumeration; 
                import java.util.HashMap; 
                import java.util.Map; 
                 
                /** 
                 * The standard class for rendering (displaying) individual cells in a JTable. 
                 * This class inherits from JTextArea, a standard component class. 
                 * However JTextArea is a multi-line area that displays plain text. 
                 * 
                 * This class implements TableCellRenderer , i.e. interface. 
                 * This interface defines the method required by any object that 
                 * would like to be a renderer for cells in a JTable. 
                 * 
                 * @author Manivel 
                 * @see JTable 
                 * @see JTextArea 
                 */ 
                 
                public class TextAreaRenderer extends JTextArea implements TableCellRenderer { 
                    private final DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); 
                 
                    // Column heights are placed in this Map 
                    private final Map<JTable, Map<Object, Map<Object, Integer>>> tablecellSizes = new HashMap<JTable, Map<Object, Map<Object, Integer>>>(); 
                 
                    /** 
                     * Creates a text area renderer. 
                     */ 
                    public TextAreaRenderer() { 
                        setLineWrap(true); 
                        setWrapStyleWord(true); 
                    } 
                 
                    /** 
                     * Returns the component used for drawing the cell.  This method is 
                     * used to configure the renderer appropriately before drawing. 
                     * 
                     * @param jTable3      - JTable object 
                     * @param value      - the value of the cell to be rendered. 
                     * @param isSelected - isSelected   true if the cell is to be rendered with the selection highlighted; 
                     *                   otherwise false. 
                     * @param hasFocus   - if true, render cell appropriately. 
                     * @param row        - The row index of the cell being drawn. 
                     * @param column     - The column index of the cell being drawn. 
                     * @return - Returns the component used for drawing the cell. 
                     */ 
                    public Component getTableCellRendererComponent(JTable jTable3, Object value, boolean isSelected,boolean hasFocus, int row, int column) { 
                        // set the Font, Color, etc. 
                        renderer.getTableCellRendererComponent(jTable3, value,isSelected, hasFocus, row, column); 
                        setForeground(renderer.getForeground()); 
                        setBackground(renderer.getBackground()); 
                        setBorder(renderer.getBorder()); 
                        setFont(renderer.getFont()); 
                        setText(renderer.getText()); 
                 
                        TableColumnModel columnModel = jTable3.getColumnModel(); 
                        setSize(columnModel.getColumn(column).getWidth(), 0); 
                        
                        int height_wanted = (int) getPreferredSize().getHeight(); 
                        addSize(jTable3, row, column, height_wanted); 
                        height_wanted = findTotalMaximumRowSize(jTable3, row); 
                        
                        if (height_wanted != jTable3.getRowHeight(row)) { 
                            jTable3.setRowHeight(row, height_wanted); 
                        } 
                        return this; 
                    } 
                 
                    /** 
                     * @param jTable3  - JTable object 
                     * @param row    - The row index of the cell being drawn. 
                     * @param column - The column index of the cell being drawn. 
                     * @param height - Row cell height as int value 
                     *               This method will add size to cell based on row and column number 
                     */ 
                    private void addSize(JTable jTable3, int row, int column, int height) { 
                        Map<Object, Map<Object, Integer>> rowsMap = tablecellSizes.get(jTable3); 
                        if (rowsMap == null) { 
                            tablecellSizes.put(jTable3, rowsMap = new HashMap<Object, Map<Object, Integer>>()); 
                        } 
                        Map<Object, Integer> rowheightsMap = rowsMap.get(row); 
                        if (rowheightsMap == null) { 
                            rowsMap.put(row, rowheightsMap = new HashMap<Object, Integer>()); 
                        } 
                        rowheightsMap.put(column, height); 
                    } 
                 
                    /** 
                     * Look through all columns and get the renderer.  If it is 
                     * also a TextAreaRenderer, we look at the maximum height in 
                     * its hash table for this row. 
                     * 
                     * @param jTable3 -JTable object 
                     * @param row   - The row index of the cell being drawn. 
                     * @return row maximum height as integer value 
                     */ 
                    private int findTotalMaximumRowSize(JTable jTable3, int row) { 
                        int maximum_height = 0; 
                        Enumeration<TableColumn> columns = jTable3.getColumnModel().getColumns(); 
                        while (columns.hasMoreElements()) { 
                            TableColumn tc = columns.nextElement(); 
                            TableCellRenderer cellRenderer = tc.getCellRenderer(); 
                            if (cellRenderer instanceof TextAreaRenderer) { 
                                TextAreaRenderer tar = (TextAreaRenderer) cellRenderer; 
                                maximum_height = Math.max(maximum_height, 
                                        tar.findMaximumRowSize(jTable3, row)); 
                            } 
                        } 
                        return maximum_height; 
                    } 
                 
                    /** 
                     * This will find the maximum row size 
                     * 
                     * @param jTable3 - JTable object 
                     * @param row   - The row index of the cell being drawn. 
                     * @return row maximum height as integer value 
                     */ 
                    private int findMaximumRowSize(JTable jTable3, int row) { 
                        Map<Object, Map<Object, Integer>> rows = tablecellSizes.get(jTable3); 
                        if (rows == null) return 0; 
                        Map<Object, Integer> rowheights = rows.get(row); 
                        if (rowheights == null) return 0; 
                        int maximum_height = 0; 
                        for (Map.Entry<Object, Integer> entry : rowheights.entrySet()) { 
                            int cellHeight = entry.getValue(); 
                            maximum_height = Math.max(maximum_height, cellHeight); 
                        } 
                        return maximum_height; 
                    } 
                }
                and here is the second file
                package components;
                 
                import java.awt.Component;
                import java.awt.event.ActionEvent;
                import java.awt.event.ActionListener;
                import javax.swing.*; 
                import javax.swing.table.*; 
                 
                /** 
                 * The standard class for testing the TextAreaRenderer class. 
                 * This class inherits from JFrame, a standard component class. 
                 * 
                 * @author Manivel 
                 * @see JFrame 
                 */ 
                public class TextAreaRendererInTable extends JFrame { 
                 
                    /** 
                     * Creates a TextAreaRendererInTable object. 
                     */ 
                    public TextAreaRendererInTable() { } 
                 
                    /** 
                     * This method build the table. 
                     */ 
                    private void showTable() { 
                        JTable jTable3 = new JTable(3, 2); 
                       
                 
                        TableColumnModel cmodel = jTable3.getColumnModel(); 
                        TextAreaRenderer textAreaRenderer = new TextAreaRenderer(); 
                        
                        cmodel.getColumn(1).setCellRenderer(new ButtonRenderer());
                        cmodel.getColumn(1).setCellEditor(new ButtonEditor(new JCheckBox()));
                        cmodel.getColumn(0).setCellRenderer(textAreaRenderer); 
                 
                        addRows(jTable3); 
                        getContentPane().add(new JScrollPane(jTable3)); 
                        setSize(300, 200); 
                        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
                        setLocationRelativeTo(null); 
                        setTitle("Text Area Renderer & Button In Table"); 
                        setVisible(true); 
                 
                    } 
                 
                    /** 
                     * This method will add rows into table. 
                     * 
                     * @param table - JTable object 
                     */ 
                    private void addRows(JTable jTable3) { 
                        String props = "text area renderer & button in table"; 
                        for (int i = 0; i < 3; i++) { 
                            //jTable3.setValueAt(props + "-" + props, i, 0); 
                            //jTable3.setValueAt(props, i, 1); 
                           jTable3.setValueAt(props + "\n" + props + " - " + props, i, 0); 
                        } 
                    } 
                 
                    /** 
                     * Main method of TextAreaRendererInTable class 
                     * 
                     * @param args - Default main method string args 
                     */ 
                    public static void main(String[] args) { 
                        new TextAreaRendererInTable().showTable(); 
                    } 
                    class ButtonRenderer extends JButton implements TableCellRenderer {
                
                  public ButtonRenderer() {
                    setOpaque(true);
                  }
                
                  public Component getTableCellRendererComponent(JTable jTable3, Object value,
                      boolean isSelected, boolean hasFocus, int row, int column) {
                    if (isSelected) {
                      setForeground(jTable3.getSelectionForeground());
                      setBackground(jTable3.getSelectionBackground());
                    } else {
                      setForeground(jTable3.getForeground());
                      setBackground(UIManager.getColor("Button.background"));
                    }
                    setText((value == null) ? "" : value.toString());
                    return this;
                  }
                }
                
                /**
                 * @version 1.0 11/09/98
                 */
                
                class ButtonEditor extends DefaultCellEditor {
                  protected JButton btn_sha;
                  private String label;
                  private boolean isPushed;
                
                  public ButtonEditor(JCheckBox checkBox) {
                    super(checkBox);
                    btn_sha = new JButton();
                    btn_sha.setOpaque(true);
                    btn_sha.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent e) {
                        fireEditingStopped();
                      }
                    });
                  }
                
                  public Component getTableCellEditorComponent(JTable jTable3, Object value,
                      boolean isSelected, int row, int column) {
                    if (isSelected) {
                      btn_sha.setForeground(jTable3.getSelectionForeground());
                      btn_sha.setBackground(jTable3.getSelectionBackground());
                      
                    } else {
                      btn_sha.setForeground(jTable3.getForeground());
                      btn_sha.setBackground(jTable3.getBackground());
                    }
                    label = (value == null) ? "DONT PUSH ME" : value.toString();
                    btn_sha.setText("PUSH ME");
                    isPushed = true;
                    return btn_sha;
                  }
                
                  public Object getCellEditorValue() {
                    if (isPushed) {
                      
                      JOptionPane.showMessageDialog(btn_sha,label + ": Ouch!");
                      // System.out.println(label + ": Ouch!");
                    }
                    isPushed = false;
                    return new String(label);
                  }
                
                  public boolean stopCellEditing() {
                    isPushed = false;
                    return super.stopCellEditing();
                  }
                
                  protected void fireEditingStopped() {
                    super.fireEditingStopped();
                  }
                }
                }