Losing table CellRenderer in JTable

Hi,
I used the TableSorter in the SwingDemo page for a JTable. I had to extend this TableSorter to include some of the features in my original TableModel, such as allowing the data (Vector) to be refreshed by a TimerTask.
When my TableModel replaced the data Vector, I tell the TableSorter to setTableModel(), using the same one. Something like:
MyTableModel model = (MyTableModel)sorter.getTableModel();
model.replaceData(new_data_vector);
sorter.setTableModel(model);
which resulted in
1. clearSortingState();
2. fireTableStructureChanged();
Once it refreshed the table with new model, the CellRenderer for a column stopped functioning. All the CellRenderer does is to take the Long value from a column's data and formatt it to a date String. So the display is a String, but the back end model is a Long.
Could you tell me what am I doing wrong?

Swing related questions should be posted in the Swing forum.
fireTableStructureChanged();When the above method is fired the TableColumnModel is rebuilt causing all the renderers and editors to be reset to the defaults. So you need to either
a) reset the renderer to your custom renderer, or
b) use table.setAutoCreateColumnsFromModel(false) which will prevent the TableColumnModel from being recreated. This assume the table structure remains the same, only the data is changed.

Similar Messages

  • How to create a dynamic table were the JTable columns keep varying

    How to create a dynamic table were the JTable columns keep varying based on the input to the jtable

    Oooh, I lied. DefaultTableModel has an API for adding and
    removing columns. I didn't know that. You should have read
    the API.
    As for preferring to extend AbstractTableModel rather than
    DefaultTableModel, I think it's more correct. DefaultTableModel
    is a simple implementation of Abstract for basic cases. It isn't
    intended to be extended. I figure most people extending
    DefaultTableModel are also extending JFrame, JPanel, and Thread
    instead of encapsulating the first two and implementing
    Runnable for the third.

  • How To Display Table Header in JTable

    Hi,
    I have a tree node that is a JTable. It displays the cells, but not the header or the left hand side of the table.
    Here is my code ...
    Anyone got any ideas?
    public SimpleTree() {
    super("Creating a Simple JTree");
    WindowUtilities.setNativeLookAndFeel();
    addWindowListener(new ExitListener());
    Container content = getContentPane();
    JTable table;
         String columnNames[] = { "OrderID", "CustomerID", "EmployeeID", "Order Date", "Shipped Date" };
         String dataValues[][] =
              { "34", "234", "67","12/02/2002", "16/04/2002" },
              { "-123", "43", "853","12/02/2002", "16/04/2002" },
              { "93", "89.2", "109","12/02/2002", "16/04/2002" },
              { "279", "9033", "3092","12/02/2002", "16/04/2002" }
         table = new JTable( dataValues, columnNames );
         table.setEnabled(true);
         table.isCellEditable(4,4);
         table.setShowHorizontalLines(true);
         table.setShowVerticalLines(true);     
         table.getTableHeader().setForeground(Color.black);
         table.getTableHeader().setBackground(Color.lightGray);
         table.getTableHeader().setReorderingAllowed(true);
         table.getTableHeader().resizeAndRepaint();
         JTableHeader header = table.getTableHeader();
    header.setUpdateTableInRealTime(true);
    header.setReorderingAllowed(true);
         Object[] hierarchy =
    { "Orders",
    new Object[] { "Orders",
                                  table},
    new Object[] { "Prodcuts",
    new Object[] { "",
    table },
    "Employees",
    "Suppliers" };
         DefaultMutableTreeNode root = processHierarchy(hierarchy);
         JTree tree = new JTree(root);
         tree.putClientProperty("JTree.lineStyle", "Angled");
         tree.setCellRenderer(new MyTreeCellRenderer(table));
         tree.setCellEditor(new SimpleTreeCellEditor(table));
         tree.repaint();
         table.repaint();
         tree.setRowHeight(-2);      
         tree.setEditable(true);
         content.add(new JScrollPane(tree), BorderLayout.CENTER);
         setSize(275, 300);
    setVisible(true);

    The column header is a different component of the table component. You can get this component directly and place it wherever you want in a container, just get them from the JTable:JPanel aPanel = new JPanel( new BorderLayout() );
    JTable myTable = xxx;
    aPanel.add( myTable.getTableHeader() , BorderLayout.NORTH );
    aPanel.add( myTable, BorderLayout.CENTER );

  • Locked table columns in JTable?

    Does anyone know if a JTable can implement locked columns? By which I mean, I'd like to nominate 1 or more columns that remain locked to the left (or even right) of the table display and don't scroll out of view when scrolling horizontally.
    I can imagine some round-about ways of doing it, but I wonder if there's a simple way to do it.
    Thanks
    Iain

    Here is my attempt at this:
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class FixedColumnScrollPane extends JScrollPane
        public FixedColumnScrollPane(JTable main, int fixedColumns)
            super( main );
            //  Use the table to create a new table sharing
            //  the DataModel and ListSelectionModel
            JTable fixed = new JTable( main.getModel() );
            fixed.setSelectionModel( main.getSelectionModel() );
            fixed.getTableHeader().setReorderingAllowed( false );
            fixed.getTableHeader().setResizingAllowed( false );
            fixed.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
            main.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
            //  Remove the fixed columns from the main table
            for (int i = 0; i < fixedColumns; i++)
                TableColumnModel columnModel = main.getColumnModel();
                columnModel.removeColumn( columnModel.getColumn( 0 ) );
            //  Remove the non-fixed columns from the fixed table
            while (fixed.getColumnCount() > fixedColumns)
                TableColumnModel columnModel = fixed.getColumnModel();
                columnModel.removeColumn( columnModel.getColumn( fixedColumns ) );
            //  Add the fixed table to the scroll pane
            fixed.setPreferredScrollableViewportSize(fixed.getPreferredSize());
            setRowHeaderView( fixed );
            setCorner(JScrollPane.UPPER_LEFT_CORNER, fixed.getTableHeader());
        public static void main(String[] args)
            //  Build your table normally
            JTable table = new JTable(10, 8);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            JScrollPane scrollPane= new FixedColumnScrollPane(table, 2 );
            JFrame frame = new JFrame("Table Fixed Column Demo");
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            frame.getContentPane().add( scrollPane );
            frame.setSize(400, 300);
            frame.setVisible(true);
    }

  • Losing comboBox selection in JTable

    I have a JTable where one column consists of comboBoxes. It is possible to add and remove rows from this table using the associated buttons.
    Unfortunately if I have made a choice from a comboBox, yet not selected another cell in the table, then I use the 'add' button to add a new row, I lose the selection just made in the comboBox.
    If I first select another cell in the table this is not a problem and it works fine.
    Any help much appreciated....

    thanks for that, but I'm afraid it was no help.
    I'm using Java 1.1.7 and the getCellEditor(int, int) method doesn't exist. doing the same with getCellEditor() doesn't produce the required results.
    The comboBoxModel is updated when a new selection is made, but the cellEditor isn't updated until you click on another location in the table. Unfortunately I don't know how it goes about doing this, so I can't imitate it in my 'add' method

  • Updating tables directly from JTable

    Hi,
    Does anybody have a complete example showing how
    to read data from a table, show it on a JTable, let
    the user update its contents and finally write the
    data back to the table as he/she exits the frame ?
    Please send the code to me asap.
    Thanks a lot for the help,
    Maxsen

    I can help you out on how to use and manipulate JTable efficiently, but a forum is to be used for helping you in java, not for doing your work, so no code here.
    For your stuff, I would simply add a WindowListener in case the user close the window. Whenever that happens, the WindowListener will call some kind of a save() method. You can also add some menus and tools that will also call this method.
    I assume you know how to use JTable and WindowListener, as well as menus and toolbars in swing, ActionListener or better Action. If one of those names looks unfamiliar to you, I can provided additional informations, and yes, sample code with those explanations.

  • High CPU issue due to table.setForeground() in JTable renderer

    Hi,
    I have a JTable with a renderer to set the text color for the row if certain conditions exist.
    The code below "works" although I have two issues:-
    1. The command "table.setForeground(Color.BLUE);" in the code below causes 50% CPU utilisation (Win XP, service pack 3). Very strange and consistent - tested on two different PCs.
    2. At times, the first column below the intended column changes color. The rest of the intended column has color set correctly.
    I'm using beans binding with the table concerned so can't post the table model - I believe the binding effectively has it's own model.
    Be greatful for any insight as it seems v. strange.....
    Thanks,
    </code>
            masterTable.setDefaultRenderer(String.class, textColour);
        TableCellRenderer textColour = new TableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
                MailingList mL = (MailingList) queryList.get((table.convertRowIndexToModel(row)));
                table.setForeground(Color.BLACK);
                if (mL.getApplicationAppId() != null) {
                    if (mL.getApplicationAppId().getSembookingsCollection() != null) {
                        Collection sB = mL.getApplicationAppId().getSembookingsCollection();
                        if (!sB.isEmpty()) {
    //                        table.setForeground(Color.BLUE);  //this line causes 50% CPU utilisation ???
                TableCellRenderer delegate = table.getDefaultRenderer(Object.class);
                return delegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Here's my latest attempt, but still some questions and issues.
    I create a textColour class and this time attempt to set the colour on the component rather than the whole table in a similar fashion to the prepareRenderer(&hellip;) method.
    This appears to work and the CPU is no longer 50% utilisation.
    However, I still have the following questions/issues/observations:-
    1. I now need to set a renderer for each type of data. Perhaps this is the way it "should" be done. For example, I need to add " masterTable.setDefaultRenderer(Date.class, new textColour());" and then reformat the dates otherwise they don't change color. Would have been nice to set the colour for the whole row BUT can't see how as I can't use the preparedRenderer method?
    2. Perhaps related to the above, as I now return "comp", I don't call the default tableRenderer : i.e. " return delegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);" {code} Is there a cleaner/"better" way to do this? If I do return the above, I don't see any colour change as my changed "comp" is replaced by returning the component from the default call above.
    3. Persumably I'm no longer in a loop as CPU is "normal" and no where near 50% (more like 0%). I still set the row to be BLACK first otherwise all rows change colour (BLUE) but looks like the row isn't rendered until the component is returned.
    4. I no longer have the second issue of colour being incorrect for the first column of one row. So that's good!
    Here's the latest ver of the code.......
    Thanks,
    {code:java}
            masterTable.setDefaultRenderer(String.class, new textColour());
            masterTable.setDefaultRenderer(Date.class, new textColour());
          public class textColour extends DefaultTableCellRenderer {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
                MailingList mL = (MailingList) queryList.get((table.convertRowIndexToModel(row)));
                Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                if (value instanceof java.util.Date) {
                    this.setText(shortDf.format((Date) value));
                comp.setForeground(Color.BLACK);
                if (mL.getApplicationAppId() != null) {
                    if (mL.getApplicationAppId().getSembookingsCollection() != null) {
                        Collection sB = mL.getApplicationAppId().getSembookingsCollection();
                        if (!sB.isEmpty()) {
                            comp.setForeground(Color.BLUE);
    //            TableCellRenderer delegate = table.getDefaultRenderer(Object.class);
    //            return delegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                return comp;
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Losing table selection

    In the begining I didn't like the default table cell editor behavior. When the cell editor lost its focus, it was still active. The cell editor was active, it didn't return the value to the table model. This migh confuse the user, so I decided to use:
    table.putClientProperty( "terminateEditOnFocusLost",
                            Boolean.TRUE );But it still lacks something. When I'm losing the focus the, cell editor is being closed (nice), but I also lose the cell selection (which is a problem, because I have a button near the table which uses the data from the selected cell... the focus goes to the button -> the table loses it's selection -> I don't know which sell to refer to).
    I would appreciate any help.
    Best regards
    Marek

    Ech, it's not exactly as I sad. As I can see now, I can access table.getSelectedRow() from my button action litener. Sorry, my mistake. This problem never existed in the first place.
    Best regards
    Marek

  • How to handle  a large table using a JTable

    I want to create a lookup for the customer master file. And there is over 5000 records. so, what is the way to handle this case?
    ( if adding the all elements to vector or array, i think it is very time consuming and request many memory)
    thank you.

    Hi, I had similar problem - I had a table with about 100000 records - I was receiving java heap error when I was trying to load it. I have solved the task by loading data by portions - only when they are needed. Make a buffer (eg 200 records) of loaded data. Initially load first 200 records to it. Implements TableModel.getValueAt(row, col) in the way that if the row index is in currently loaded records range, return existing value. If it is out of range, replace data in buffer with data range containing requested value. For example, if row=50, take 50th row from loaded buffer; if row=450, first load records from 400th to 600th to your buffer, than take 50th value from it. Works perferct (table is scrlled with no problems) for 100000 records, mo memory overloading.
    The real problem appeared, when I had to sort this table - takes really long time.
    p.s. 5000 records is not too much - you can load all of them in one array and have no problems.

  • Merge table cells of JTable

    Can we merge two cells of JTable, the way we do it in html using rowspan and colspan?

    no, that's unsupported. There are some (partly oldish, google should help) experiments out there - but beware: they all require tweaks on the level of the ui-delegates which isn't a real option most of the time.
    Cheers
    Jeanette

  • Losing table vertical alignment when converting ditamap to book

    FrameMaker Version: 12.0.4.445 (latest, part of TCS5)
    I have a structured project, where several XML files have been arranged into a ditamap.
    For one of the XML files, I have a table, where I need to set Cell Vertical Alignment of the cells to MIDDLE.
    So using Paragraph Designer > Table Cell, I change the entries from Top to Middle (The defaults were Top).
    With the ditamap pane selected, I then go File menu >> Save Ditamap As
    I save the ditamap as "Book 12.0 with fm components (*.book)" file type.
    In the resulting book, the XML files are now .FM files.
    However, at this point, when I open the .FM file that has the table, the cell styles have reverted to TOP.
    I've searched high-and-low for a similar issue. This is looking like a bug to me, but can someone confirm?
    Thanks

    (Perhaps the moderator should move this to the FrameMaker Integration discussion (under RoboHelp).
    I've determined the correct settings for my purposes, that being vertical alignment in a FM-to-RH integration project. I originally thought it was specifically a FrameMaker issue, though the solution also involves settings in RoboHelp. Here are my findings:
    1. For the selected FM table, note its Table Tag in the Table Designer (e.g., FormatA). This will be used later.
    2. If there is table Entry > Image element, then select the Image element, and set its placement attribute = inline.
    Though inline is supposed to be the default, I found it necessary to state explicitly in order to control alignment of image within a RH table cell.
    3. Moving on from FM, in the CSS file that you are using with your RH project, suppose that you have defined your table as follows. Note that I'm using "CenterMiddle" as the title.
    table.CenterMiddle {
      width: 100% ! important ;  /* This forces the RH table to autofit the window */
      text-align: Center;
      font-family: "Adobe Garamond Pro";
      border-left-style: Solid;
      border-left-width: 1px;
      border-left-color: #000000;
      border-right-style: Solid;
      border-right-width: 1px;
      border-right-color: #000000;
      border-top-style: Solid;
      border-top-width: 1px;
      border-top-color: #000000;
      border-bottom-style: Solid;
      border-bottom-width: 1px;
      border-bottom-color: #000000;
    .CenterMiddle td {
      vertical-align: middle ! important ;  /* This forces the individual cells to align vertically */
      border-color: #000000;
      border-style: solid;
      border-width: 1px;
    4. Go to the RH project to which the FM project is linked.
    5. Go File menu > Project Settings.
    6. In the FrameMaker Document group, click Edit.
    7. Under FrameMaker Settings, locate the Table style that you noted in step (1), and set it to the name of your table from (3).
    At this point, you can update all the FM components in your RH project, and compile the RH project to get the desired results. In my case, I needed both text and images in the table cells to have vertical alignment = middle.

  • Getting a whole table into a JTable?

    Is there a short way to insert all table data (contained in a database) into a DefaultTableModel?

    What do you mean by "short"? The DefaultTableModel expects its data to be a Vector of Vectors or a two dimensional array and its headers to be a vector or array. So you're going to have to take the database data and put it into one of those structures. You can do that when you instantiate the DTM or use a the setDataVector(. . .) methods.
    Or, maybe extend DTM so that you can give it a ResultSet as its data and header info.
    Cheers
    DB

  • 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

  • Adding JButton in a JTable

    hi
    i know this has been discussed quite a number of times before, but i still couldn't figure it out..
    basically i just want to add a button to the 5th column of every row which has data in it.
    this is how i create my table (partially)
         private JTable clientTable;
         private DefaultTableModel clientTableModel;
    private JScrollPane scrollTable;
    clientTableModel = new DefaultTableModel(columnNames,100);
              clientTable = new JTable(clientTableModel);
              TableColumn tblColumn1 = clientTable.getColumn("Request ID");
              tblColumn1.setPreferredWidth(70);
              tblColumn1 = clientTable.getColumn("Given Name");
              tblColumn1.setPreferredWidth(300);
              tblColumn1 = clientTable.getColumn("Address");
              tblColumn1.setPreferredWidth(350);
              tblColumn1 = clientTable.getColumn("Card Serial");
              tblColumn1.setPreferredWidth(100);
              tblColumn1 = clientTable.getColumn("Print Count");
              tblColumn1.setPreferredWidth(70);
              tblColumn1 = clientTable.getColumn("Print?");
              tblColumn1.setPreferredWidth(40);
              clientTableModel.insertRow(0,data);
              //clientTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              scrollTable = new JScrollPane(clientTable);and i call this function void listInfoInTable(){
              JButton cmdPrint[];
              Vector columnNames = new Vector();
              Object[] data={"","","","","",""};
              Statement stmt=null;
              ResultSet rs=null;
              PreparedStatement ps;
              String query=null;
              String retrieve=null;
              int i,j=0;
              TableColumnModel modelCol = clientTable.getColumnModel();
              try{
                   con = DriverManager.getConnection(url);
                   JOptionPane.showMessageDialog(null,"Please wait while the program retrieves data.");
                   query="select seqNo, givenName, address1, address2, address3, address4, cardSerNr, PIN1, PrintFlag from PendPINMail where seqNo<250;";
                 ps = con.prepareStatement(query);
                 rs=ps.executeQuery();
                 while (rs.next()){
                      data[0]= rs.getString("seqNo");
                      data[1]= rs.getString("givenName");
                      data[2]= rs.getString("address1");
                      data[3]= rs.getString("cardSerNr");
                      data[4]= rs.getString("PrintFlag");
    //                  modelCol.getColumn(5).setCellRenderer();
                      clientTableModel.insertRow(j,data);
                      j++;
              }catch (SQLException ex){
                   JOptionPane.showMessageDialog(null,"Database error: " + ex.getMessage());
         } to display data from database inside the table.
    How do I add JButton to the 5th column of each row? This documentation here http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#width says that i need to implement TableCellEditor to put JButton in the table. How do i really do it? I want the button to call another function which prints the data from the row (but this is another story).
    Any help is greatly appreciated. Thanks

    you would need CellRenderer i think that it is in
    javax.swing.table.*;
    see if you can get started with that.
    Davidthanks, i'll try and have a look at it
    Yes, that's definitely what you need to start with,
    but you also need a CellEditor to return the
    button as well, otherwise the button will not be
    clickable (the renderer just paints the cell for
    display, it doesn't allow you to interact with it).
    You could maintain a list of components for rendering
    each cell of the table so that your
    CellRenderer and CellEditor always
    return the same object (i.e. a JButton for any
    given cell).
    CB.thanks for the info.. could you point me to some examples? is sounds quite complicated for me....
    thanks again

  • Cannot get text file to print in jtable. Using text file as a database

    Instead of doing JDBC i am using text file as database. I cant get data from text file to print into JTable when i click find button. Goal is to find a record and print that record only, but for now i am trying to print all the records. Once i get that i will change my code to search desired record and print it. when i click the find button nothing happens. Can you please take a look at my code, dbTest() method. thanks.
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import java.io.*;
    public class GUIdirectory extends JFrame
    implements ActionListener {
    // Define the components and the layout
    JLabel inputLabel_lastname = new JLabel("Last Name");
    JTextField inputText_lastname = new JTextField("Last Name",15);
    JLabel inputLabel_firstname = new JLabel("First Name");
    JTextField inputText_firstname = new JTextField(" ",15);
    JLabel inputLabel_middleinitial = new JLabel("Middle Initial");
    JTextField inputText_middleinitial = new JTextField(" ",4);
    JButton inputButton = new JButton("Find");
    JPanel inputLayout = new JPanel(new FlowLayout(FlowLayout.CENTER,5,5));
    JButton jButton1 = new JButton();
    //create a new table and scrollpane
    JTable dataTable = new JTable();
    JScrollPane dataTableScrollPane = new JScrollPane();
    public static void main(String args[]) {
    GUIdirectory gui = new GUIdirectory("Telephone Directory");
    gui.show();
    gui.pack();
    //TokenTest tt = new TokenTest();
    //gui.dbTest();
    public GUIdirectory(String Title) {
    super(Title);
    // Add ourselves as a listener for the window closing
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    exitWindow(1); }
    inputLabel_lastname.setLabelFor(inputText_lastname);
    inputText_lastname.setHorizontalAlignment(JTextField.RIGHT);
    inputText_lastname.addActionListener(this);
    inputLabel_firstname.setLabelFor(inputText_firstname);
    inputText_firstname.setHorizontalAlignment(JTextField.RIGHT);
    inputText_firstname.addActionListener(this);
    inputLabel_middleinitial.setLabelFor(inputText_middleinitial);
    inputText_middleinitial.setHorizontalAlignment(JTextField.RIGHT);
    inputText_middleinitial.addActionListener(this);
    inputButton.addActionListener(this);
    inputLayout.add(inputLabel_lastname);
    inputLayout.add(inputText_lastname);
    inputLayout.add(inputLabel_firstname);
    inputLayout.add(inputText_firstname);
    inputLayout.add(inputLabel_middleinitial);
    inputLayout.add(inputText_middleinitial);
    inputLayout.add(inputButton);
    getContentPane().setLayout(new BorderLayout(5,5));
    getContentPane().add("North",inputLayout);
    dataTableScrollPane.setViewportView(dataTable);
    getContentPane().add("Center",dataTableScrollPane);
    // A default method, primarily used for testing.
    public void actionPerformed(ActionEvent evt) {
    GUIdirectory gui = new GUIdirectory();
    gui.dbTest();
    void dbTest() {
    DataInputStream dis = null;
    String dbRecord = null;
    String hold;
    try {
    File f = new File("customer.txt");
    FileInputStream fis = new FileInputStream(f);
    BufferedInputStream bis = new BufferedInputStream(fis);
    dis = new DataInputStream(bis);
    Vector dataVector = new Vector();
    Vector headVector = new Vector(2);
    Vector row = new Vector();
    // read the record of the text database
    while ( (dbRecord = dis.readLine()) != null) {
    StringTokenizer st = new StringTokenizer(dbRecord, ",");
    while (st.hasMoreTokens()) {
    row.addElement(st.nextToken());
    System.out.println("Inside nested loop: " + row);
    System.out.println("inside loop: " + row);
    dataVector.addElement(row);
    System.out.println("outside loop: " + row);
    headVector.addElement("Title");
    headVector.addElement("Type");
    dataTable = new JTable(dataVector, headVector);
    dataTableScrollPane.setViewportView(dataTable);
    } catch (IOException e) {
    // catch io errors from FileInputStream or readLine()
    System.out.println("Uh oh, got an IOException error!" + e.getMessage());
    } finally {
    // if the file opened okay, make sure we close it
    if (dis != null) {
    try {
    dis.close();
    } catch (IOException ioe) {
    } // end if
    } // end finally
    } // end dbTest
    // Exits the program upon closing the window
    public void exitWindow(int i) {
    System.exit(i);
    public GUIdirectory() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void jbInit() throws Exception {
    jButton1.setText("jButton1");
    this.getContentPane().add(jButton1, BorderLayout.CENTER);

    Nothing happens because in the actionPerformed() method you are creating a new version of GUIdirectory. You just want to execute the dbTest() method of the current instance of GUIdirectory.
    The code should be:
    public void actionPerformed(ActionEvent evt)
    //GUIdirectory gui = new GUIdirectory();
    //gui.dbTest();
    dbTest();

Maybe you are looking for

  • Financial document - Letter of credit not updated

    Hi , The financial document ( LC) open value is not updated in vx13n after the PGI  and billing even though accounting document is generated in both the cases. We have assigned the financial document at the item level in the sales order. Aslo we have

  • How to write an outer join

    Hi, Let's suppose I have to write an outer join like this: select ... from table_1 a, table_2 b where a.field1 = b.field1 and a.field2 >= b.field2 but I know that for some values there might not to be a matching between the two tables. Should I rewti

  • Storing xml in oracle 8i db

    Hi, I'm trying to store a XML string into a long coloumn in Oracle 8i database. I'm doing this thro a Stored Procedure. when the size of the XML statemene goes beyond 4000, i get the following error message on the command.execute statement "ORA-01460

  • Can the SSD in a MBA 4,1 work in a MBA 3,1?

    I was considering upgrading the SSD in a MBA 13 (late 2011) and using the stock SSD in a MBA 11 (late 2010). Any reason why this might not work - or should it work fine? Thanks.

  • Find and Replace issue

    Hello all. I must have clicked something I should not have. In the past I could search for a string ( $username ) and no issues at all...it would find them. Now if I have the dollar sign ( $ ) in the find section it will find nothing.  When there are