Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 05-24-2009, 11:54 PM
Member
 
Join Date: Mar 2009
Posts: 2
Rep Power: 0
ting.at.net@hotmail.com is on a distinguished road
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);


}
Bookmark Post in Technorati
Reply With Quote
  #2 (permalink)  
Old 05-25-2009, 04:37 AM
Fubarable's Avatar
Moderator
 
Join Date: Jun 2008
Posts: 5,968
Rep Power: 7
Fubarable is on a distinguished road
Default
Just a guess -- are the cells with the buttons editable per your table model?
Bookmark Post in Technorati
Reply With Quote
  #3 (permalink)  
Old 05-25-2009, 07:01 AM
Member
 
Join Date: Mar 2009
Posts: 2
Rep Power: 0
ting.at.net@hotmail.com is on a distinguished road
Default
public boolean isCellEditable() {
return true;
}

is defined in my TableModel class. So yes, or I think it is.
Bookmark Post in Technorati
Reply With Quote
  #4 (permalink)  
Old 05-25-2009, 07:17 AM
Fubarable's Avatar
Moderator
 
Join Date: Jun 2008
Posts: 5,968
Rep Power: 7
Fubarable is on a distinguished road
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:

Code:
[code]
  // your code goes here
  // notice how the top and bottom tags are different
[/code]
Best of luck!
Bookmark Post in Technorati
Reply With Quote
  #5 (permalink)  
Old 05-25-2009, 08:04 AM
Fubarable's Avatar
Moderator
 
Join Date: Jun 2008
Posts: 5,968
Rep Power: 7
Fubarable is on a distinguished road
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.
Bookmark Post in Technorati
Reply With Quote
  #6 (permalink)  
Old 05-26-2009, 12:42 AM
hardwired's Avatar
Senior Member
 
Join Date: Jul 2007
Posts: 1,561
Rep Power: 4
hardwired is on a distinguished road
Default
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;
    }
}
Bookmark Post in Technorati
Reply With Quote
  #7 (permalink)  
Old 05-26-2009, 04:37 AM
Steve11235's Avatar
Senior Member
 
Join Date: Dec 2008
Posts: 921
Rep Power: 2
Steve11235 is on a distinguished road
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...
Bookmark Post in Technorati
Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Unable to use fireTableRow after adding sorter on JTable swat_katz AWT / Swing 2 04-10-2009 12:59 AM
adding Image to JButton mayhewj7 New To Java 3 03-31-2009 04:39 AM
Problem on adding JButton on JPanel NEED HELP boisk AWT / Swing 15 03-15-2009 03:27 PM
JButton to display JTable Nemesis777 New To Java 0 12-08-2008 01:16 PM
Adding information to a JTable in a JTabbedPane bigpappatrader AWT / Swing 0 12-05-2007 08:09 AM


All times are GMT +2. The time now is 12:58 PM.



VBulletin, Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO ©2009, Crawlability, Inc.
Copyright ©2006 - 2007, www.java-forums.org