Size of combobox in JTable with custom cell editor

Hi All -
I have a JTable that displays a combobox in certain cells. I have a custom table model, renderer, and editor. All of that works fine. I render the combobox with the renderer, and then return the combobox as an editor in the editor so that it can drop down and actually be of use. My problem is - I set the size of the combobox with a setBounds call in the renderer, I add it to a panel, and return the panel - because I dont want the combobox to take up the entire space of the cell. This approach fails in the editor. The setBounds and setSize calls have no effect. As soon as you click the combobox, the editor takes over and all of a sudden the combobox resizes to the entire area of the cell. I assume this is because in the editor you arent actually placing anything - your simply returning the "editing form" of the component.
So - anybody know of a way to work around this? Worst case, I could just allow the combobox to use the entire area of the cell - but it makes it uglier so I figured I would run it by the forums.
Eric

Rather than just redirect you to my previous answer from ages ago, I'll just give it again. :-)
You can actually do this, but you have to get tricky. By default, the dropdown's width will be the same width as the cell... but it doesn't have to be that way. Essentially what you have to do is override the UI (MetalComboBoxUI) for the combo component. In your new customized UI component subclass (that you set the combo to use), modify the the createPopup() method of this UI class, and add your own logic to set the size of the popup before you return it.
Ideally the size would be based on the computed max width of a rendered item shown in the combo, but really you could set it to whatever just to see how it works.

Similar Messages

  • Problem sorting JTable with custom cell editor

    Greetings,
    I have created a JTable with a JComboBox as the cell editor for the first column. However, I couldn't simply set the default cell editor for the column to be a JComboBox, since the values within the list were different for each row. So instead, I implemented a custom cell editor that is basically just a hashtable of cell editors that allows you to have a different editor for each row in the table (based on the ideas in the EachRowEditor I've seen in some FAQs - see the code below). I also used a custom table model that is essentially like the JDBCAdapter in the Java examples that populates the table with a query to a database.
    The problem comes when I try to sort the table using the TableSorter and TableMap classes recommended in the Java Tutorials on JTables. All of the static (uneditable) columns in the JTable sort fine, but the custom cell editor column doesn't sort at all. I think that the problem is that the hashtable storing the cell editors never gets re-ordered, but I can't see a simple way to do that (how to know the old row index verses the new row index after a sort). I think that I could implement this manually, if I knew the old/new indexes...
    Here's the code I use to create the JTable:
    // Create the Table Model
    modelCRM = new ContactTableModel();
    // Create the Table Sorter
    sorterCRM = new TableSorter(modelCRM);
    // Create the table
    tblCRM = new JTable(sorterCRM);
    // Add the event listener for the sorter
    sorterCRM.addMouseListenerToHeaderInTable(tblCRM);
    Then, I populate the column for the custom cell editor like this:
    // Add the combo box for editing company
    TableColumn matchColumn = getTable().getColumn("Match");
    RowCellEditor rowEditor = new RowCellEditor();
    // loop through and build the combobox for each row
    for (int i = 0; i < getTable().getRowCount(); i++) {
    JComboBox cb = new JComboBox();
    cb.addItem("New");
    //... code to populate the combo box (removed for clarity)
    rowEditor.add(i,new DefaultCellEditor(cb, i))); //TF
    } // end for
    matchColumn.setCellEditor(rowEditor);
    Any ideas how to do this, or is there a better way to either sort the JTable or use a combobox with different values for each row? Please let me know if more code would help make this clearer...
    Thanks,
    Ted
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class RowCellEditor implements TableCellEditor
    protected Hashtable editors;
    protected TableCellEditor editor, defaultEditor;
    public RowCellEditor()
    editors = new Hashtable();
    defaultEditor = new DefaultCellEditor(new JTextField());
    public void add(int row, TableCellEditor editor)
    editors.put(new Integer(row), editor);
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column)
    editor = (TableCellEditor) editors.get(new Integer(row));
    if (editor == null)
    editor = defaultEditor;
    return editor.getTableCellEditorComponent(table,
    value,
    isSelected,
    row,
    column);
    public Object getCellEditorValue() {
    return editor.getCellEditorValue();
    public boolean stopCellEditing() {
    return editor.stopCellEditing();
    public void cancelCellEditing() {
    editor.cancelCellEditing();
    public boolean isCellEditable(EventObject anEvent) {
    return true; //TF
    //return editor.isCellEditable(anEvent);
    public void addCellEditorListener(CellEditorListener l) {
    editor.addCellEditorListener(l);
    public void removeCellEditorListener(CellEditorListener l) {
    editor.removeCellEditorListener(l);
    public boolean shouldSelectCell(EventObject anEvent) {
    return editor.shouldSelectCell(anEvent);
    -------------------

    Well, I found a solution in another post
    (see http://forum.java.sun.com/thread.jsp?forum=57&thread=175984&message=953833#955064 for more details).
    Basically, I use the table sorter to translate the row index for the hashtable of my custom cell editors. I did this by adding this method to the sorter:
    // This method is used to get the correct row for the custom cell
    // editor (after the table has been sorted)
    public int translateRow(int sortedRowIndex)
    checkModel();
    return indexes[sortedRowIndex];
    } // end translateRow()
    Then, when I create the custom cell editor, I pass in a reference to the sorter so that when the getTableCellEditorComponent() method is called I can translate the row to the newly sorted row before returning the editor from the hashtable.

  • JTable with custom cell for folding and unfolding rows

    Hi,
    I am trying to implement a JTable, whereas one of the columns is a custom component, which has a small + in the right upper corner.
    When you push this + the JTable should unfold other rows, giving more detail on the current row.
    So something like this :
    |--------------------------------|
    |   <some-string>              + |
    |--------------------------------|Drawing this custom component for the column is no problem but I am having trouble implementing the MouseMotionListener events over this.
    If I add a mouseMotionListener to the JTable, I am able to forward these events to my custom class which draws this custom component.
    But off course the X and Y coordinates of this MouseEvent are not mapped into the grid of my custom component, which poses my question.
    How can I attach to each cell of this custom column of my JTable, a listener as to implement some mouseover and mouseclick stuff ?
    In case this post is not all that clear, I will try to add a demo showing my problem.
    Kind regards,
    Wim.

    You're reinventing a wheel that's been done a few times. One example is JTreeTable (http://community.java.net/javadesktop/) but there are others.

  • JTable with more cell editors??

    Hi,
    I have a JTbale in which I have two special columns- one with buttons and the other similar to the the color changer from the swing tutorial.
    My question is should I have now two renders and two editors in this situation?
    Tnax

    should I have now two renders and two editors in this situation?You should!
    ;o)
    V.V.

  • JTable custom cell editor losing focus

    This is a followup to Re: Tutorial on AWT/Swing control flow wherein I ask for pointers to help me understand the source of focus-loss behaviour in my JTable's custom cell editor.
    I have done some more investigations and it turns out that the focus loss is a more general problem with custom cell editors which call other windows. Even the color-picker demo in the JTable tutorial at http://download.oracle.com/javase/tutorial/uiswing/examples/components/index.html#TableDialogEditDemo has this problem, IF you add a text field or two to the layout BEFORE the table. The only reason the table in the demo doesn't lose the focus when the color-picker comes out is because the table is the only thing in the window!
    Here is the demo code, augmented with two text fields, which are admittedly ugly here but which serve the desired purpose:
    * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions
    * are met:
    *   - Redistributions of source code must retain the above copyright
    *     notice, this list of conditions and the following disclaimer.
    *   - Redistributions in binary form must reproduce the above copyright
    *     notice, this list of conditions and the following disclaimer in the
    *     documentation and/or other materials provided with the distribution.
    *   - Neither the name of Oracle or the names of its
    *     contributors may be used to endorse or promote products derived
    *     from this software without specific prior written permission.
    * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
    * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    import javax.swing.*;
    import javax.swing.border.Border;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class TableDialogEditDemo extends JPanel {
        public class ColorEditor extends AbstractCellEditor
                implements TableCellEditor,
                ActionListener {
            Color currentColor;
            JButton button;
            JColorChooser colorChooser;
            JDialog dialog;
            protected static final String EDIT = "edit";
            public ColorEditor() {
                //Set up the editor (from the table's point of view), which is a button.
                //This button brings up the color chooser dialog, which is the editor from the user's point of view.
                button = new JButton();
                button.setActionCommand(EDIT);
                button.addActionListener(this);
                button.setBorderPainted(false);
                //Set up the dialog that the button brings up.
                colorChooser = new JColorChooser();
                dialog = JColorChooser.createDialog(button, "Pick a Color", true,  //modal
                        colorChooser, this,  //OK button handler
                        null); //no CANCEL button handler
             * Handles events from the editor button and from the dialog's OK button.
            public void actionPerformed(ActionEvent e) {
                if (EDIT.equals(e.getActionCommand())) {
                    //The user has clicked the cell, so bring up the dialog.
                    button.setBackground(currentColor);
                    colorChooser.setColor(currentColor);
                    dialog.setVisible(true);
                    //Make the renderer reappear.
                    fireEditingStopped();
                } else { //User pressed dialog's "OK" button
                    currentColor = colorChooser.getColor();
            public Object getCellEditorValue() {
                return currentColor;
            public Component getTableCellEditorComponent(JTable table,
                                                         Object value,
                                                         boolean isSelected,
                                                         int row,
                                                         int column) {
                currentColor = (Color) value;
                return button;
        public class ColorRenderer extends JLabel
                implements TableCellRenderer {
            Border unselectedBorder = null;
            Border selectedBorder = null;
            boolean isBordered = true;
            public ColorRenderer(boolean isBordered) {
                this.isBordered = isBordered;
                setOpaque(true);
            public Component getTableCellRendererComponent(
                    JTable table, Object color,
                    boolean isSelected, boolean hasFocus,
                    int row, int column) {
                Color newColor = (Color) color;
                setBackground(newColor);
                if (isBordered) {
                    if (isSelected) {
                        if (selectedBorder == null) {
                            selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
                                    table.getSelectionBackground());
                        setBorder(selectedBorder);
                    } else {
                        if (unselectedBorder == null) {
                            unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
                                    table.getBackground());
                        setBorder(unselectedBorder);
                return this;
        public TableDialogEditDemo() {
            super(new GridLayout());
            JTextField tf1 = new JTextField("tf1");
            add(tf1);
            JTextField tf2 = new JTextField("tf2");
            add(tf2);
            JTable table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            table.setFillsViewportHeight(true);
            JScrollPane scrollPane = new JScrollPane(table);
            table.setDefaultRenderer(Color.class,
                    new ColorRenderer(true));
            table.setDefaultEditor(Color.class,
                    new ColorEditor());
            add(scrollPane);
        class MyTableModel extends AbstractTableModel {
            private String[] columnNames = {"First Name",
                    "Favorite Color",
                    "Sport",
                    "# of Years",
                    "Vegetarian"};
            private Object[][] data = {
                    {"Mary", new Color(153, 0, 153),
                            "Snowboarding", new Integer(5), new Boolean(false)},
                    {"Alison", new Color(51, 51, 153),
                            "Rowing", new Integer(3), new Boolean(true)},
                    {"Kathy", new Color(51, 102, 51),
                            "Knitting", new Integer(2), new Boolean(false)},
                    {"Sharon", Color.red,
                            "Speed reading", new Integer(20), new Boolean(true)},
                    {"Philip", Color.pink,
                            "Pool", new Integer(10), new Boolean(false)}
            public int getColumnCount() {
                return columnNames.length;
            public int getRowCount() {
                return data.length;
            public String getColumnName(int col) {
                return columnNames[col];
            public Object getValueAt(int row, int col) {
                return data[row][col];
            public Class getColumnClass(int c) {
                return getValueAt(0, c).getClass();
            public boolean isCellEditable(int row, int col) {
                if (col < 1) {
                    return false;
                } else {
                    return true;
            public void setValueAt(Object value, int row, int col) {
                data[row][col] = value;
                fireTableCellUpdated(row, col);
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("TableDialogEditDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JComponent newContentPane = new TableDialogEditDemo();
            newContentPane.setOpaque(true);
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }When you come back from choosing a color, tf1 is given the focus, instead of the table. This is because bringing the color picker window to the front causes a focus lost event for the cell editor component; it's temporary, as it should be, so why on earth is the system losing track of who has focus in the window??
    I see the following in Window#getMostRecentFocusOwner():
      public Component getMostRecentFocusOwner()
        if (isFocused())
          return getFocusOwner();
        else
          Component mostRecent =
            KeyboardFocusManager.getMostRecentFocusOwner(this);
          if (mostRecent != null)
            return mostRecent;
          else
            return (isFocusableWindow())
                   ? getFocusTraversalPolicy().getInitialComponent(this)
                   : null;
      }My app has a custom focus traversal policy, so I'm able to see who is being called, and indeed, getInitialComponent() is being called. Clearly, the KeyboardFocusManager is actually losing track of the fact that the table was focussed at the point where control was transferred to the color picker! This strikes me as completely unreasonable, especially since, as noted, this is a temporary focus loss event, not a permanent one.
    I'd be grateful for any wisdom in solving this, since similar behaviour to this little demo -- without focus loss, naturally -- is an essential part of my application.

    Looks like it is because the 'restore-focus-to-previous-after-modal-dialog-close' is in a later event than when the control returns to the action performed (which I guess makes sense: it continues the action event handler and the focus events are handled later, but I needed two chained invoke laters so it might also be that the OS events comes later).
    The following works for me (in the actionPerformed edited):
               // create the dialog here so it is correctly parented
               // (otherwise sometimes OK button not correctly the default button)
               dialog = JColorChooser.createDialog(button, "Pick a Color", true,  //modal
                            colorChooser, this,  //OK button handler
                            null); //no CANCEL button handler
                    //The user has clicked the cell, so bring up the dialog.
                    button.setBackground(currentColor);
                    colorChooser.setColor(currentColor);
                    button.addFocusListener(new FocusListener() {
                        @Override
                        public void focusLost(FocusEvent e) {}
                        @Override
                        public void focusGained(FocusEvent e) {
                            // dialog closed and focus restored
                            button.removeFocusListener(this);
                            fireEditingStopped();
                    dialog.setVisible(true);but a simpler request might be better (althoug I still need an invoke later):
    // rest as before except the FocusListener
                    dialog.setVisible(true);
                    button.requestFocusInWindow();
                    EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            fireEditingStopped();
                    });And a quick fix to the renderer so you can actualy see the focus on it:
                    if(hasFocus) {
                        Border border = DefaultLookup.getBorder(this, ui, "Table.focusCellHighlightBorder");
                        setBorder(BorderFactory.createCompoundBorder(
                                border, BorderFactory.createMatteBorder(1, 4, 1, 4,
                                        ((MatteBorder) getBorder()).getMatteColor())));
                    }

  • JTable custom cell editor focus problem

    Hi I have created a JTable (using Java 1.4.2) and have three cell Editors, one is a JFormattedTextField, one is a JComboBox and one is a custom cell editor.
    When I press tab I can select the cell with the JFormattedTextField and when I start typing the JFormattedTextField accepts my input and it is displayed in the cell. This is the type of behaviour I would like but it does not seem to work for my other 2 cell editors:
    When I tab to the JComboBox cell I can see that the cell is selected but typing or using the arrow keys does not allow me to select a new value in the JComboBox. (I have also tried typing space or enter to activate the JComboBox whilst the cell is selected.) The only ways to select a new value at the moment is to first click on the cell with the mouse and then use the keyboard to select a new value. It is like the actual JComboBox is not receiving the focus? Does anyone know how to solve this problem?
    I also seem to have the same problem with my custom cell editor. My custom editor is a JPanel which contains JFormattedTextField again I can tab to the cell and see that it is selected but to activate the JFormattedTextField I have to actually select it with the mouse.
    I have been stuck on this for some time so if any one has any suggestions they would be much appreciated !

    Hi I have created a JTable (using Java 1.4.2) and have three cell Editors, one is a JFormattedTextField, one is a JComboBox and one is a custom cell editor.
    When I press tab I can select the cell with the JFormattedTextField and when I start typing the JFormattedTextField accepts my input and it is displayed in the cell. This is the type of behaviour I would like but it does not seem to work for my other 2 cell editors:
    When I tab to the JComboBox cell I can see that the cell is selected but typing or using the arrow keys does not allow me to select a new value in the JComboBox. (I have also tried typing space or enter to activate the JComboBox whilst the cell is selected.) The only ways to select a new value at the moment is to first click on the cell with the mouse and then use the keyboard to select a new value. It is like the actual JComboBox is not receiving the focus? Does anyone know how to solve this problem?
    I also seem to have the same problem with my custom cell editor. My custom editor is a JPanel which contains JFormattedTextField again I can tab to the cell and see that it is selected but to activate the JFormattedTextField I have to actually select it with the mouse.
    I have been stuck on this for some time so if any one has any suggestions they would be much appreciated !

  • JTable & custom cell editor

    Hello everyone,
    what is the correct way of writing a custom cell editor for a JTable? I followed the example in the Java tutorial ([How to use tables|http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editor]), but the result is a bit weird. The code I have is the following:
        private class NumericCellEditor extends AbstractCellEditor implements TableCellEditor {
            NumericFTField field = new NumericFTField(threeDecimalsFormat, 3, null, 1);
            public Component getTableCellEditorComponent(JTable table, Object value,
                    boolean isSelected, int row, int col) {
                field.setValue(value);
                return field;
            public Object getCellEditorValue() {
                return field.getValue();
            @Override
            public boolean stopCellEditing() {
                if (((NumericFTField)field).verifyDouble()) {
                    field.setBorder(new EmptyBorder(0, 0, 0, 0));
                    fireEditingStopped();
                    return true;
                } else {
                    field.setBorder(BorderFactory.createLineBorder(Color.red));
                    return false;
        }where the NumericFTField is a class derived from JFormattedTextField that only allows digits, decimal separator, minus and 'E' to be inserted, and it monitors clipboard operations. verifyDouble() is a method of the NumericFTField class that verifies whether the current input can be parsed to a double and whether it satisfies everything it should. This is then used in
    ((TableColumn)jTblSpecs.getColumnModel().getColumn(1)).setCellEditor(new NumericCellEditor());The NumericFTField class works great, I use it also in place of a JTextFields, so I'd say there is nothing wrong with it.
    After I click in a cell (single click), it behaves a little different that the default cell editor: the cell is not highlighted, but it immediately jumps to the editing state (why???). I, indeed, can insert the allowed characters only. When I click in a cell, do some editing and press Enter, the cell's content gets validated. If it is invalid, stopCellEditing() method does its magic; if it is valid, the caret disappears and everything SEEMS okay. However, if I started typing at this point, the cell reverts to the editing state, but now I am able to enter any character I want. It truly looks like the cell editor is now some other component, not the original NumericFTField one. What is going on here?
    It would be great is someone could provide a short schematic source of a custom cell editor class that would work exactly as the JTable's default one except it would only permit digits and so on. It doesn't have to be anything fancy, just a "skeleton" of the class with comments like "input verification here" etc.
    I am sorry for any lack of clarity, but I am still a Java newbie.
    Any help would be much appreciated.
    Best regards,
    vt

    Hi,
    I am also facing the same problem. In addition to what you have specified, my requirement is to be able to select multiple rows for deletion. But, the very first row selected using mouse is not visible as selected though its selected. The other rows are visible as selected.
    If you can use any JDK version, start using JDK1.6. You will not be facing this problem. There were so many changes done for swings from JDK 1.4 to 1.6. But, I have to strictly use JDK1.4, but could not find any workaround for this problem.
    It would be great if anyone can help me out in this issue to get workaround for this problem.

  • JTable Custom Cell Editor: how to get value?

    I have some custom cell renderers and editor. One of my custom cell editor is a text field that can popup a separat gui for easier data selection. As this text field alone with the popup gui works great, when i use this field in my custom jtable cell editor, the gui selected value is never displayed in the table cell. it just shows the old value.?

    Well, here's how I do it. I'm very new to Swing so I'm, not sure if this is the best way. If you find a better way, please repost on this message.
    My cell editor is a JPanel with a JTextfield in it. I make sure that the JTextfield will have default focus when the JPanel is focused.
    In the CellEditor, I add a KeyListener to the JTextField so that when the user hits enter, it fires the stopEditing. I then add a function to CellEditor that returns what's in the JTextField.
    In the code, m_value is the JTextField. You want to add MyKeyAdapter to the JTextField. Viola, it works!
          * This private class reads in an enter key.
         class MyKeyAdapter extends KeyAdapter {
              public void keyPressed(KeyEvent e) {
                   if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                        stopCellEditing();
          * Returns the value of the editor
          * @return the value of the editor
         public String getValue() {
              return m_value.getText();

  • JTable - Custom cell editor lossing commit

    Hello,
    I have a custom cell editor and a default renderer assigned to a specific cell in my table...
    I have the following problem :
    If i change the value of cell 'c1' from value 'v1' to 'v2' and press enter and go to another cell the value in 'c1' is rendered correctly as 'v2'
    Hoever if i change the value of cell 'c1' from 'v1' to 'v2' and simply click over to another cell the value in 'c1' stays rendered as 'v1'
    Question : Is there ANY way to mimic the behavior of the user pressing enter in my custom cell editor when a user simply selects another cell, i guess on loss of focus or something..
    This is the last problem i have on the current project i am on and its very annoying.
    Thanks in advance, any help appreciated..
    -Alan

    I have the same problem using a custom Date/Time Picker Object (which extends JComboBox) as an editor within a table cell. For simplicity sake, I am posting code using only the base editable JComboBox, but it exhibits the same symptoms. If you enter a value in the TextField portion of the ComboBox and Tab, your value remains the same. If you enter a value in the TextField portion of the ComboBox and click in another cell, the value returns to the previous value (before editing began).
    import java.awt.*;                                                  // BorderLayout
    import javax.swing.*;                                               // JTable, JFrame
    import javax.swing.table.*;                                         // DefaultTableModel
    public class Tester extends JFrame
      public static void main(String[] args)
        Tester test = new Tester();
      public Tester()
        String[] values = {"Test", "Values"};
        JComboBox combo = new JComboBox(values);
        combo.setEditable(true);
        DefaultCellEditor editor = new DefaultCellEditor(combo);
        JTable table = new JTable(2, 3);
        table.getColumn(table.getColumnName(0)).setCellEditor(editor);
        JScrollPane scroll = new JScrollPane(table);
        getContentPane().add(scroll, BorderLayout.CENTER);
        pack();
        setVisible(true);
    }

  • How to print jTable with custom header and footer....

    Hello all,
    I'm trying to print a jTable with custom header and footer.But
    jTable1.print(PrintMode,headerFormat,footerFormat,showPrintDialog,attr,interactive)
    does not allow multi line header and footer. I read in a chat that we can make custom header and footer and wrap the printable with that of the jTable. How can we do that..
    Here's the instruction on the chat...
    Shannon Hickey: While the default Header and Footer support in the JTable printing won't do exactly what you're looking for, there is a straight-forward approach. You can turn off the default header/footer and then wrap JTable's printable inside another Printable. This wrapper printable would then render your custom data, and then adjust the size given to the wrapped printable
    But how can i wrap the jTable's Printable with the custom header and footer.
    Thanks in advance,

    I also once hoped for an easy way to modify a table's header and footer, but found no way.
    Yet it is possible.

  • Positioning custom cell editors

    I've got a custom cell editor that Im using to edit the cells of my JTable.
    I cant use a DefaultCellEditor, as my editor will contain a JTree.
    When I display the editor, I want to position it along-side the cell which was selected for editing.
    I can see methods in JTable to find the row/column at a given Point, but cant find any to get the location of a chosen row/column.
    Does anyone know if there is a way to do this?

    Here is some code that I used with a lot of debug messages. My editor is a table and the movement references was because the table could be off the parent table panel. If it was too far to the right, I wanted to move my popup table to the left to compensate.
         * Return the editor component to the table
         * @param table container for the editor
         * @param value value from the model
         * @param isSelected is the cell selected (has focus)
         * @param row of the cell
         * @param column of the cell
         * @return aLabel is used to provide visual feedback that the editor is
         * working
        public Component getTableCellEditorComponent(
            JTable table, Object value, boolean isSelected, int row, int column)
            logger.debug("PicklistEditor: getTableCellEditorComponent.value(" + value + ")");
            editingRow = row;
            editingColumn = column;
            dataEntryTable = table;
            dataEntryTable.setSurrendersFocusOnKeystroke(true);
            Rectangle tableRectangle = dataEntryTable.getBounds();
            int tableRightEdge = tableRectangle.x + tableRectangle.width;
            Point p = dataEntryTable.getLocationOnScreen();
            Rectangle r = dataEntryTable.getCellRect(row, column, true);
            Rectangle picklistRectangle = picklistFrame.getBounds();
            logger.debug("PicklistEditor: table.getBounds() = " + table.getBounds());
            logger.debug("PicklistEditor: tableRightEdge = " + tableRightEdge);
            logger.debug("PicklistEditor: picklistFrame.getBounds() = " + picklistFrame.getBounds());
            picklistFrame.setLocation(p.x + r.x, p.y + r.y + r.height);
            picklistFrame.setVisible(true);
            logger.debug(
                "PicklistEditor: picklistFrame.getLocationOnScreen() = " +
                picklistFrame.getLocationOnScreen());
            int picklistRightEdge = picklistFrame.getLocationOnScreen().x + picklistRectangle.width;
            int moveRightAmount = 0;
            if (picklistRightEdge > tableRightEdge)
                moveRightAmount = picklistRightEdge - tableRightEdge;
                picklistFrame.setLocation((p.x + r.x) - moveRightAmount, p.y + r.y + r.height);
            logger.debug("PicklistEditor: picklistRightEdge = " + picklistRightEdge);
            logger.debug("PicklistEditor: moveRightAmount = " + moveRightAmount);
            javax.swing.SwingUtilities.invokeLater(
                new Runnable()
                public void run()
                    editField.requestFocusInWindow();
            aLabel.setText("Editing...");
            logger.debug("PicklistEditor: editPanel.getBounds(" + editPanel.getBounds() + ")");
            logger.debug("PicklistEditor: editInputPanel.getBounds(" + editInputPanel.getBounds() +
            logger.debug("PicklistEditor: acceptEditFieldButton.getBounds(" +
                acceptEditFieldButton.getBounds() + ")");
            logger.debug("PicklistEditor: picklistScrollPane.getBounds(" +
                picklistScrollPane.getBounds() + ")");
            return aLabel;
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • JTable with custom combobox

    Hi
    I been trying to create a JTable with a custom combobox, that is in a column the lists contained within each combobox is unique. I tried using a renderer, even though the combo appears I cannot select the combo for editing. Any suggestions on how to get the combo working properly would be appreciated thanks.

    It's been a few years since I did something like this, but my recollection is that you should implement the TableCellEditor interface and have the getTableCellEditor method return your custom combo box. Then, either override getCellEditor in your JTable to return your custom TableCellEditor or (better) call tableColumn.setCellEditor for the column you're interested in, passing an instance of your TableCellEditor. I suggest you return the same JComboBox from your implementation of getTableCellEditor every time, and either replace the underlying model or have a custom model in which you can easily switch the contents on-the-fly.
    Having done this in the past, I remember that it's quite easy to leak stuff - I wouldn't advise making a new JComboBox every time.
    Regards,
    Huw

  • JTable - help with custom cell renderers and editors

    I've got myself into a bit of a mess with cell renderers and editors.
    I've got a custom component that wants displaying in a column and then hand over all functionality to this component when you start editing it.
    Now how I went out about this was to create a custom cell renderer that extends this component and implements TableCellRenderer.
    I then created a table cell editor that extends AbstractCellEditor and implements TableCellEditor and this cell editor creates a new component when it's initialized. I then use setCellEditor(new MyCellEditor()) on the column and setCellRenderer(new MyCellRenderer()).
    This works slightly but I'm wondering how this is all implemented.
    When I set the cell editor on it's own it seems to be sharing a reference to the single component that's being used which means that if you edit one cell all the cells get changed to the new value.
    Thanks for the help,
    Alex

    only a few forums are actually browsedAnd theSwing forum is one of the most active. Did you search it for editiing examples? I've seen many editing examples posted in a SSCCE format.
    SSCEE is also impossible as the functionality spans over about 10 classes We did not ask for your application, we asked for a SSCCE. The whole point of a SSCCE is to simplify the 10 classes into a single class and maybe an inner class for the editor to make sure you haven't made a silly mistake that is hidden because of the complexity of your real application.

  • JTable with custom column model and table model not showing table header

    Hello,
    I am creating a JTable with a custom table model and a custom column model. However the table header is not being displayed (yes, it is in a JScrollPane). I've shrunk the problem down into a single compileable example:
    Thanks for your help.
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test1 extends JFrame
         public static void main(String args[])
              JTable table;
              TableColumnModel colModel=createTestColumnModel();
              TestTableModel tableModel=new TestTableModel();
              Test1 frame=new Test1();
              table=new JTable(tableModel, colModel);
              frame.getContentPane().add(new JScrollPane(table));
              frame.setSize(200,200);
              frame.setVisible(true);
         private static DefaultTableColumnModel createTestColumnModel()
              DefaultTableColumnModel columnModel=new DefaultTableColumnModel();
              columnModel.addColumn(new TableColumn(0));
              return columnModel;
         static class TestTableModel extends AbstractTableModel
              public int getColumnCount()
                   return 1;
              public Class<?> getColumnClass(int columnIndex)
                   return String.class;
              public String getColumnName(int column)
                   return "col";
              public int getRowCount()
                   return 1;
              public Object getValueAt(int row, int col)
                   return "test";
              public void setValueAt(Object aValue, int rowIndex, int columnIndex)
    }Edited by: 802416 on 14-Oct-2010 04:29
    added                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    Kleopatra wrote:
    jduprez wrote:
    See http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setHeaderValue(java.lang.Object)
    When the TableColumn is created, the default headerValue  is null
    So, the header ends up rendered as an empty label (probably of size 0 if the JTable computes its header size based on the renderer's preferred size).nitpicking (can't resist - the alternative is a cleanup round in some not so nice code I produced recently <g>):
    - it's not the JTable's business to compute its headers size (and it doesn't, the header's the culprit.) *> - the header should never come up with a zero (or near-to) height: even if there is no title shown, it's still needed as grab to resize/move the columns. So I would consider this sizing behaviour a bug.*
    - furthermore, the "really zero" height is a longstanding issue with MetalBorder.TableHeaderBorder (other LAFs size with the top/bottom of their default header cell border) which extends AbstractBorder incorrectly. That's easy to do because AbstractBorder itself is badly implemented
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459419
    Thanks for the opportunity to have some fun :-)
    JeanetteNo problem, thanks for the insight :)

  • Performance decrease with custom cell renderer

    Hi,
    Finally, I have my cell renderer working fine (it was simpler than I thought). Anyway, I'm suspecting something is not working quite well yet. When I try to reorder my colums (by dragging them) they move like slow motion. If I don't register my custom cell renderer, I can move my columns fine. Next is the code of my custom renderer.
    class PriorityRenderer extends DefaultTableCellRenderer {   
      public Component getTableCellRendererComponent(
      JTable table, Object value,     boolean isSelected,
      boolean hasFocus, int row, int column) {              
        if(value instanceof coloredValue) {
        coloredValue cv = (coloredValue)value;
        if(isSelected) this.setBackground(table.getSelectionBackground());
        else this.setBackground(cv.getbkColor());
        this.setForeground(cv.gettxColor());
        this.setText(value.toString());
        this.setOpaque(true);
        return this;
    }All the cells of my JTable are "coloredValue"s. This is a little class with a String, two colors and some getter methods.
    Can anyone giveme a hint ?
    Thanks!!

    OK! Now the performance problem is gone!! (I don't know why, I didn't touch a thing)
    Thanks anyway

Maybe you are looking for