Results 1 to 7 of 7
  1. #1
    Join Date
    Mar 2009
    Posts
    2
    Rep Power
    0

    Default Adding JButton to a JTable

    I am having trouble adding a JButton to a JTable. I can render it using CellRenderer, and get the look of JButton. But when I use CellEditor to add a JButton to the JTable, nothing seems clickable.

    the TableCellEditor implementation class is:

    package codesample;

    import java.awt.Component;
    import java.util.EventObject;
    import javax.swing.JTable;
    import javax.swing.event.CellEditorListener;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableModel;
    import javax.swing.JButton;
    import javax.swing.JSpinner;
    import javax.swing.JLabel;

    public class InputEditor implements TableCellEditor {

    protected TableModel tableModel;

    public InputEditor(TableModel tableModel) {
    this.tableModel = tableModel;
    }

    public Component getTableCellEditorComponent(JTable table, Object value,
    boolean isSelected, int row, int column) {
    if (column == CodeSample.BUY)
    return new JButton("Buy");
    if (column == CodeSample.SELL)
    return new JButton("Sell");
    if (column == CodeSample.QUANTITY)
    return new JSpinner();
    return new JLabel();
    }

    public Object getCellEditorValue() {
    throw new UnsupportedOperationException("Not supported yet.");
    }

    public boolean isCellEditable(EventObject anEvent) {
    return true;
    }

    public boolean shouldSelectCell(EventObject anEvent) {
    return true;
    }

    public boolean stopCellEditing() {
    return false;
    }

    public void removeCellEditorListener(CellEditorListener l) {
    throw new UnsupportedOperationException("Not supported yet.");
    }

    public void addCellEditorListener(CellEditorListener l) {
    throw new UnsupportedOperationException("Not supported yet.");
    }

    public void cancelCellEditing() {
    throw new UnsupportedOperationException("Not supported yet.");
    }

    }

    and I thought it returns a JButton or JSpinner when the BUY, SELL, QUANTITY columns are selected. I am sure these values got called correctly because my cell renderer works fine. I can see the renderered JButton and JSpinner, just not able to push it down. I believe my JButton/JSpinner didn't actually get insert into JTable, and all I am seeing so far is rendered JButton/JSpinner.

    In my main function, I added the CellEditor to the JTable:

    public static void main(String[] args) {

    // reading from file, internet, or database and feed it into a DataModel
    DataModel data = initData();
    // initialize a JTable with the DataModel
    JTable table = initTable(data);
    // get TableColumnModel from the table
    TableColumnModel tcm = table.getColumnModel();
    // initialize the CellRenderers for visual display
    InputRenderer IRenderer = new InputRenderer();
    CurrencyRenderer CRenderer = new CurrencyRenderer();
    // initialize the CellEditors for interactive feedback
    InputEditor IEditor = new InputEditor(table.getModel());
    // pick the column, set its renderer and editor
    TableColumn tc = tcm.getColumn(BUY);
    tc.setCellRenderer(IRenderer);
    tc.setCellEditor(IEditor); // here
    tc = tcm.getColumn(SELL);
    tc.setCellRenderer(IRenderer);

    tc = tcm.getColumn(QUANTITY);
    tc.setCellRenderer(IRenderer);

    tc = tcm.getColumn(PRICE);
    tc.setCellRenderer(CRenderer);

    // add the JTable to a JScrollPane
    JScrollPane scrollPane = new JScrollPane(table);
    // add JFrame
    JFrame frame = new JFrame("CodeSample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);
    // add scroll pane to the frame
    frame.add(scrollPane, BorderLayout.CENTER);
    // add dataChangeListener to data to listen to the event changes

    frame.setSize(450, 150);
    frame.setVisible(true);


    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Just a guess -- are the cells with the buttons editable per your table model?

  3. #3
    Join Date
    Mar 2009
    Posts
    2
    Rep Power
    0

    Default

    public boolean isCellEditable() {
    return true;
    }

    is defined in my TableModel class. So yes, or I think it is.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    According to the Sun Swing JTable tutorial, you may be better off having your InputEditor extend the AbstractCellEditor as it saves you "the trouble of implementing the event firing code necessary for cell editors".

    If this doesn't help, then your best bet here may be to show us compilable code. We don't want to see your whole program, but rather you should condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem, in other words, an SSCCE (Short, Self Contained, Correct (Compilable), Example). For more info on SSCCEs please look here:

    Short, Self Contained, Correct (Compilable), Example

    Again, if the code is compilable and runnable more people will be able to help you.

    Also, when posting code here, please use code tags so that your code will retain its formatting and thus will be readable -- after all, your goal is to get as many people to read your post and understand your code as possible, right?

    To do this, highlight your pasted code (please be sure that it is already formatted when you paste it into the forum; the code tags don't magically format unformatted code) and then press the code button, and your code will have tags.

    Another way to do this is to manually place the tags into your code by placing the tag [code] above your pasted code and the tag [/code] below your pasted code like so:

    Java Code:
    [code]
      // your code goes here
      // notice how the top and bottom tags are different
    [/code]
    Best of luck!

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Sorry, but we must discuss one other thing. Regarding this post on JavaRanch: Adding a JButton (Interactive) to a JTable (Swing / AWT / SWT / JFace forum at JavaRanch)

    Please read what JavaRanch has to say about cross-posting: BeForthrightWhenCrossPostingToOtherSites

    These same considerations apply here. Thanks for your attention and future consideration in this matter.

  6. #6
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.text.NumberFormat;
    import java.util.EventObject;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    
    public class EditorTest {
        private JScrollPane getTableComponent() {
            String[] colNames = {
                "Stock", "Price", "Shares", "Quantity", "Action", "Action", "Holder"
            };
            final Object[][] data = {
                { "MSFT",   Double.valueOf(12.21), Integer.valueOf(10),
                  Integer.valueOf(0), "Buy", "Sell", "Bill" },
                { "IBM",    Double.valueOf(13.21), Integer.valueOf(12),
                  Integer.valueOf(0), "Buy", "Sell", "Tim"  },
                { "ORACLE", Double.valueOf(21.22), Integer.valueOf(11),
                  Integer.valueOf(0), "Buy", "Sell", "Tom" }
            };
            DefaultTableModel model = new DefaultTableModel(data, colNames) {
                public Class getColumnClass(int col) {
                    return data[0][col].getClass();
                }
            };
            JTable table = new JTable(model);
            TableColumnModel colModel = table.getColumnModel();
            colModel.getColumn(1).setCellRenderer(new DoubleRenderer());
            colModel.getColumn(3).setCellRenderer(new SpinnerRenderer());
            colModel.getColumn(4).setCellRenderer(new ButtonRenderer());
            colModel.getColumn(5).setCellRenderer(new ButtonRenderer());
            colModel.getColumn(3).setCellEditor(new SpinnerEditor());
            colModel.getColumn(4).setCellEditor(new ButtonEditor(table));
            colModel.getColumn(5).setCellEditor(new ButtonEditor(table));
            table.setCellSelectionEnabled(true);
            Dimension d = table.getPreferredSize();
            table.setPreferredScrollableViewportSize(d);
            return new JScrollPane(table);
        }
    
        public static void main(String[] args) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(new EditorTest().getTableComponent());
            f.pack();
            f.setLocation(100,100);
            f.setVisible(true);
        }
    }
    
    class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {
        JTable table;
        SpinnerNumberModel model = new SpinnerNumberModel(0, 0, null, 1);
        JSpinner spinner = new JSpinner(model);
        int clickCountToStart = 1;
    
        public Component getTableCellEditorComponent(JTable table,
                                                     Object value,
                                                     boolean isSelected,
                                                     int row, int column) {
            spinner.setValue(((Integer)value).intValue());
            return spinner;
        }
    
        public Object getCellEditorValue() {
            return (Integer)spinner.getValue();
        }
    
        public boolean isCellEditable(EventObject anEvent) {
            if(anEvent instanceof MouseEvent) { 
                return ((MouseEvent)anEvent).getClickCount() >= clickCountToStart;
            }
            return true;
        }
    
        public boolean shouldSelectCell(EventObject anEvent) {
            return true;
        }
    
        public boolean stopCellEditing() {
            return super.stopCellEditing();
        }
    
        public void cancelCellEditing() {
            super.cancelCellEditing();
        }
    }    
    
    class ButtonEditor extends AbstractCellEditor implements TableCellEditor,
                                                             ActionListener {
        JTable table;
        JButton button = new JButton();
        NumberFormat nf = NumberFormat.getCurrencyInstance();
        int clickCountToStart = 1;
    
        public ButtonEditor(JTable table) {
            this.table = table;
            button.addActionListener(this);
        }
    
        public void actionPerformed(ActionEvent e) {
            StringBuilder sb = new StringBuilder();
            int row = table.getEditingRow();
            int col = table.getEditingColumn();
            //System.out.printf("row = %d  col = %d%n", row, col);
            sb.append((String)table.getValueAt(row, 6));
            sb.append(" has ");
            sb.append(((col == 4) ? "bought " : "sold "));
            sb.append(((Integer)table.getValueAt(row, 3)).toString());
            sb.append(" shares of " + (String)table.getValueAt(row, 0));
            sb.append(" at " +
                nf.format(((Double)table.getValueAt(row, 1)).doubleValue()));
            stopCellEditing();
            System.out.println(sb.toString());
        }
    
        public Component getTableCellEditorComponent(JTable table,
                                                     Object value,
                                                     boolean isSelected,
                                                     int row, int column) {
            button.setText(value.toString());
            return button;
        }
    
        public Object getCellEditorValue() {
            return button.getText();
        }
    
        public boolean isCellEditable(EventObject anEvent) {
            if(anEvent instanceof MouseEvent) { 
                return ((MouseEvent)anEvent).getClickCount() >= clickCountToStart;
            }
            return true;
        }
    
        public boolean shouldSelectCell(EventObject anEvent) {
            return true;
        }
    
        public boolean stopCellEditing() {
            return super.stopCellEditing();
        }
    
        public void cancelCellEditing() {
            super.cancelCellEditing();
        }
    }
    
    class SpinnerRenderer implements TableCellRenderer {
        SpinnerNumberModel model = new SpinnerNumberModel(0, 0, null, 1);
        JSpinner spinner = new JSpinner(model);
    
        public Component getTableCellRendererComponent(JTable table,
                                                       Object value,
                                                       boolean isSelected,
                                                       boolean hasFocus,
                                                       int row, int column) {
            spinner.setValue(((Integer)value).intValue());
            return spinner;
        }
    }
    
    class ButtonRenderer implements TableCellRenderer {
        JButton button = new JButton();
    
        public Component getTableCellRendererComponent(JTable table,
                                                       Object value,
                                                       boolean isSelected,
                                                       boolean hasFocus,
                                                       int row, int column) {
            button.setText(value.toString());
            return button;
        }
    }
    
    class DoubleRenderer extends DefaultTableCellRenderer {
        NumberFormat nf = NumberFormat.getCurrencyInstance();
    
        public DoubleRenderer() {
            setHorizontalAlignment(RIGHT);
        }
    
        public Component getTableCellRendererComponent(JTable table,
                                                       Object value,
                                                       boolean isSelected,
                                                       boolean hasFocus,
                                                       int row, int column) {
            super.getTableCellRendererComponent(table, value, isSelected,
                                                hasFocus, row, column);
            setText(nf.format(((Double)value).doubleValue()));
            return this;
        }
    }

  7. #7
    Steve11235's Avatar
    Steve11235 is offline Senior Member
    Join Date
    Dec 2008
    Posts
    1,046
    Rep Power
    7

    Default

    Your buttons won't do much without action listeners. I think you approach was OK, you just don't do anything when the buttons are clicked...

Similar Threads

  1. Replies: 2
    Last Post: 04-10-2009, 12:59 AM
  2. adding Image to JButton
    By mayhewj7 in forum New To Java
    Replies: 3
    Last Post: 03-31-2009, 04:39 AM
  3. Problem on adding JButton on JPanel NEED HELP
    By boisk in forum AWT / Swing
    Replies: 15
    Last Post: 03-15-2009, 03:27 PM
  4. JButton to display JTable
    By Nemesis777 in forum New To Java
    Replies: 0
    Last Post: 12-08-2008, 01:16 PM
  5. Adding information to a JTable in a JTabbedPane
    By bigpappatrader in forum AWT / Swing
    Replies: 0
    Last Post: 12-05-2007, 08:09 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •