Custom JTable

Hi, I need to get a JTable to display a JPanel in each of it's cells, with the JPanel being a chosen colour for each individual cell. Also some of the JPanels may also need to contain an instance of a Canvas item in them. Any ideas?? So far I can't even get the JPanel to show up let alone my custom JPanel or Canvas item.
Cheers,
Matt.

I think you are a bit lost.
Here we go:
Why do you need to display an JPanel in each cell?
What do you want your table to display?
java.awt.Canvas usually are not used with Swing. JPanel has itself replaced the position of Canvas, so use a JPanel for anything you would have used Canvas for.
Now to presumed answers from presumed questions:
1) I'll need to paint background differently for each cell in an JTable, what do I do?
You have a multitude of options, I will present two of them.
I presume you have a way of actually telling which colour should be used as background based upon the data in the tablemodel.
Version 1:
Make your own cell-renderer. In it is getTableCellRendererComponent, query nessecary data and set the correct and appropriate colour.
This can be easily done with a wrapper.
Example:
public class WrapperTableCellRenderer implements TableCellRenderer
  private TableCellRenderer tcr = null;
  public WrapperTableCellRenderer( TableCellRenderer tcr )
    this.tcr = tcr;
  public Component getTableCellRendererComponent(......)
     Component c = tcr.getTableCellRendererComponent(......);
     if( data.isThisGreen() )
        c.setBackground( Color.GREEN );
     return c;
}This you can easily use by just doing the following in your code:
JTable jt = new JTable();
jt.setCellRenderer( new WrapperTableCellRenderer( jt.getCellRenderer() ) );Alternative number two is to override the 'prepareRenderer(...)' in your JTable and do modifications there as well.
2) I'll need to paint customised shapes instead of text in my JTable, how do I do it?
This time you definiatly have to make your own TableCellRenderer that returns your JPanel that paints the customised shapes.
Regards,
Peter Norell

Similar Messages

  • F2 key not working with custom JTable Column

    I have a custom JTable Column (which is a JPanel with a JTextfield and JButton). Everything works as expected, except when the user presses "F2" to start editing the custom column cell. When the user presses F2, the custom cell goes into editing mode, but I am unable to type anything in it.
    Below is the SSCCE.
    Steps to Reproduce problem:
    1) Run the Program
    2) Select any cell in first Column.
    3) Press "F2" and try to type into the cell. Can't type anything.
    package com.ns;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.util.EventObject;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    public class TextButtonCellFrame extends javax.swing.JFrame {
        // Variables declaration - do not modify                    
        private JTextField inputText;
        private JScrollPane jScrollPane1;
        private JPanel testPanel;
        private JTable testTable;
        // End of variables declaration                  
        public TextButtonCellFrame() {
            initComponents();
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            testPanel = new JPanel();
            jScrollPane1 = new JScrollPane();
            testTable = new JTable();
            inputText = new JTextField();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            testTable.setModel(new DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            testTable.setCellSelectionEnabled(true);
            testTable.setRowHeight(52);
            testTable.setSurrendersFocusOnKeystroke(true);
            testTable.getColumnModel().getColumn(0).setCellRenderer(new MyTableCellRenderer());
            testTable.getColumnModel().getColumn(0).setCellEditor(new MyTableCellEditor(new JTextField()));
            testTable.getColumnModel().getColumn(0).setPreferredWidth(200);
            jScrollPane1.setViewportView(testTable);
            testPanel.add(jScrollPane1);
            inputText.setPreferredSize(new Dimension(50, 20));
            testPanel.add(inputText);
            getContentPane().add(testPanel, BorderLayout.CENTER);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-576)/2, (screenSize.height-417)/2, 576, 417);
        }// </editor-fold>                       
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TextButtonCellFrame().setVisible(true);
        public class MyTableCellRenderer extends JPanel implements TableCellRenderer {
            Point point;
            JButton button1 = new JButton("Test 1");
            JTextField txtField = new JTextField();
            public MyTableCellRenderer() {
                setLayout(new BorderLayout());
                this.add(button1, BorderLayout.EAST);
                this.add(txtField,BorderLayout.CENTER);
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
                if (isSelected) {
                    txtField.setBackground(testTable.getSelectionBackground());
                    txtField.setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
                else {
                    txtField.setBackground(testTable.getBackground());
                    txtField.setBorder(null);
                return this;
        public class MyTableCellEditor extends DefaultCellEditor {
            JPanel panel = new JPanel();
            JButton button1 = new JButton ("Test 1");
            JTextField txtField;
            MyTableCellEditor(JTextField txtField) {
                super (txtField);
                this.txtField = txtField;
                panel.setLayout(new BorderLayout());
                panel.add(button1, BorderLayout.EAST);
                panel.add(txtField,BorderLayout.CENTER);
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == button1)
                    JOptionPane.showMessageDialog(null, "Action One Successful");
            public Component getTableCellEditorComponent(JTable table, Object value,
                                        boolean isSelected, int row, int column) {
                return panel;
           public boolean isCellEditable(final EventObject anEvent) {
              if (anEvent instanceof KeyEvent) {
                 final KeyEvent keyEvent = (KeyEvent) anEvent;
                 SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                       if (!Character.isIdentifierIgnorable(keyEvent.getKeyChar())) {
                          txtField.setText(txtField.getText() + keyEvent.getKeyChar());
                       txtField.setCaretPosition(txtField.getText().length());
                       txtField.requestFocusInWindow();
                return super.isCellEditable(anEvent);
    }The code for isCellEditable(final EventObject anEvent) which is needed to edit the cell using keyboard was provided by DarrylBurke here
    regards,
    nirvan.

    The F2 key when pressed generates an action event (either JTable generates it or some other component). I am not sure how to handle the action event in the isCellEditable() method. Also, F(X) range of keys other than F2 dump some junk character in the JTextfield when pressed. I am now stuck at this point and don't know how handle F(X) range of keys.
    regards,
    nirvan.

  • Proble with Custom JTable Header

    Hi
    I want create Custom JTable with JTextField on column header, so that user can enter some text. As of now i am able to create the text box on header using custom TableCellRenderer but i am not able to make it editable.....
    Please help me. if any one need more info, pls let me know.

    KetuRai wrote:
    Then what should i do to achieve this functionality. Do any one have sample code?
    Or other alternative to achieve this.I don't know If this is the best way but my approach is using a InputDialog and a custom renderer.
    just click on the table header and input a text. Good Luck!
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    public class TableHeaderDemo {
        public void createAndShowUI() {
            JFrame frame = new JFrame("Click Table Header to change text");
            String[] columnName = {"CheckBox Column", "Data Column"};
            Object[][] data = {{"Data 1", "Data 2"},
            {"Data 3", "Data 4"}, {"Data 5", "Data 6"}};
            final JTable myTable = new JTable(data, columnName);
            myTable.getTableHeader().setDefaultRenderer(new MyRenderer());
            myTable.getTableHeader().addMouseListener(new java.awt.event.MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    int col = myTable.getTableHeader().columnAtPoint(e.getPoint());
                    String str = javax.swing.JOptionPane.showInputDialog("Enter a text: ");
                    myTable.getColumnModel().getColumn(col).setHeaderRenderer(new MyRenderer(str));
                    myTable.getTableHeader().revalidate();
                    myTable.getTableHeader().repaint();
            JScrollPane scrollPane = new JScrollPane(myTable);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setResizable(false);
            frame.getContentPane().add(scrollPane);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        class MyRenderer implements TableCellRenderer {
            JTextField text = new JTextField();
            MyRenderer(String str) {
                text.setText(str);
            MyRenderer() {
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) {
                text.setBorder(BorderFactory.createRaisedBevelBorder());
                text.setBackground(Color.BLUE);
                text.setForeground(Color.WHITE);
                text.setHorizontalAlignment(JTextField.CENTER);
                return text;
        public static void main(String[] args){
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new TableHeaderDemo().createAndShowUI();
    }

  • Custom JTable cell editor problem

    I have a custom JTable cell editor which is a JPanel with 2 JtextFields, One for a name, the other for a data value. My problem lies in when the the cell is selected and then the user start typing. The JTextfield outline shows up, but there is no carat. I can only edit the cell when I click the mouse in it again. I have my isCellEditable method set to only allow editing on 2 mouse clicks, but I did try it with just returning true and had the same problem. Please help.
    Code:
    class cellValue {
    String name;
    String data;
    Color nameColor;
    Color dataColor;
    Font font;
    public cellValue(String n, String d, Color nC, Color dC, Font ff){
    name = n;
    data = d;
    nameColor = nC;
    dataColor = dC;
    font = ff;
    } //end class
    public class TextFieldCellEditor extends JPanel implements TableCellRenderer, TableCellEditor{
    private EventListenerList listenerList = new EventListenerList();
    private ChangeEvent event = new ChangeEvent(this);
    private cellValue s;
    private int e_row=0;
    private int e_col=0;
    private JTextField ta;
    private JTextField tb;
    public TextFieldCellEditor() {
    setLayout(new GridBagLayout());
    ta = new JTextField();
    tb = new JTextField();
    tb.setHorizontalAlignment(SwingConstants.RIGHT);
    add(ta, new GridBagConstraints(0,0,1,1,0.6,0.0,java.awt.GridBagConstraints.WEST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    add(new JLabel(" "),new GridBagConstraints(1,0,1,1,0.1,0.0,java.awt.GridBagConstraints.WEST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    add(tb, new GridBagConstraints(2,0,1,1,0.3,0.0,java.awt.GridBagConstraints.EAST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    } //end init
    public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected,
    boolean hasFocus,int row, int column) {
    s = (cellValue)value;
    e_row = row;
    e_col = column;
    ta.setText(s.name);
    tb.setText(s.data);
    ta.setFont(s.font);
    tb.setFont(s.font);
    ta.setForeground(s.nameColor);
    tb.setForeground(s.dataColor);
    setForeground(table.getForeground());
    setBackground(table.getBackground());
    ta.setBackground(table.getBackground());
    tb.setBackground(table.getBackground());
    ta.setCaretColor(Color.WHITE);
    tb.setCaretColor(Color.WHITE);
    return (JComponent)(this);
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    return (getTableCellRendererComponent(table, value,isSelected, true, row, column));
    public boolean isCellEditable(EventObject e) {
    if (e instanceof MouseEvent) {
    return ((MouseEvent)e).getClickCount() >= 2;
    } return true;
    // return true;
    public boolean shouldSelectCell(EventObject anEvent) {
    return (true);
    public void cancelCellEditing() {
    public boolean stopCellEditing() {
    fireEditingStopped();
    return (true);
    public Object getCellEditorValue() {
    return (ta.getText());
    public void addCellEditorListener(CellEditorListener l){
    try {
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run() {requestFocus();}
    } catch (Exception e) {};
    listenerList.add(CellEditorListener.class, l);
    public void removeCellEditorListener(CellEditorListener l) {
    listenerList.remove(CellEditorListener.class, l);
    protected void fireEditingStopped(){
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2)
    ((CellEditorListener)listeners[i+1]).editingStopped(event);
    protected void fireEditingCanceled() {
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2)
    ((CellEditorListener)listeners[i+1]).editingCanceled(event);
    } //end class

    Thanks again for the repley.
    I tried removing the celleditorlistener and using the setSurrenderFocusOnKeystroke, but it did not work. The textfield is editable;
    I did change:
    public void addCellEditorListener(CellEditorListener l){
    try {
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run() {ta.requestFocus();}
    } catch (Exception e) {};
    listenerList.add(CellEditorListener.class, l);
    }This allows the first textfield to request focus and this seems to work. But when I highlight a cell, then start typing, the first character I type puts me into the editor, but it is lost. Example:
    I type hello
    and get ello in the cell. Then when I press enter the input is excepted and the selection goes to the next cell, but I cannot move the Highlight cursor at all, seems locked. The only way I can continue to the next cell is to use the mouse.
    You said you had a cell editor working. Would you care to share as an example. This is killing me to get this to work properly.
    Thanks again
    Dave

  • Custom Cell Renderer issue in Custom JTable

    I have CustomeTable extends JTable which renders different UI Components like (JTextField/ ComboBox /JButton/JCheckBox) in *"single column*" so i have overridden *getCellRenderer* and *getCellEditor methods.*
    Now my Custom Table changes contextually by selecting different nodes in JTree similar to Windows Explorer
    *The problem is Some times When i Click Button & then i click other Node which displays other UIComponents old components (Button is painted) instead of new COmponent(JTextfield or ...)*
    *For each UI Renderer i have called its repaint() method still this issue is noticed not frequentlly but yes occasionally.*

    Following are some of my Custom Text / Combo Renderer / Password / Button to display different UI Components @ Column 2 as per my above Code
    private class MyDefaultRenderer implements TableCellRenderer {
            private JTextField l;
            private Border borderPrevious;
            public MyDefaultRenderer() {
                l = new JTextField();
                borderPrevious = l.getBorder();
            public Component getTableCellRendererComponent(JTable table,
                    Object value,
                    boolean isSelected,
                    boolean hasFocus,
                    int row,
                    int column) {
                PropertyInfoType propertyType = propertyInfoList.get(row).getType();
                if (ConfigCommonPropertyPanel.isInputEditable && !propertyInfoList.get(row).isReadOnly()) {
                String tempVal = "";
                if (value != null && value instanceof String) {
                    tempVal = value.toString();
                l.setText(tempVal);
                l.setOpaque(true);
                l.revalidate();
                l.repaint();
                return l;
            public Object getCellEditorValue() {
                return l.getText();
           private class ButtonRenderer implements TableCellRenderer {
            JPanel buttonPanel;
            JButton button;
            public ButtonRenderer() {
                buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
                button = new JButton(getAdminUIMsg(168));
                buttonPanel.setOpaque(true);
                buttonPanel.add(button);
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                button.setFont(LNFManager.getThemeForComponent(table).getBodyText());
                buttonPanel.setPreferredSize(new Dimension(getPreferredSize().width, getRowHeight()));
                buttonPanel.revalidate();
                buttonPanel.repaint();
                return buttonPanel;
        private class ButtonEditor extends JButton implements TableCellEditor, ActionListener {
            int rowIndex;
            int columnIndex;
            JTable table;
            JPanel panel;
            public ButtonEditor() {
                super("Validate Database");
                panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
                addActionListener(this);
            public Component getTableCellEditorComponent(JTable table, Object value,
                    boolean isSelected, int row, int column) {
                rowIndex = row;
                columnIndex = column;
                setOpaque(true);
                panel.setOpaque(true);
                panel.setPreferredSize(new Dimension(getPreferredSize().width, getRowHeight()));
                setFocusable(true);
                panel.repaint();
                panel.add(this);
                return panel;
            public Object getCellEditorValue() {
                return this.isSelected();
            public boolean isCellEditable(EventObject anEvent) {
                return true;
            public boolean shouldSelectCell(EventObject anEvent) {
                return true;
            public boolean stopCellEditing() {
                return true;
            public void cancelCellEditing() {
            public void addCellEditorListener(CellEditorListener l) {
            public void removeCellEditorListener(CellEditorListener l) {
            public void actionPerformed(ActionEvent e) {
                              try{
    // Some Business Logic To check my Database / LDAP Connections on Button Click
                                 }catch( Exception ex){
                                  } finally{
                                            stopCellEditing();
                                            transferFocus();
                   +Shouldnt i call repaint() on a specific Component for a Specific renderer ?+
    My Code works perfectly 99 % of the times ..
    But very rarely when i click My Button On my Custom Table say
    When i click NODE A - which displays different UI in Right Split Info
    Row 2 Column 2 - has Validate Button
    Then i Click NODe B - Which displayes Contextual UI Components
    Row 2 Column 2 should display TextBox (as expected)
    but due to some rendering issue its Displaying same Validate Button
    I have debugged and verified my logic to call renderer is perfect.
    My rest of rows /columns displays appropriate UI Components except the
    position of Button .
    I think after my Button Editor is Invoked & i perform some business logic Button renderer is not getting invoked ???

  • Custom JTable column (JCheckBox) not included in row selection.

    I am trying to use JCheckBox (for display only data) as one of my JTable columns. I have written custom cell renderer for the same. Every thing is working fine except that when I select a row, the new custom JCheckBox column is not included in selection. Here is the code that I am using.
        protected class CheckBoxColumnRenderer extends DefaultTableCellRenderer {
            JCheckBox ckb = new JCheckBox();
            public Component getTableCellRendererComponent(JTable table, Object value,
                        boolean isSelected, boolean hasFocus, int row, int column) {
                if (value instanceof Boolean) { // Boolean
                  ckb.setSelected(((Boolean) value));
                  ckb.setHorizontalAlignment(JLabel.CENTER);
                  ckb.setBackground(super.getBackground());
                  if (isSelected || hasFocus) {
                      ckb.setBackground(table.getSelectionBackground());
                return ckb;
        }How can I include the custom cell in the row selection.
    regards,
    nirvan.

    they have lots of dependencies and it is not always easy to strip out an SSCCE without a considerable effort.Exactly. And is the cause of the problem the dependencies or something else. The only way to know for sure is to strip out the code and simplify the problem, that way you truly understand what the problem is.
    The majority of time this can be done with minimal effort as in this case.
    Some times we are sure that the problem is with certain part of the code Is the problem the code or the way the code is invoked? How do we know the TableModel is created properly or that the column class is overwritten correctly when we can't see it?
    someone having a third look at it may actually find the enhancement required with ease.Exactly, but we need to see the big picture.
    So are you sure that I should post an SSCCE with every possible question where coding is involved ?In the majority of cases a SSCCE is easily created in 5-10 minutes, so if you want the fastest help then yes.
    Just twice this past week I was ready to ask a question on the forum and was preparing a SSCCE to post and sure enough both times the creation of the SSCCE caused me to look at the problem differently and I solved it. I would much rather solve a problem on my own then post a question and wait for hours (days) hoping someone else knows the answer.

  • Custom JTable cell editors and persistence

    I have a JTable with an underlying data model (an extension of AbstractTableModel) that uses custom cell editors in the last column. The cell editor in that column, for a given row, depends on the value selected in another column of the same row. The cell editors include text, date, list, and tree editors (the last one in a separate dialogue). The number of rows is changeable.
    I have need to persist the data for a populated table from time to time, for restoration later on. I've achieved that, such that the data model is recreated, the table appears correct, and the appropriate cell editors activated (by creating new instances of the editors' classes).
    However, my problem is that the (custom) cell editors do not reflect the data in the model when editing mode is begun the first time after restoration. Eg. the text editor is always empty, the list editor shows the first item, and no node is selected in the tree editor.
    If I've restored the model correctly, should the editors properly reflect the underlying data when they are set to editing mode?
    I suspected not, and thus tried to explicitly 'set' the correct values immediately after each editor is recreated ... but to no avail.
    Does anyone have any thoughts, or experience with something similar? I'm happy to supply code.

    You can use html tags within Swing, so I think you can do the following:
    * MyRenderer.java
    * Created on 26 April 2007, 10:27
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package newpackage;
    import java.awt.Component;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.SwingConstants;
    import javax.swing.table.TableCellRenderer;
    * @author CS781RJ
    public class MyRenderer extends JLabel implements TableCellRenderer
        public MyRenderer()
            setHorizontalTextPosition(SwingConstants.RIGHT);
            setIconTextGap(3);
            setOpaque(true);
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean cellHasFocus, int row, int column)
            if (isSelected)
                setBackground(table.getSelectionBackground());
                setForeground(table.getSelectionForeground());
            else
                setBackground(table.getBackground());
                setForeground(table.getForeground());
            if (value instanceof String)
                if ((value != null) && (value.toString().length() > 0))
                    System.out.println("Value: " + value.toString());
                    setFont(new java.awt.Font("Tahoma", 0, 11));
                    setText("<html>" + value.toString().replaceAll("\n", "<br>") + "</html>");
            return this;
    }In the class that has the JTable, use the code AFTER declaring the values, columns, etc:
    jTable1.getColumnModel().getColumn(0).setCellRenderer(new MyRenderer());
    jTable1.setValueAt("Riz\nJavaid", 0, 0);One thing I haven't done is to resize the cell heights, make sure this is done.
    Hope this helps
    Riz

  • Custom jtable editors

    Hi,
    I've written an application which needs to use multiple editors for the same table. Also I've modified the keyboard navigation to create a new row for certain keystrokes like TAB and ENTER. For this I've attached a KeyListener to the JTable.
    My problem is that though the editors work fine, but the keyevent dont arrive at my listener when I double click a cell to edit it. But if I were to select the cell and start typing, the keyeventListener works just fine.
    Kindly do lemme know what I should be doing.
    Thanks in advance.
    KR.

    First some notes:
    1) don't use KeyListeners
    2) don't use KeyListeners
    3) don't use KeyListeners
    got it? :-)
    Your problem is that keyListeners only work on focused components - in the general case there's no way to predict which component will have the focus when the table is editing. Depends on both the JTable and the editor in use.
    The high level and very powerful approach that replaces the veeeery low level keyListeners is the InputMap/ActionMap mechanism (if you are not familiar with it, read the article about keybindings that's somewhere at this site) - it's used internally by Swing as well and you can easily plug-into the internal default handling.
    There is absolutely no reason for any tricks, the straightforward way to go is:
    a) get the table's default action that's bound to the keyStroke you want to enhance (JTable has all registered keyStrokes in the inputMap of type WHEN_ANCESTOR_OF...)
    Object actionKey = table.getInputMap(type).get(myKeyStroke);
    Action action = table.getActionMap(actionKey);b) define a custom action that augments the default - depending on context, let it do its own work before/after calling the default
    class CustomAction extends.... {
      Action delegate;
      void actionPerformed(...) {
        JTable table = (JTable) e.getSource();
        // check conditions
        // do work
        delegate.actionPerformed(e);
        // check conditions
        // do work;
    }c) replace the custom action for the default action in the table's actionMap
    table.getActionMap().put(actionKey, new CustomAction(action);Greetings
    Jeanette

  • Customizing JTable

    I'm currently working on some customizing of a JTable, and I wonder if anybody can help me with the following that I would like to do. I thought it would be common enough that it should be pretty easy, but I didn't see any good methods
    What I need to do is to use the first row of the table to hold editable combo boxes for filtering.
    Now, getting the combo boxes to work, and doing the filtering is easy enough.
    What I'm looking at now is finding a way to make sure that as the client scrolls down in the scroll pane that the first row of the table, which contains the combo boxes, remains visible just below the headers.
    I can't actually use them as the headers (I don't think, anyway) because I need the headers to be there too, and because headers aren't editable.
    Does anybody know of a (preferable not convoluted) way to do this?
    - Adam

    Does anybody know of a (preferable not convoluted) way to do this?Yes, the combo boxes should not be part of the table. You should be creating a separate panel displaying the combo boxes above the table header. This is the way most filtering applications work.

  • Customized JTable cell

    Hello there:
    I want to customize the JTable cell which combines a textfield and a label. other than that, it will behave like any other Jtable component. I wrote a sample class as below, it looks ok but acts weird. Most likely my customized renderer is wrong, anyone pls revise it? thanks a lot!
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.BorderFactory;
    import javax.swing.BoxLayout;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.TableCellRenderer;
    public class CustomizedTable extends JFrame {
    * @param args
    CustomizedTable(){
    String[] col = new String[]{
    "col1", "col2","col3"
    Object[][] data = {
    {"1","2","3"},
    {"1","2","3"},
    {"1","2","3"},
    {"1","2","3"}
    JTable table = new JTable(data,col);
    DataColumn dc = new DataColumn();
    table.setDefaultRenderer(table.getColumnClass(0),dc);
    table.setDefaultEditor(table.getColumnClass(0),dc);
    dc = new DataColumn();
    table.setDefaultRenderer(table.getColumnClass(1),dc);
    table.setDefaultEditor(table.getColumnClass(1),dc);
    dc = new DataColumn();
    table.setDefaultRenderer(table.getColumnClass(2),dc);
    table.setDefaultEditor(table.getColumnClass(2),dc);
    JScrollPane scroll = new JScrollPane(table);
    scroll.setPreferredSize (new Dimension(300,200));
    getContentPane().add(scroll, BorderLayout.CENTER);
    pack();
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    new CustomizedTable();
    class DataColumn extends DefaultCellEditor implements TableCellRenderer {
    JFormattedTextField ftf;
    private JPanel panel = null;
    private JLabel l = new JLabel(" %");
    public DataColumn() {
    super(new JFormattedTextField());
    ftf = (JFormattedTextField) getComponent();
    ftf.setHorizontalAlignment(JTextField.RIGHT);
    ftf.setFocusLostBehavior(JFormattedTextField.PERSIST);
    ftf.setBorder(BorderFactory.createEmptyBorder());
    panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
    panel.add(ftf);
    panel.add(l);
    public Component getTableCellRendererComponent(JTable table, Object o,
    boolean isSelected, boolean hasFocus, int row, int column) {
    ftf = (JFormattedTextField) getComponent();
    ftf.setHorizontalAlignment (JTextField.RIGHT);
    ftf.setFocusLostBehavior(JFormattedTextField.PERSIST);
    ftf.setBorder(BorderFactory.createEmptyBorder());
    //panel = new JPanel();
    //panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
    //panel.add(ftf);
    //panel.add(l);
    return panel;
    public Component getTableCellEditorComponent(JTable table, Object value,
    boolean isSelected, int row, int column) {
    JFormattedTextField ftf = (JFormattedTextField) super
    .getTableCellEditorComponent(table, value, isSelected, row,
    column);
    ftf.setValue(value);
    // ftf.setBorder(BorderFactory.createEmptyBorder());
    // ftf.setHorizontalAlignment(JTextField.RIGHT);
    // panel = new JPanel();
    // panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
    // panel.add(ftf);
    // panel.add(l);
    return panel;
    }

    After 40 postings you should know how to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags.

  • Selection of Custom JTable cell renderer inconsistenent between LAFs

    Sorry if that seems cryptic, but I don't know if I've run into a bug or not. I've recently switched from windows to linux and have noticed a problem with one of my programs. I have a "multiline" renderer that I made for my JTable. The renderer isn't terribly elegant, but when I'd select the row of the table, I made the multi-line renderer change its colors in response to the selection.
    This color selection switching works fine under the Metal LAF and the Windows LAF. However, this no longer works in the default look and feel is for linux (GTK+???). My multiline renderer in the JTable won't change its foreground/background in response to selection, but will if I use the Metal LAF under linux.
    Any idea what I'm doing wrong? Is this a bug? (I'm fairly certain I'm doing something silly, I just can't see it for the life of me).
    Here's the code I use to update the selection:
    class MultilineRenderer extends JTextArea
            implements TableCellRenderer {
        public MultilineRenderer(){
            super();
            setWrapStyleWord(false);
            setLineWrap(true);
            setFont(Const.TABLE_FONT);
            setOpaque(true);
        public Component getTableCellRendererComponent(
                JTable table, Object text,
                boolean isSelected, boolean hasFocus,
                int row, int column) {
            String data = (String)text;
            setText(data);
            if (isSelected){
                setForeground(table.getSelectionForeground());;
                setBackground(table.getSelectionBackground());
            } else {
                setForeground(table.getForeground());
                setBackground(table.getBackground());
            return this;
    }

    Some look and feels will ignore calls to setBackground and setForeground, and will instead decide their own colour.
    To quote the API documentation:
    "The background color affects each component differently and the parts of the component that are affected by the background color may differ between operating systems."
    I would imagine that this is your problem. Annoying, I know!

  • Listener for custom JTable

    I need to know when a user clicks in a certain column in a JTable. This column displays checkboxes. How do i implement a listener for this and where do i put it? I've tried implementing actionlistener with an editor class, but the event never fires.

    In the future, Swing related questions should be posted in the Swing forum.
    You need to add a TableModelListener to the TableModel. It will notify you when the value of a cell is changed.

  • Customized JTable can't find keyPressed() event

    I'm writing a new table component that extends from JTable. One of the behaviors to be implemented is to prevent the up and down arrow keys from navigating to an adjacent cell. Problem is, when a cell is selected (and being edited), something is handling the keyPressed(KeyEvent e) method before the table. I tried adding a KeyListener() to the component, but that doesn't help. It never gets there either. I suspect it's down inside the editor component - perhaps at the document level? The table does get the keyReleased(KeyEvent e) method okay.
    The selected cell does change, but it does not start editing. Subsequent key events (including keyPressed) are captured at the JTable level and consumed appropriately.
    What I need is to capture the initial keyPressed(KeyEvent e) and consume it...but where is it getting handled?
    Any help? Thanks...

    When the editor is invoked it has the focus and recieves the key events.
    Good Luck with this... I developed my own JTable extension to solve some of the common problems I have with it. It is a mess.
    Beware; there are several bugs still in the JTable. Like you can't operate some JComboBox editors with the keyboard. Also, when in an text editor and focus moves off the JTable the contents are lost.
    I also was interested in changing the default key navigation. I recall that this is not to hard but did not do it.

  • Custom JTable + Collections

    Using a treemap with a Jtable... Have the following code:
    public Object getValueAt(int row, int col)
        Object value = null;
        do
         if(data.containsKey(row))
              Account account = (Account) data.get(row);
              switch(col)
                case 0:
                 value = new Integer(account.getAccNum());
                 break;
                case 1:
                  value = account.getOwner();
               break;
                case 2:
                   value = new Double(account.getBalance());
                   break;
                case 3:
                   if(account instanceof SavAccount)
                     value = "Savings";
                   else
                     value = "Cheque";
                   break;
                 default:
                    value = null;
            else
           row++;
        } while (value.equals(null));
      return value;
    }data is the TreeMap of accounts. For some reason it gives me a NullPointerException when trying to paint the 3rd row of the table . It blames the exception on the while line.

    Its not very efficient to loop throught the entire TreeMap attempting to find the correct Account to display. Just use an ArrayList instead. The code would be something like:
    public Object getValueAt(int row, int col)
         Security security = (Security)list.get( row );
         switch (col)
              case 0: return security.getName();
              case 1: return security.getSymbol();
              case 2: return security.getExchange();
              case 3: return security.getType();
              case 4: return security.getAssetClass();
              case 5: return security.getGoal();
         return null;
    }

  • TableSorter with Custom JTable

    I need some straight thinking here.
    I would like to add the TableSorter to a customised JTable (MyJTable).
    MyJTable extends JTable and uses a customsised Model (MyJTableModel) which extends DefaultTableModel.
    Both MyJTable and MyJTableModel are established components which work fine together and have been in use for a long period.
    The TableSorter class from the tutorial expects the Model to be a TableModel and appears to the JTable as a TableModel.
    So
              // Introducing the Sorter
              // TableSorter normally takes a DefaultTableModel
              // The mainModel is a MyJTableModel which Extends DefaultTableModel
              // So This is OK
              TableSorter mainSortModel = new TableSorter(mainModel);
              // mainTable is a MyJTable which normally takes a MyJTableModel
              // but the TableSorter is based on AbstractTableModel
              // So Here I Have a Mis-Match
              mainTable = new MyJTable(mainSortModel);
              // I Tried to Adapt TableSorter to extend MyJTableModel (which extends DefaultTableModel)
              // but this led to other errors in TableSorter
              mainSortModel.setTableHeader(mainTable.getTableHeader());How do I introduce the TableSorter ?

    I am somewhat new, but I was able to use the
    TableSorter without creating my own mouse-event... I
    believed the TableSorter does it automatically for
    you...You right. The TableSorter does normally. Unfortuantely in my case this isn't working because I have a customised table and model. Actually I'm unsure why it doesn't and I'm trying to diagnose where the problem lies. These reason I have focussed on the mose behaviour is because I can see it isn't working. Maybe that is the only problem but I was trying to figure out how to localise the problem more. Hence my last post.
    Thanks

Maybe you are looking for