Floating Height of JTextArea (as Renderer/Editor) in a JTable Cell

Hey Folks,
I'm kinda struggling with JTextAreas...
There is this JTable, which consists of three colums (practically there are two - the other one's an ID-Field...) and only one
of them ist editable für users.
Left column is a commentary column which has a max of 150 characters - Right column fills automaticly with a user/date stamp.                                                                                                                                                                                    
The main function is that on showing the table, old comments will be retrieved from database and new ones can be entered.
This works all fine and is no matter of subject...
The core of my problem is that there seems to be no straigh-forward way of determine a proper linecount from (a wordwrapped!) JTextArea.
After a long search in the net, i found this approach:
    private static ArrayList<String> getWrappedLines(JTextArea myTextArea) {
        ArrayList<String> linesList = new ArrayList<String>();
        int length = myTextArea.getDocument().getLength();
        int offset = 0;
        try {
            while (offset < length) {
                int end = Utilities.getRowEnd(myTextArea, offset);
                if (end < 0) {
                    break;
                // Include the last character on the line
                end = Math.min(end + 1, length);
                String line =
                    myTextArea.getDocument().getText(offset, end - offset);
                // Remove the line break character
                if (line.endsWith("\n")) {
                    line = line.substring(0, line.length() - 1);
                linesList.add(line);
                offset = end;
        } catch (BadLocationException e) {
            System.err.println("Bad Location at TextArea");
        return linesList;
    }    This code reads the content of a JTextArea an separates wrapped lines in an array.
With manual line breaks ("\n") I get Exceptions (Bad Location) which isn't too bad, because
I was trying to ban manual line breaks anyway...
The above given method retrieves the lines, while the next sets the new Height (line count multiplied by Font Height) to the row.
    public static void setOptimalRowHeight(JTable table, JTextArea textArea, int row, int column) {
        if (
            row >= 0 &&
            column == VerwaltungsnotizController.IND_VNO_NOTIZ   
            int fontHeight =
                textArea.getFontMetrics(textArea.getFont()).getHeight();
            ArrayList<String> wrappedLines = getWrappedLines(textArea);
            int nrOfLines = wrappedLines.size();
            int oldSize = table.getRowHeight(row);
            int newSize = (fontHeight * nrOfLines) + 5;
            if (newSize != oldSize) {
                table.setRowHeight(row, newSize);
     public static void setOptimalRowHeight(JTable table, JTextArea textArea) {
     int row = table.getSelectedRow();
     int column = table.getSelectedColumn();
     if (
          row >= 0 &&
          column == VerwaltungsnotizController.IND_VNO_NOTIZ   
          setOptimalRowHeight(table, textArea, row, column);
     }The above combined Sources are used by two classes, which are "tied" to the table.
One is the CellEditor (which works almost fine); the other one is the CellRenderer (which fails miserably!)
CellEditor (with Listener):
public class VnoCellEditor extends AbstractCellEditor implements TableCellEditor {
    private VnoTextArea textArea;
    private JTable table;
    public VnoCellEditor (JTable table) {
        this.table = table;
        textArea = new VnoTextArea(table);
        textArea.setMaximumInputLength(VerwaltungsnotizController.MAX_INPUT_VNO);
        textArea.addKeyListener(new TextAreaEnterAdapter());
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        Document document = textArea.getDocument();
        document.addDocumentListener(new VnoTextAreaDocListener(table, textArea));
    public Component getTableCellEditorComponent(JTable table, Object value,
                                                 boolean isSelected, int row,
                                                 int column) {
        if (value instanceof String) {
            textArea.setText((String)value);
        } else if (value instanceof Integer) {
            Integer intValue = (Integer)value;
            textArea.setText(intValue.toString());
        } else {
            Object objValue = value;
            textArea.setText(objValue.toString());
        System.err.println("Editor - get Component");
        return textArea;
    public Object getCellEditorValue() {
        return textArea.getText();
public class VnoTextAreaDocListener implements DocumentListener {
    private JTable table;
    private JTextArea textArea;
    public VnoTextAreaDocListener(JTable table, JTextArea textArea) {
        this.table = table;
        this.textArea = textArea;
    public void insertUpdate(DocumentEvent e) {
        VnoTableRowHeightHelper.setOptimalRowHeight(table, textArea);
    public void removeUpdate(DocumentEvent e) {
        VnoTableRowHeightHelper.setOptimalRowHeight(table, textArea);
    public void changedUpdate(DocumentEvent e) {
        //Plain text components don't fire these events
}As said the editor works almost as planned. On every Keystroke made in Edit-Mode of the table, insertUpdate() or removeUpdate()
is being called, corresponding to the type of Keystroke ... (duh!)
The Helpers method is called and the row-height is set real nicely.
!But!
when i navigate into an other row, a removeUpdate()-event is beeing thrown and due to the mechanism the cell selection
gets somehow mixed around and row-heights get switched.
Maybe this could get improved, but i don't se my error - which wouldn't be nescessary if this event wasn't thrown.
(for what I don't see a reason anyway ... !)
CellRenderer:
public class VnoCellRenderer implements TableCellRenderer {
    private VnoTextArea textArea;
    private int Row = -1;
    private int Column = -1;
    private VnoTableModel jtmVno;
    public VnoCellRenderer(JTable table) {
        this.jtmVno = (VnoTableModel)table.getModel();
        textArea = new VnoTextArea(table);
        textArea.setLayout(new BorderLayout());
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
    public VnoTextArea getTextArea() {
        return textArea;
    public Component getTableCellRendererComponent(JTable table, Object value,
                                                   boolean isSelected,
                                                   boolean hasFocus, int row,
                                                   int column) {
        Row = row;
        Column = column;
        String tmpValue = null;
        if (value instanceof String) {
            tmpValue = (String)value;
        } else if (value instanceof Integer) {
            tmpValue = ((Integer)value).toString();
        } else {
            tmpValue = value.toString();
        // FARBEN:
        // Normalmodus
        if (jtmVno == null) {
            System.err.println("Table Model noch nicht initialisiert!");
            textArea.setBackground(Color.LIGHT_GRAY);
        } else {
            if (jtmVno.isCellEditable(Row, Column)) {
                textArea.setBackground(Color.WHITE);
            } else {
                textArea.setBackground(Color.LIGHT_GRAY);
        textArea.setForeground(Color.BLACK);
        // Für ausgewählte Zeile
        if (isSelected && !hasFocus) {
            textArea.setBackground(CommonConstants.SELECTION_COLOR_BLUE);
            textArea.setForeground(Color.WHITE);
        textArea.setText(tmpValue);
        textArea.setEditable(true);
        if (Column == VerwaltungsnotizController.IND_VNO_NOTIZ) {
            VnoTableRowHeightHelper.setOptimalRowHeight(table, textArea, row, column);
        return textArea;
}Okay, this is where the shit hits the fan!
Since with renderers there is no manual content mutation, row-height-settings are not done with listeners.
I put this at the very end of the getTableCellRendererComponent(), which is called every time a cell gets rendered.
The main problem here is that at this point my methods can't determine any linewraps at all!
getWrappedLines() always returns an empty Array (since Utilities.getRowEnd() returns "-1" beforehand...).
I'm afraid that my methods are called way too early - at a point were the rendering is not completed or has not even started.
And to accomplish my desired tasks the fully rendered JTextArea would be needed ... ?!
I have very limited swing experience, so I can only guess about this core features ...
But i this is the case - my methods should be called later on the rendered cell. But how? from which component?
Btw: I have written my own JTextArea to limit the input size
public class VnoTextArea extends JTextArea {
    private JTable table;
    private int _maximumInputLength = 0;
    public VnoTextArea(JTable table) {
        this.table = table;
    public void setMaximumInputLength(int maximumInputLength) {
      if (maximumInputLength != 0) {
        _maximumInputLength = maximumInputLength;
        super.setDocument(new PlainDocument() {
            public void insertString(int offset, String string, AttributeSet attributeSet) throws BadLocationException {
              StringBuffer buffer = new StringBuffer(string);
              int size = VnoTextArea.this.getText().length();
              int bufferSize = buffer.length();
              if ((size + bufferSize) > _maximumInputLength) {
                buffer.delete((_maximumInputLength - size), bufferSize);
              if (size < _maximumInputLength) {
                super.insertString(offset, buffer.toString(), attributeSet);
              } else {
                Toolkit.getDefaultToolkit().beep();
}I'm sorry for not providing a running example, but it's a pretty huge project...
Providing all dependencies would go far beyond the scope.
(and there are many sources which I'm not allowed to post)
But I hope my examples get down to the core of my problem!
I also tried different approaches:
- using getPreferredSize() of the JTextArea (seemed to do nothing useful at all?!)
- using getLineCount/() of the TextArea (only counts "\n" ...)
- guessing that every row consist of an average of 20 characters cumpute by myself (low-tech, buggy but fast - unsatisfying)
With my above mentioned approach I got by far the best results (partially) - but I'm at my wits' end.
I don't know it any better... And i have tried for days without improvement.
What would you do?
vielen Dank im Voraus schon mal für eventuelle Mühen,
Haye

no solution - just a couple of comments:
- never ever change the calling table in a renderer, I mean really NEVER
- instead, listen to table events and resize the row height as appropriate
- JTextArea has a somehow weird prefSize calculation (forgot the details, so don't nail me :), so you have to manually set one dimension and then ask the area to calculate the other. In your renderer, you can do something like:
Component getTableCellRendererComponent(....) {
    int columnWidth = table.getColumnModel().getColumn(column).getWidth();
    textArea.setSize(columnWidth, Short.MAX_VALUE);
    ... here do the normal config
// then somewhere else, triggered by appropriate change events
void updateRowHeight(JTable table, int row) {
   int height = table.getRowHeight();
   foreach column {
         TableCellRenderer r = table.getCellRenderer(row, column);
         Component c = table.prepareCellRenderer(r, row, column);
         height = Math.max(height, c.getPreferredSize().height);
   table.setRowHeight(row, height);
} HTH - ein bißchen wenigstens :-)
Jeanette

Similar Messages

  • How to select rows in the inner JTable rendered in an outer JTable cell

    I have wrriten the following code for creating cell specific renderer - JTable rendered in a cell of a JTable.
    table=new JTable(data,columnNames)
    public TableCellRenderer getCellRenderer(int row, int column)
    if ((row == 0) && (column == 0))
    return new ColorRenderer();
    else if((row == 1) && (column == 0))
    return new ColorRenderer1();
    else
    return super.getCellRenderer(row, column);
    ColorRenderer and ColorRenderer1 are two inner classes, which implement TableCellRenderer to draw inner JTable on the outer JTable cell, having 2 rows and 1 column each.
    Now what is happening the above code keeps executing continously, that is the classes are being initialised continously, inner JTables are rendered (drawn) continously, and this makes the application slow after some time. It throws java.lang.OutOfMemoryException.
    WHY IS IT SO??? I can't understand where's the bug..
    Any advice please???
    Moreover i want selections in inner tables and not on outer table, how can this be possible.
    I am working on this since a long time but have not yet found a way out...

    With your help i have overcome the problem of continous repeatition.
    The major problem which I am facing is, in selecting rows in the inner rendered JTables.
    I have added listener on outer JTable which select rows on the outer JTable, hence the complete inner JTable which being treated as a row, gets selected.
    The thing is i need to select the rows of inner rendered JTables,not the outer JTable.
    How to go about it??
    I have even added listener to inner rendered JTables, but only first row of every table gets selected.
    Please help....
    Thanks in advance.

  • Rendering multiple objects in JTable cells

    Hi,
    I wish to render in a single JTable cell (actually all cells in a Column) an ImageIcon and it's associated description string. The description string should be rendered below the ImageIcon, as it's caption. How can this be done? I assume a custom cell renderer, but the details are muddy at this point.
    thanks!
    JPL

    Thanks.
    I have looked atthe tutorial, but it focuses on a single object type per cell - I've got two different types (an ImageIcon and a String) that will occupuy a single cell.
    Taking a conceptual leap here, is it possible to create a new TableCellRenderer that houses a JPanel and GridLayout, and then place an ImageIcon and JLabel into that panel? I guess as long as things are JComponents, should I be OK with this approach?
    thanks,
    jpl

  • Tab transversal while using JTextArea as a JTable cell editor..

    I'm working on a project that will use a JTable with a JTextArea cell editor to create a chart for classroom scheduling. Searching on Google, I found a way to use a JTextArea as a cell editor and render the cell properly. However, when editing a cell, pressing the Tab key inserts a tab, rather than leaving the cell and going to the next one, as happens with just a regular JTable. In fact, none of the keyboard shortcuts that work on a JTable work once the JTextArea cell editor is used. Does anyone know of any way to resolve this? Below is some code I'm using to create a sample GUI, just to verify that I can do this. Another question is would it be easier to use a bunch of JLabels and JTextAreas, remove the padding from those JTextAreas, and try to allow for Tab transversals between stand-alone JTextAreas, rather than JTextAreas as JTable cell editors?
    Thanks!
    package edu.elon.table;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class GUI
         private JFrame frame;
         private String[] columnNames = {"Classroom", "8:00-9:10", "9:25-10:35",
              "10:50-12:00", "12:15-1:25", "1:40-2:50", "1:40-3:20 (MW)",
              "3:35-5:15 (MW)", "5:30-7:10 (MW)"};
         private Object[][] data = {columnNames,
              {"ALAM 201 (42)\nENG 110 LAB", "", "", "", "", "", "", "", ""},
              {"ALAM 202 (42)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 203 (38)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 205 (40)\n", "", "", "", "", "", "", "", ""},
              {"ALAM 206 (39)\nSINK, TV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 207 (40+)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 214 (38)\nTV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 215 (42)\nTV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 216 (42)\n", "", "", "", "", "", "", "", ""},
              {"ALAM 301 (40)\nTV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 302 (38)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 304 (35)\nFRENCH", "", "", "", "", "", "", "", ""},
              {"ALAM 314 (30)\nDP, PSY, COMPUTER ASSISTED", "", "", "", "", "", "",
              {"ALAM 315 (40)\nPC LAB, DP/DVD", "", "", "", "", "", "", "", ""}};
         private JTable table;
         public GUI()
              frame = new JFrame();
              table = new JTable(data, columnNames);
              table.setRowHeight(table.getRowHeight()*2);
              TableColumnModel cModel = table.getColumnModel();
              TextAreaRenderer renderer = new TextAreaRenderer();
              TextAreaEditor editor = new TextAreaEditor();
              for (int i = 0; i < cModel.getColumnCount(); i++)
                   cModel.getColumn(i).setCellRenderer(renderer);
                   cModel.getColumn(i).setCellEditor(editor);
              frame.setLayout(new GridLayout(1,0));
              frame.add(table);
              frame.pack();
              frame.setVisible(true);
    public static void main (String[] args)
    GUI gui = new gui();
    * Written by Dr. Heinz Kabutz, found through online newsletter via Google.
    class TextAreaRenderer extends JTextArea
    implements TableCellRenderer {
    private final DefaultTableCellRenderer adaptee =
    new DefaultTableCellRenderer();
    /** map from table to map of rows to map of column heights */
    private final Map cellSizes = new HashMap();
    public TextAreaRenderer() {
    setLineWrap(true);
    setWrapStyleWord(true);
    public Component getTableCellRendererComponent(//
    JTable table, Object obj, boolean isSelected,
    boolean hasFocus, int row, int column) {
    // set the colours, etc. using the standard for that platform
    adaptee.getTableCellRendererComponent(table, obj,
    isSelected, hasFocus, row, column);
    setForeground(adaptee.getForeground());
    setBackground(adaptee.getBackground());
    setBorder(adaptee.getBorder());
    setFont(adaptee.getFont());
    setText(adaptee.getText());
    // This line was very important to get it working with JDK1.4
    TableColumnModel columnModel = table.getColumnModel();
    setSize(columnModel.getColumn(column).getWidth(), 100000);
    int height_wanted = (int) getPreferredSize().getHeight();
    addSize(table, row, column, height_wanted);
    height_wanted = findTotalMaximumRowSize(table, row);
    if (height_wanted != table.getRowHeight(row)) {
    table.setRowHeight(row, height_wanted);
    return this;
    private void addSize(JTable table, int row, int column,
    int height) {
    Map rows = (Map) cellSizes.get(table);
    if (rows == null) {
    cellSizes.put(table, rows = new HashMap());
    Map rowheights = (Map) rows.get(new Integer(row));
    if (rowheights == null) {
    rows.put(new Integer(row), rowheights = new HashMap());
    rowheights.put(new Integer(column), new Integer(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.
    private int findTotalMaximumRowSize(JTable table, int row) {
    int maximum_height = 0;
    Enumeration columns = table.getColumnModel().getColumns();
    while (columns.hasMoreElements()) {
    TableColumn tc = (TableColumn) columns.nextElement();
    TableCellRenderer cellRenderer = tc.getCellRenderer();
    if (cellRenderer instanceof TextAreaRenderer) {
    TextAreaRenderer tar = (TextAreaRenderer) cellRenderer;
    maximum_height = Math.max(maximum_height,
    tar.findMaximumRowSize(table, row));
    return maximum_height;
    private int findMaximumRowSize(JTable table, int row) {
    Map rows = (Map) cellSizes.get(table);
    if (rows == null) return 0;
    Map rowheights = (Map) rows.get(new Integer(row));
    if (rowheights == null) return 0;
    int maximum_height = 0;
    for (Iterator it = rowheights.entrySet().iterator();
    it.hasNext();) {
    Map.Entry entry = (Map.Entry) it.next();
    int cellHeight = ((Integer) entry.getValue()).intValue();
    maximum_height = Math.max(maximum_height, cellHeight);
    return maximum_height;
    * Written by Dr. Heinz Kabutz, found through online newsletter via Google.
    class TextAreaEditor extends DefaultCellEditor
    public TextAreaEditor() {
         super(new JTextField());
    final JTextArea textArea = new JTextArea();
    textArea.setWrapStyleWord(true);
    textArea.setLineWrap(true);
    JScrollPane scrollPane = new JScrollPane(textArea);
    scrollPane.setBorder(null);
    editorComponent = scrollPane;
    delegate = new DefaultCellEditor.EditorDelegate() {
    public void setValue(Object value)
    textArea.setText((value != null) ? value.toString() : "");
    public Object getCellEditorValue()
    return textArea.getText();
    }

    Using the KeyEvent manager and playing around with the JTextArea, I was able to get a JTable using JTextAreas as the cell editors that worked very close to the way the regular JTable works. You have to hit Tab twice to shift focus to another cell, or hit Tab once and then an arrow key. Also, Alt-Enter will allow you to enter a cell for editing. All of the changes were made to the TextAreaEditor class, which should now read as follows:
    class TextAreaEditor extends DefaultCellEditor implements KeyListener
         private int lastKeyCode;
         public TextAreaEditor(final JTable table) {
              super(new JTextField());
              lastKeyCode = KeyEvent.CTRL_DOWN_MASK;
              final JTextArea textArea = new JTextArea();
              textArea.setWrapStyleWord(true);
              textArea.setLineWrap(true);
              textArea.addKeyListener(this);
              textArea.setFocusable(true);
              textArea.setFocusAccelerator((char) KeyEvent.VK_ENTER);
              JScrollPane scrollPane = new JScrollPane(textArea);
              scrollPane.setBorder(null);
              scrollPane.setFocusable(false);
              editorComponent = scrollPane;
              delegate = new DefaultCellEditor.EditorDelegate() {
                   public void setValue(Object value) {
                        textArea.setText((value != null) ? value.toString() : "");
                   public Object getCellEditorValue() {
                        return textArea.getText();
         public void keyTyped(KeyEvent ke)
              // TODO Auto-generated method stub
         public void keyPressed(KeyEvent ke)
              if (ke.getKeyCode() == KeyEvent.VK_TAB)
                   ke.consume();
                   KeyboardFocusManager.getCurrentKeyboardFocusManager()
                             .focusNextComponent();
                   return;
              if (ke.getKeyCode() == KeyEvent.VK_TAB && ke.isShiftDown())
                   ke.consume();
                   KeyboardFocusManager.getCurrentKeyboardFocusManager()
                             .focusPreviousComponent();
                   return;
              if ((lastKeyCode == KeyEvent.CTRL_DOWN_MASK) &&
                        (ke.getKeyCode() == KeyEvent.VK_ENTER))
                   ke.consume();
                   editorComponent.requestFocus();
              else
                   lastKeyCode = ke.getKeyCode();
         public void keyReleased(KeyEvent ke)
              // TODO Auto-generated method stub
         }

  • HELP !! change the line height in JTextArea ??

    can anyone tell me , how to change (set) the line height in JTextArea ???

    Looking at the source code for JTextArea, the rowHeight is taken from the font's FontMetrics and is used to set the preferred size of the ta, as you can see in the following app. Also, only three properties are maintained by the default PlainDocument as shown in the output. Might be worth your while to check out JTextPane.
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    public class TARowHeight {
      public static void main(String[] args) {
        final CustomTextArea ta = new CustomTextArea(5,10);
        ta.addPropertyChangeListener(new PropertyChangeListener() {
          public void propertyChange(PropertyChangeEvent e) {
            System.out.println(e.getPropertyName() + " changed to " + e.getNewValue());
        ta.setLineWrap(true);
        ta.setWrapStyleWord(true);
        ta.setFont(new Font("lucida sans regular" , Font.PLAIN, 16));
        JPanel centerPanel = new JPanel();
        centerPanel.add(ta);
        SpinnerNumberModel model = new SpinnerNumberModel(20,8,36,1);
        final JSpinner spinner = new JSpinner(model);
        spinner.addChangeListener(new ChangeListener() {
          public void stateChanged(ChangeEvent e) {
            int height = ((Integer)spinner.getValue()).intValue();
            ta.setRowHeight(height);
            ta.revalidate();
            ta.repaint();
        JPanel southPanel = new JPanel();
        southPanel.add(spinner);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new JScrollPane(centerPanel), "Center");
        f.getContentPane().add(southPanel, "South");
        f.setSize(300,200);
        f.setLocation(400,400);
        f.setVisible(true);
        System.out.println(ta.getRowHeight());
        Dictionary names = ((AbstractDocument)ta.getDocument()).getDocumentProperties();
        Enumeration keys = names.keys();
        Enumeration values = names.elements();
        while(keys.hasMoreElements())
          System.out.println("key: " + keys.nextElement() +
                             " value: " + values.nextElement());
    class CustomTextArea extends JTextArea {
      private int rowHeight;
      public CustomTextArea(int rows, int cols) {
        super(rows, cols);
      protected int getRowHeight() {
            if (rowHeight == 0) {
                FontMetrics metrics = getFontMetrics(getFont());
                rowHeight = metrics.getHeight();
            return rowHeight;
      protected void setRowHeight(int rowHeight) {
        int oldVal = this.rowHeight;
        this.rowHeight = rowHeight;
        firePropertyChange("rowHeight", oldVal, rowHeight);
    }

  • Problem in JTable cell renderer

    Hi
    One problem in JTable cell. Actually I am using two tables while I am writing renderer for word raping in first table .. but it is affected in last column only remain is not being effected�. Please chaek it out what is exact I am missing�
    Thanks
    package com.apsiva.tryrowmerge;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.EventObject;
    import java.util.Hashtable;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.border.Border;
    import javax.swing.border.EmptyBorder;
    import javax.swing.event.*;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    class Item_Details extends JFrame {
        ApsJTable itemTable = null;
         ApsJTable imageTable = null;     
         ArrayList data = new ArrayList();
         String[] columns = new String[2];
         ArrayList data1 = new ArrayList();
         String[] columns1 = new String[2];
         ItemTableModel itemTableModel = null;
         ItemTableModel itemTableModel1 = null;
         public Item_Details()
              super("Item Details");          
             this.setSize(600,100);
             this.setBackground(Color.WHITE);
              this.setVisible(true);
             init();          
         private void init(){
              ////////////// Get data for first Table Model  ////////////////////////////
              data = getRowData();
              columns = getColData();
              System.out.println(columns[0]);
             itemTableModel = new ItemTableModel(data,columns);
             /////////////Get Data for Second Table Model //////////////////////////////
              try{
                        data1 = getRowData1();
                 }catch(Exception e){}
              columns1 = getColumns1();
             itemTableModel1 = new ItemTableModel(data1,columns1);
             ///////////// Set Data In Both Table Model //////////////////////////////////
              itemTable = new ApsJTable(itemTableModel);
              imageTable = new ApsJTable(itemTableModel1);
              this.itemTable.setShowGrid(false);
              this.imageTable.setShowGrid(false);
              this.itemTable.setColumnSelectionAllowed(false);
              this.imageTable.setColumnSelectionAllowed(false);
              System.out.println(itemTable.getColumnCount());
              this.imageTable.setRowHeight(getImageHeight()+3);
              JScrollPane tableScrollPane = new JScrollPane(this.imageTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              tableScrollPane.setRowHeaderView(this.itemTable);
              //itemTable.getColumnModel().getColumn(0).setMaxWidth(200);
              itemTable.getColumnModel().getColumn(0).setPreferredWidth(200);
              itemTable.getColumnModel().getColumn(1).setPreferredWidth(600);
              tableScrollPane.getRowHeader().setPreferredSize(new Dimension(800, 0));
              itemTable.getTableHeader().setResizingAllowed(false);
              itemTable.getTableHeader().setReorderingAllowed(false);
              itemTable.setColumnSelectionAllowed(false);
              //itemTable.setRowHeight(25);
              itemTable.setCellSelectionEnabled(false);
              itemTable.setFocusable(false);
              imageTable.getTableHeader().setReorderingAllowed(false);
              imageTable.setFocusable(false);
              imageTable.setCellSelectionEnabled(false);
              //tableScrollPane.setOpaque(false);
              itemTable.setAutoCreateColumnsFromModel(false);
              int columnCount = itemTable.getColumnCount();
              for(int k=0;k<columnCount;k++)
                   TableCellRenderer renderer = null;
                   TableCellEditor editor = null;
                   renderer = new TextAreaCellRenderer();     // NEW
              //     editor = new TextAreaCellEditor();     
              //     TableColumn column = new TableColumn(k,itemTable.getColumnModel().getColumn(k).getWidth(),renderer, editor);
                   System.out.println(k);
                   itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);          
                   //itemTable.getColumnModel().getColumn(k).setCellEditor(editor);
                   /*itemTable.getColumnModel().getColumn(1).setCellRenderer(new TextAreaCellRenderer());
                   itemTable.getColumnModel().getColumn(1).setCellEditor(new TextAreaCellEditor());*/
    //               itemTable.setShowGrid(false);
                   //itemTable.addColumn(column);
                   //itemTable.getColumnModel().getColumn(k).setCellRenderer(new MultiLineCellRenderer());
                   //itemTable.getColumnModel().getColumn(k).setCellEditor(new TextAreaCellEditor());
    ////////////---------------------- Here background color is being set--------------//////////////////
              this.imageTable.getParent().setBackground(Color.WHITE);
              this.itemTable.getParent().setBackground(Color.WHITE);
              tableScrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER,this.itemTable.getTableHeader());
              getContentPane().add(tableScrollPane,BorderLayout.CENTER);
              getContentPane().setVisible(true);
         public static void main(String[] str){
              com.incors.plaf.alloy.AlloyLookAndFeel.setProperty("alloy.licenseCode", "2005/05/28#[email protected]#1v2pej6#1986ew");
              try {
                javax.swing.LookAndFeel alloyLnF = new com.incors.plaf.alloy.AlloyLookAndFeel();
                javax.swing.UIManager.setLookAndFeel(alloyLnF);
              } catch (javax.swing.UnsupportedLookAndFeelException ex) {
              ex.printStackTrace();
              Item_Details ID = new Item_Details();
              ID.setVisible(true);
    public ArrayList getRowData()
         ArrayList rowData=new ArrayList();
         Hashtable item = new Hashtable();
         item.put(new Long(0),new String("Item No:aaaaaaa aaaaaaaa aaaaaaaaa aaaaaa"));
         item.put(new Long(1),new String("RED-1050"));
         rowData.add(0,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Description:rt r trtrt rttrytrr tytry trytry tr tr rty thyjyhjhnhnhgg hhjhgjh"));
         item.put(new Long(1),new String("SYSTEM 18 mbh COOLING 13 mbh HEATING 230/208 v POWER AIRE "));
         rowData.add(1,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Stage:"));
         item.put(new Long(1),new String("Draft"));
         rowData.add(2,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Price: "));
         item.put(new Long(1),new String("999.00"));
         rowData.add(3,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(4,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(5,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(6,item);
         /*item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(5,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(6,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(7,item);
         return rowData;
    public String[] getColData()
         String[] colData = new String[]{"Attribute","Value"};
         return colData;
    public ArrayList getRowData1()throws MalformedURLException{
         ArrayList rowData = new ArrayList();
         Hashtable item = new Hashtable();
         String str = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url = new URL(str);
         ImageIcon ic = new ImageIcon(url);
         ImageIcon scaledImage = new ImageIcon(ic.getImage().getScaledInstance(getImageHeight(), -1,Image.SCALE_SMOOTH));
         item.put(new Long(0), scaledImage);
         rowData.add(0,item);
         String str1 = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url1 = new URL(str1);
         ImageIcon ic1 = new ImageIcon(url1);
         ImageIcon scaledImage1 = new ImageIcon(ic1.getImage().getScaledInstance(120, -1,Image.SCALE_DEFAULT));
         item.put(new Long(0),scaledImage1);
         rowData.add(1,item);
         return rowData;
    public String[] getColumns1(){
         String[] colData = new String[]{"Image"}; 
         return colData;
    public int getImageHeight(){
         ImageIcon ic = new ImageIcon("c:\\image\\ImageNotFound.gif");
         return ic.getIconHeight();
    class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
         public TextAreaCellRenderer() {
              setEditable(false);
              setLineWrap(true);
              setWrapStyleWord(true);
         public Component getTableCellRendererComponent(JTable table,
              Object value, boolean isSelected, boolean hasFocus,
              int nRow, int nCol)
              if (value instanceof String)
                   setText((String)value);
              // Adjust row's height
              int width = table.getColumnModel().getColumn(nCol).getWidth();
              setSize(width, 1000);
              int rowHeight = getPreferredSize().height;
              if (table.getRowHeight(nRow) != rowHeight)
                   table.setRowHeight(nRow, rowHeight);
              this.setBackground(Color.WHITE);
              return this;

    I think Problem is between these code only
    for(int k=0;k<columnCount;k++)
                   TableCellRenderer renderer = null;
                   TableCellEditor editor = null;
                   renderer = new TextAreaCellRenderer();
                                                                itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);or in this renderer
    class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
         public TextAreaCellRenderer() {
              setEditable(false);
              setLineWrap(true);
              setWrapStyleWord(true);
         public Component getTableCellRendererComponent(JTable table,
              Object value, boolean isSelected, boolean hasFocus,
              int nRow, int nCol)
              if (value instanceof String)
                   setText((String)value);
              // Adjust row's height
              int width = table.getColumnModel().getColumn(nCol).getWidth();
              setSize(width, 1000);
              int rowHeight = getPreferredSize().height;
              if (table.getRowHeight(nRow) != rowHeight)
                   table.setRowHeight(nRow, rowHeight);
              this.setBackground(Color.WHITE);
              return this;
    }

  • Setting JTable cell editor

    Hallo,
    I have troubles setting jtable cell edtior. when i run code below, editor stays unchnaged.
    Do you know where's the problem, please (except in programmer^_^) ???
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    public class Test extends JFrame {
        JTable table;
        Test() {
            // Create table model
            table = new JTable();
            table.setModel(new DefaultTableModel(
                new Object[][] {
                    { Boolean.TRUE, Integer.valueOf(10) },
                    { "Hallo!", Boolean.FALSE },
                }, new String[] { "Col1", "Col2" }));
            // Setup frame a little
            setLayout(new BorderLayout());
            setBounds(new Rectangle(300,300,200,100));
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            add(table,BorderLayout.CENTER);
             * Two calls below have no effect:-(
             * What did i wrong?
            // set cell editor for all cells
            table.setCellEditor(new DefaultCellEditor(
                    new JComboBox(new String[] { "0", "1" }) ));
            // Use checkbox for booleans
            table.setDefaultEditor(Boolean.class, new DefaultCellEditor(
                    new JCheckBox() ));
            // Use combobox for strings
            table.setDefaultEditor(String.class, new DefaultCellEditor(
                    new JComboBox( new String[] { "Hallo!", "Bye!" } ) ));
        public static void main(String[] arg) {
            Test test = new Test();
            test.setVisible(true);
    }

    Hi again,
    yes it works when i set it for single column, but i'd like to use default editor, because column count is not fixed.
    According to documentation: "Sets a default cell editor to be used if no editor has been set in a TableColumn. If no editing is required in a table, or a particular column in a table, uses the isCellEditable method in the TableModel interface to ensure that this JTable will not start an editor in these columns. If editor is null, removes the default editor for this column class."
    So when i call
    column.setCellEditor(null); in TableColumnModelListener columnAdded event. But still it's not working. See sample below (i've changed it to cell renderer coz result is clear on single view, but problem stays same)
    More over problem seems to be with algoritm that decide which class to use. Object takes preference any time. W/o it npe arries.
    Regards
    Adam
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableModel;
    public class Test extends JFrame {
        JTable table;
        Test() {
            // Create table model
            table = new JTable();
            table.setModel(new DefaultTableModel(
                new Object[][] {
                    { Boolean.TRUE, Integer.valueOf(10) },
                    { "Hallo!", Boolean.FALSE },
                }, new String[] { "Col1", "Col2" }));
            // Setup frame a little
            setLayout(new BorderLayout());
            setBounds(new Rectangle(300,300,200,100));
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            add(table,BorderLayout.CENTER);
            table.setDefaultRenderer(Object.class,new Renderer(Color.YELLOW));
            table.setDefaultRenderer(String.class,new Renderer(Color.BLUE));
            table.setDefaultRenderer(Boolean.class,new Renderer(Color.RED));
            table.setDefaultRenderer(Integer.class,new Renderer(Color.GREEN));
            // use default renderer in all columns
            table.getColumn(table.getColumnName(0)).setCellRenderer(null);
            table.getColumn(table.getColumnName(0)).setCellRenderer(null);       
        public static void main(String[] arg) {
            Test test = new Test();
            test.setVisible(true);
        class Renderer extends DefaultTableCellRenderer {
            Color color;
            Renderer(Color color) { this.color = color; }
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
                super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                setBackground(color);
                setToolTipText("Class is "+value.getClass().getName());
                return this;
    }Message was edited by:
    a3cchan

  • Cell Editor to limit characters in jtable cell

    Hello Java Gods,
    Can anyone help me or write for me a custom cell editor/renderer to limit the max number of characters in a jtable cell to be 10? By this, I mean, the user should not be able to type more than 10 characters in this particular cell.
    Any help would be greatly appreciated. I have to hand in this code before this evening. So please please help me folks.
    Thanking you all in advance.
    Warm Regards,
    Java Newbie

    Try one of these CellEditors:
    class LimitedEditor extends DefaultCellEditor {
        public LimitedEditor() {
            super(new JTextField());
        public boolean stopCellEditing() {
            String value = ((JTextField) getComponent()).getText();
            if (!value.equals("")) {
                if (value.length() > 10) {
                    ((JComponent) getComponent()).setBorder(new LineBorder(Color.red));
                    JOptionPane.showMessageDialog(null, "String length cannot be bigger than 10");
                    return false;
            return super.stopCellEditing();
        public Component getTableCellEditorComponent(final JTable table, final Object value,
                final boolean isSelected, final int row, final int column) {
            JTextField tf = ((JTextField) getComponent());
            tf.setBorder(new LineBorder(Color.black));
            if (value == null) {
                tf.setText("");
            } else {
                tf.setText(value.toString());
            return tf;
    class LimitedEditor2 extends DefaultCellEditor {
        public LimitedEditor2() {
            super(new JTextField());
            JTextField tf = ((JTextField) getComponent());
            tf.setDocument(new PlainDocument() {
                public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
                    int len = getLength();
                    if (len + str.length() > 10) {
                        Toolkit.getDefaultToolkit().beep();
                    } else {
                        super.insertString(offs, str, a);
    }Usage example:
            TableColumn tc = table.getColumnModel().getColumn(1);
            tc.setCellEditor(new LimitedEditor2());]

  • Cell rendering the JRadioButton in JTable(Most Urgent)

    Hai guys,
    How can I rendering the JRadioButton in JTable ?
    In JTable JCombo,JTexrField,JTextArea to be rendered.But I can't rendering the JRadioButton.
    This is urgent for me.
    By kavi...

    http://onesearch.sun.com/search/onesearch/index.jsp?qt=JRadioButton+in+JTable&qp=siteforumid%3Ajava57&chooseCat=allJava&col=developer-forums&site=dev

  • Problem using an editable JComboBox as JTable cell editor

    Hi,
    i have a problem using an editable JComboBox as cell editor in a JTable.
    When i edit the combo and then I press the TAB or ENTER key then all works fine and the value in the TableModel is updated with the edited one, but if i leave the cell with the mouse then the value is not passed to the TableModel. Why ? Is there a way to solve this problem ?
    Regards
    sergio sette

    if (v1.4) [url
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JTa
    le.html#setSurrendersFocusOnKeystroke(boolean)]go
    hereelse [url
    http://forum.java.sun.com/thread.jsp?forum=57&thread=43
    440]go here
    Thank you. I've also found this one (the first reply): http://forum.java.sun.com/thread.jsp?forum=57&thread=124361 Works fine for me.
    Regards
    sergio sette

  • Using two editor instances within JTable

    Hello,
    I'm struggling around using component editors within JTable. E.g. selectAll text on entering a JTextField cell or immediately raising the popup while entering a JComboBox cell.
    In my analysis most of these problems arises due the re-use of the cell editor.
    The event sequence is doing things in the context of the old cell while preparing the editor for the new cell has already been started.
    Because it is the same component and some things are bound deep inside the L&F it seems not easy to handle them properly.
    Just an idea from me is to avoid such problems by working with two instances for the editors in general. This should avoid all problems coming out of overlapping event processing. (To provide each cell with an own component is of course no solution)
    Any comment on such an approach?
    Thanks in advance
    Wolfgang R.

    No, it wasn't the custom JTable extension.
    By entering a cell a popup will be shown for a short moment. This is only by using Windows L&F (not Metal). Within the L&F a togglePopup() is called which may cause this problem.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.util.EventObject;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    public class JTableExt extends JTable {
         public static class ComboBoxEnumRenderer extends JComboBox implements
                   TableCellRenderer {
              public ComboBoxEnumRenderer() {
                   setEditable(false);
                   setBackground(Color.WHITE);
              public Component getTableCellRendererComponent(JTable table, Object value,
                        boolean isSelected, boolean hasFocus, int row, int column) {
                   this.removeAllItems();
                   this.addItem(value);
                   return this;
         public static class ComboBoxEnumEditor extends DefaultCellEditor {
              private static String[] values = null;
              public ComboBoxEnumEditor() {
                   super(new JComboBox());
                   values = new String[50000];
                   for (int i = 0; i < values.length; i++) {
                        values[i] = "row_" + i;
              public Component getTableCellEditorComponent(JTable table, Object value,
                        boolean isSelected, int row, int column) {
                   JComboBox combo = (JComboBox) getComponent();
                   combo.removeAllItems();
                   for (int i = 0; i < values.length; i++) {
                        combo.addItem(values);
                   combo.setSelectedIndex(0);
                   return super.getTableCellEditorComponent(table, value, isSelected, row,
                             column);
         public JTableExt() {
              super();
              init();
         // invoke editor on cell entry
         public void changeSelection(final int row, final int column, boolean toggle,
                   boolean extend) {
              super.changeSelection(row, column, toggle, extend);
              if (editCellAt(row, column))
                   getEditorComponent().requestFocusInWindow();
         private void init() {
              setDefaultEditor(Object.class, new ComboBoxEnumEditor());
              setDefaultRenderer(Object.class, new ComboBoxEnumRenderer());
         private static void setUI() {
              String lnfName = "";
              //lnfName = "com.jgoodies.plaf.plastic.Plastic3DLookAndFeel";
              lnfName = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
              try {
                   UIManager.setLookAndFeel(lnfName);
              } catch (Exception exc) {
         public static void main(String args[]) {
              try {
                   setUI();
                   javax.swing.JFrame frame = new javax.swing.JFrame();
                   frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                   frame.getContentPane().setLayout(new BorderLayout());
                   final JTableExt demo = new JTableExt();
                   Object[][] data = new Object[30][1];
                   demo.setModel(new DefaultTableModel(data, new String[] { "first column" }));
                   frame.getContentPane().add("Center", new JScrollPane(demo));
                   frame.setSize(600, 600);
                   frame.setVisible(true);
              } catch (Throwable t) {
                   System.exit(0);
    //end

  • Rendering custom class in JTable

    Greetings
    I am attempting to build an application that uses a JTable to display various attributes of seismic files. I want users to be able to display various attributes for each individual column so that they could display the actual value read from the file, the format used to read the value, the byte offset of the value or a string denoting all 3 attributes. I have created a class to hold the cell values
    public class SegyCell
         public static final int SHORT_INT = 0;
           public static final int LONG_INT = 1;
           public static final int IBM_FLOAT = 2;
           public static final int IEEE_FLOAT = 3;
           public static final int SINGLE_BYTE = 4;
         public final int SHOW_VALUE=0;
         public final int SHOW_FORMAT=1;
         public final int SHOW_BYTEPOS=2;
         public final int SHOW_ALL=3;
         private Object BytePosition;
         private Object Format;     
         private Object Value;
         private Object Displayed;
         public SegyCell(Object value,int bytepos,int format)
              //     trace header value from SEGY. keep byte position, format as well as value
              Value=value;
              BytePosition=new Integer(bytepos);
              Format=new Integer(format);
              Displayed=Value;
         public SegyCell(Object value)
              //     string or other value where format and bytepos arent important
              Value=value;
              Displayed=Value;
              BytePosition=null;
              Format=null;
         public void SetDisplay(int show)
              if(show==SHOW_VALUE)
                   Displayed=Value;
              else if(show==SHOW_FORMAT)
                   Displayed=Format;
              else if(show==SHOW_BYTEPOS)
                   Displayed=BytePosition;
              else
                   Displayed=Value;
         public Object GetDisplayed()
              return Displayed;
         }I store objects of SegyCell in each JTable cell.
    I have created a custom renderer
    class MySegyCellRenderer  extends  DefaultTableCellRenderer          
         public void setValue(SegyCell cell)
              Object value=cell.GetDisplayed();
              if(value.getClass().getName().equals("java.lang.String"))
                   setText(value.toString());
              else
                   java.text.NumberFormat format = NumberFormat.getNumberInstance();
                   setText(value== null ? "" : format.format(value));
    }I set the renderer for each column
         private void setColumnRenderers()
              for(int i=0;i<ColumnNames.length;i++)
                   TableColumn col=getColumn(ColumnNames);
                   col.setCellRenderer(new MySegyCellRenderer());
    I have tested my code and the SegyCell objects are being stored by the Table model. However when the table appears each cell is just filled with the address of the SegyCell object.
    Also the setValue method in my renderer is never used.
    Obviously I am doing something really dumb here but darned if I can see it. Any insights or whacks on the head would be most appreciated.
    Regards
    Doug Bath

    Thanks Nicholas
    You pointed me in the right direction. I had to make a slight change to my setValue method.
    class MySegyCellRenderer  extends  DefaultTableCellRenderer          
         public void setValue(Object ob)
              SegyCell cell=(SegyCell)ob;
              Object value=cell.GetDisplayed();
                 if(value.getClass().getName().equals("java.lang.String"))
                   setText(value.toString());
              else
                   java.text.NumberFormat format = NumberFormat.getNumberInstance();
                   setText(value== null ? "" : format.format(value));
    }And now my cells are rendering properly. I also used the setDefaultRenderer as suggested by camckr. My cells are appearing properly now.
    You are right in that Format and Byte position are always integer. However I only create them once and I may assign them to Displayed multiple times so I thought it best to make them Objects up front.
    Thanks again
    Doug

  • How to use Jtable cell Editor

    HI,
    Here trying to populate the ImageIcon using JLabel in Jtable cell. For that I used DefaultCellRenderer. For implement the mouseListener to label I used the DefaultCellEditor. I am facing one problem here. After editing the label I selected the second row of the table, the first row image is not displaying. Can any one help on this issue?
    public class LabelCellEditor extends DefaultCellEditor {
    public LabelCellEditor(final JCheckBox checkBox) {
    super(checkBox);
    public Component getTableCellEditorComponent(final JTable table, final Object value,
    final boolean isSelected, final int row, final int column) {
    Color background = null;
    background = ColorManager.SELECTED_ROW_BGCOLOR;
    labelVal = (JLabel) value;
    labelVal.setOpaque(true);
    labelVal.setFont(FontManager.TABLE_DATA_FONT);
    labelVal.setBackground(background);
    labelPanel = new JPanel();
    labelPanel.setOpaque(true);
    labelPanel.setBackground(background);
    labelPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
    labelPanel.setBorder(new EmptyBorder(5, 0, 0, 0));
    labelPanel.add(labelVal);
    return this.labelPanel;
    public Object getCellEditorValue() {
    return this.labelPanel;
    public class LabelCellRenderer extends DefaultTableCellRenderer {
    public LabelCellRenderer(final int alignment) {
    //setHorizontalAlignment(alignment);
    this.align = alignment;
    public Component getTableCellRendererComponent(final JTable table, final Object value,
    final boolean isSelected, final boolean hasFocus, final int row, final int column) {
    if (value != null) {
    if (value instanceof JLabel) {
    labelVal = (JLabel) value;
    labelVal.setOpaque(true);
    labelVal.setFont(FontManager.TABLE_DATA_FONT);
    labelVal.setBackground(background);
    labelVal.setHorizontalAlignment(this.align);
    labelVal.setBorder(new EmptyBorder(0, LRPADD, 0, LRPADD));
    JPanel panel = new JPanel();
    panel.setOpaque(true);
    panel.setBackground(background);
    panel.setLayout(new FlowLayout(FlowLayout.LEFT));
    panel.setBorder(new EmptyBorder(5, 0, 0, 0));
    panel.add(labelVal);
    return panel;
    return this;
    }

    With more than 30 postings you should know by now how to use the "Code" tags when posting code so the code reatains its original formatting and is therefore more readable.
    There is no need to create a custom editor, here is a simple example.

  • JPanel as a JTable Cell Editor

    I want to use a JPanel and as a JTable Cell Editor. The JPanel consists of a JTextField and a JButton. When I bring it up as an editor all works fine until I change the text field value and click on another line causing the editor to be stopped. Then my app seems to go into a processing frenzy which effectively stop me from doing anything else (the app has trouble repainting itself as well).
    I'm assuming I'm not passing an important message from the JPanel to the text field but am not sure. Has anyone had success in doing this? What am I missing?
    Thanks in advance,
    Phillip

    Looks like I was too quick off the draw in posting this.
    My problem was due to some old "expiremental" code that was processing key binding.
    Once I removed the unnecessary code all worked well.

  • AutoComplete JComboBox As JTable cell editor

    Hello, when I try to use AutoComplete JComboBox as my JTable cell editor, I facing the following problem
    1) Exception thrown when show pop up. - Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    2) Unable to capture enter key event.
    Here is my complete working code. With the same JComboBox class, I face no problem in adding it at JFrame. But when using it as JTable cell editor, I will have the mentioned problem.
    Any advice? Thanks
    import javax.swing.*;
    import javax.swing.JTable.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    * @author  yccheok
    public class NewJFrame extends javax.swing.JFrame {
        /** Creates new form NewJFrame */
        public NewJFrame() {
            initComponents();
                    /* Combo Box Added In JFrame. Work as expected. */
                    final JComboBox comboBox = new JComboBox();
                    comboBox.addItem("Snowboarding");
                    comboBox.addItem("Rowing");
                    comboBox.addItem("Chasing toddlers");   
                    comboBox.setEditable(true);
                    comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
                       public void keyReleased(KeyEvent e) {
                           if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                               System.out.println("is enter");
                               return;
                           System.out.println("typed");
                           comboBox.setSelectedIndex(0);
                           comboBox.showPopup();
                    getContentPane().add(comboBox, java.awt.BorderLayout.SOUTH);
        public JTable getMyTable() {
            return new JTable() {
                 Combo Box Added In JTable as cell editor. Didn't work as expected:
                 1. Exception thrown when show pop up.
                 2. Unable to capture enter key event.
                public TableCellEditor getCellEditor(int row, int column) {
                    final JComboBox comboBox = new JComboBox();
                    comboBox.addItem("Snowboarding");
                    comboBox.addItem("Rowing");
                    comboBox.addItem("Chasing toddlers");   
                    comboBox.setEditable(true);
                    comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
                       public void keyReleased(KeyEvent e) {
                           if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                               System.out.println("is enter");
                               return;
                           System.out.println("typed");
                           comboBox.setSelectedIndex(0);
                           comboBox.showPopup();
                    return new DefaultCellEditor(comboBox);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = getMyTable();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jScrollPane1.setViewportView(jTable1);
            getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
            pack();
        }// </editor-fold>                       
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        // End of variables declaration                  
    }

    You need to create a custom CellEditor which will prevent these problems from occurring. The explanation behind the problem and source code for the new editor can be found at Thomas Bierhance's site http://www.orbital-computer.de/JComboBox/. The description of the problem and the workaround are at the bottom of the page.

Maybe you are looking for

  • Blackberry 8310 not showing reply or send in sms text options menu

    I have a blackberry 8310. iam able to recieve sms text messages but when i click to on options, there is no "reply" option in the menu for me to be able to reply to the text. The chip works fine in other phones so that tells me something in the phone

  • Sy-tcode No Longer Exist in SRM 7.0

    Hi Experts, Right now we are doing a Upgrade from SRM 4.0 to SRM 7.0. In SRM 4.0 there is lot of code written with system variables like sy-tcode & sy-ucomm. I could do workaround of some system variables. But for If sy-tcode EQ 'BBPSOCO001' i could

  • What does it take to be a good DBA.

    Hi i am a student with 1 year to go and i interested in becoming a DBA i have no real world experience but i have done java ,php,prolog and i have good knowlege of sql queries. I do understand that you need to be good a drivers1,2,3 and 4

  • What add on do i need to remove to stop the following error

    keyword Add-on![Exception... "Component returned failure code: 0x8000ffff (NS_ERROR_UNEXPECTED) [nsIPrefBranch.getCharPref]" nsresult: "0x8000ffff (NS_ERROR_UNEXPECTED)" location: "JS frame :: chrome://keywords/content/overlay.xul :: <TOP_LEVEL> :: l

  • Loading a Picture onto the Scene

    I am trying to load a picture onto the scene by using the following action script commands: on (release) { loadMovie("Kjole1.jpg", ramme); Nothing happens when the button is released, so it doesn't work. "Kjole1.jpg" is a picture file in the same dir