OnMouseDown buttons within JTable Cells?

I have written an app that uses a custom renderer to enable me to put an image in a cell and attach a custom editor to that image so that when it is clicked it pops up a JPanel. Trouble is, once the user clicks the button and the JPanel appears the image that was within the cell disappears and the cell is empty. How do I switch the image once clicked and display it in the clicked cell.
Thanks

When you click on the cell the editor is invoked and will display the data based on the editor, not the renderer.
So, I'm guessing that in addition to displaying the popup, your editor must be responsible for displaying the original image.

Similar Messages

  • Drag the component from one cell to another cell within JTable

    Hi All,
    I have one requirement to drag the component from JList to JTable cell. I am able to do it but once if i drag the component from list to table cell, table accepting the drop after this i am unable to move the same component from one cell to another cell within the table.
    Any advice.
    I have used the following logic for JTable and JList is drag enabled.
    DefaultTableModel tableModel=new DefaultTableModel(
                new Object [][] {
                    {null, null, null, null,null,null,null},
                    {null, null, null, null,null,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","Title 5","Title 6","Title 7"
            JTable table = new javax.swing.JTable(){
                public boolean isCellEditable(int row, int column)
                    return false;
            table.setModel(tableModel);
            table.setDragEnabled(true);
            table.setDropMode(DropMode.INSERT);
            table.setTransferHandler(new TransferHandler(){
                public boolean canImport(TransferHandler.TransferSupport info){
                    if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)){
                        return false;
                    return true;
                public boolean importData(TransferSupport support) {
                    if (!support.isDrop()) {
                        return false;
                    if (!canImport(support)) {
                        return false;
                    JTable table=(JTable)support.getComponent();
                    DefaultTableModel tableModel=(DefaultTableModel)table.getModel();
                    // fetch the drop location
                    JTable.DropLocation dl = (JTable.DropLocation)support.getDropLocation();
                    int row = dl.getRow();
                    int col=dl.getColumn();
                    // fetch the data and bail if this fails
                    String data;
                    try {
                        data = (String)support.getTransferable().getTransferData(DataFlavor.stringFlavor);
                    } catch (UnsupportedFlavorException e) {
                        return false;
                    } catch (IOException e) {
                        return false;
                    calendarTableModel.setValueAt(data, row, col);
                    return true;
            });Thanks & Regards,
    Maadhav.
    Edited by: maadhav on Jun 23, 2009 12:29 AM

    Hi All,
    I fixed this issue with some additional logic which allow me to drag and drop the string component from one cell to another cell within in the JTable.
    I am attaching the new logic here, if any one needs use it.
    DefaultTableModel tableModel=new DefaultTableModel(
                new Object [][] {
                    {null, null, null, null,null,null,null},
                    {null, null, null, null,null,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","Title 5","Title 6","Title 7"
            JTable table = new javax.swing.JTable(){
                public boolean isCellEditable(int row, int column)
                    return false;
            table.setModel(tableModel);
            table.setDragEnabled(true);
            table.setDropMode(DropMode.USE_SELECTION);
            table.setTransferHandler(new TransferHandler(){
              public int getSourceActions(JComponent c) {
                    return DnDConstants.ACTION_COPY_OR_MOVE;
                public Transferable createTransferable(JComponent comp)
                    JTable table=(JTable)comp;
                    int row=table.getSelectedRow();
                    int col=table.getSelectedColumn();
                    String value = (String)table.getModel().getValueAt(row,col);
                    StringSelection transferable = new StringSelection(value);
                    table.getModel().setValueAt(null,row,col);
                    return transferable;
                public boolean canImport(TransferHandler.TransferSupport info){
                    if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)){
                        return false;
                    return true;
                public boolean importData(TransferSupport support) {
                    if (!support.isDrop()) {
                        return false;
                    if (!canImport(support)) {
                        return false;
                    JTable table=(JTable)support.getComponent();
                    DefaultTableModel tableModel=(DefaultTableModel)table.getModel();
                   JTable.DropLocation dl = (JTable.DropLocation)support.getDropLocation();
                    int row = dl.getRow();
                    int col=dl.getColumn();
                    String data;
                    try {
                        data = (String)support.getTransferable().getTransferData(DataFlavor.stringFlavor);
                    } catch (UnsupportedFlavorException e) {
                        return false;
                    } catch (IOException e) {
                        return false;
                    tableModel.setValueAt(data, row, col);
                    return true;
            });Thanks & Regards,
    Maadhav..
    Edited by: maadhav on Jun 23, 2009 5:26 AM
    Edited by: maadhav on Jun 23, 2009 5:28 AM

  • JTextField/JTable-cell Button

    Is there any known efficient methods of creating the JTextField or JTable-cell Button as like in Forte's Component Inspector window where you click on the property value field and the value is displayed just left of a small button labelled "..." ie: [some text field with value][...] also referred to as the "ellipsis" buttons, or will most answers to this question simply describe the layout of a JField-JButton combination? The action from clicking on the [...] button aligned right of the JTextField simply invokes or displays a larger input interface in which upon completion of the entered data, returns the input to the related JTextField.
    Thanks to anybody for any help with this, and perhaps in return, I may be able to answer any non-gui java questions, or some not so unfamilliar GUI questions.

    Hello StanislavL and Lutianxiong,
    I remember asking this question some time ago, and the time has come again for me to seek this functionality. I have finally achieved the functionality and thought I would post the answer for anybody else. I had not realized that I had recieved a solution/reply to my original question as I come here to post the answer, and in fact, my solution does appear to be very similiar to your reply, StanislavL. As for you, Lutianxiong and other seekers of this info, here is my solution with a JFileChooser style input for the 3rd column which only shows gif,jpg and png files:
    <code>
    ------------- TableCellFileInput.java -------------------
    public class TableCellFileInput extends javax.swing.JPanel {
    private String extensions[];
    public TableCellFileInput(String fileExtensions[]) {
    extensions = fileExtensions;
    self = this;
    initComponents();
    private void initComponents() {
    valueField = new javax.swing.JTextField();
    fileButton = new javax.swing.JButton();
    setLayout(new java.awt.BorderLayout());
    valueField.setText("jTextField1");
    add(valueField, java.awt.BorderLayout.CENTER);
    fileButton.setText("...");
    fileButton.setMargin(new java.awt.Insets(0, 2, 0, 2));
    fileButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    fileButtonActionPerformed(evt);
    add(fileButton, java.awt.BorderLayout.EAST);
    private void fileButtonActionPerformed(java.awt.event.ActionEvent evt) {
    String filePath = valueField.getText();
    if(filePath != null && filePath.length() > 0) {
    filePath = new java.io.File(filePath).getParent();
    javax.swing.JFileChooser chooser
    = new javax.swing.JFileChooser(filePath);
    chooser.setFileFilter(new ImageFilter());
    int returnVal = chooser.showOpenDialog(this);
    if(returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
    valueField.setText(chooser.getSelectedFile().getAbsolutePath());
    class ImageFilter extends javax.swing.filechooser.FileFilter {
    public boolean accept(java.io.File f) {
    if(f.isDirectory()) return true;
    String fName = f.getName();
    if(extensions != null) {
    for(int i=0;i<extensions.length;i++) {
    if(fName.endsWith(extensions[ i ])) return true;
    return false;
    public String getDescription() {
    return DESCRIPTION;
    class CustomCellEditor extends javax.swing.AbstractCellEditor
    implements javax.swing.table.TableCellEditor {
    public Object getCellEditorValue() {
    return valueField.getText();
    public java.awt.Component getTableCellEditorComponent(javax.swing.JTable table, Object value, boolean isSelected, int row, int column) {
    System.out.println("fileEditor");
    if(value == null) valueField.setText("");
    else valueField.setText(value.toString());
    return self;
    public void setColumn(javax.swing.table.TableColumn column) {
    column.setCellEditor(new CustomCellEditor());
    private javax.swing.JButton fileButton;
    private javax.swing.JTextField valueField;
    private static final String DESCRIPTION = "Image File Filter";
    private java.awt.Component self;
    ------------- TestTable .java -------------------
    public class TestTable extends javax.swing.JFrame {
    public TestTable() {
    editorField = new javax.swing.JTextField();
    String fileExts[] = {"gif","jpg","png"};
    fileEditorField = new TableCellFileInput(fileExts);
    initComponents();
    javax.swing.table.TableColumn column
    = jTable1.getColumn("Title 3");
    fileEditorField.setColumn(column);
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    jTable1.setModel(new javax.swing.table.DefaultTableModel(
    new Object [][] {
    {null, null, null, "cats"},
    {null, null, null, "dogs"},
    {null, null, null, "mice"},
    {null, null, null, "birds"}
    new String [] {
    "Title 1", "Title 2", "Title 3", "Title 4"
    Class[] types = new Class [] {
    java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.String.class
    public Class getColumnClass(int columnIndex) {
    return types [columnIndex];
    jScrollPane1.setViewportView(jTable1);
    getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
    java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    setBounds((screenSize.width-400)/2, (screenSize.height-300)/2, 400, 300);
    private void exitForm(java.awt.event.WindowEvent evt) {
    System.exit(0);
    public static void main(String args[]) {
    new TestTable().show();
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField editorField;
    private TableCellFileInput fileEditorField;
    </code>

  • Edit a JTable cell, click save button, value isn't stored in JTable

    I'm editing a JTable cell, just using default editor provided by JTable
    I click a save button elsewhere in my GUI
    The value typed into the cell so far isn't stored in the TableModel yet and so doesn't get saved.
    How can I make sure the value gets stored in the JTable in the above scenario when the JButton is pressed but before saving.
    Preferably I'd like the code with the JButton not to have to know about the JTable at all.
    Cheers,
    D

    I the forums 100s of times.Many thanks. If they had a decent search on this forum I might have found it as I did try.
    Come to think of it - Sun have completely fcukd up this forum.

  • Rendering a JTable within a JTable Cell

    How can one render a JTable within another JTable cell?

    You could return JTable in your TableCellRenderer.
    Denis Krukovsky
    http://sourceforge.net/projects/dotuseful/

  • JButton "sticking" in a JTable Cell

    So I've modified the renderer and what not and slapped a button into a JTable Cell. The assignment requires it to turn red/green altrenativly when pressed. It works perfectly aside from the fact that the buttons appear to not "bounce back" when they switch colors. (i.e. They appear depressed when red and pressed when green). The code is below. any ideas?
    import java.awt.Color;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.JButton;
    public class ButtonTableModel extends AbstractTableModel {
         private static final long serialVersionUID = 1;
         private Object[][] rows = new Object[2][1];
         private String[] columns = new String[1];
         public ButtonTableModel() {
              for(int k = 0; k < rows.length; k++) {
                   JButton button3 = new JButton("222");
                   button3.setSize(200, 200);
                   button3.setBackground(Color.red);
                   button3.addMouseListener(new ColorChanger(button3));
                   rows[k][0] = button3;
              /*button = new JButton("Test Button");
              button.setBackground(Color.red);
              button.addMouseListener(new ColorChanger(button));
              button2 = new JButton("asdf");
              button2.setBackground(Color.red);
              button2.addMouseListener(new ColorChanger(button2));
              rows[0][0] = button;
              rows[1][0] = button2;*/
         private class ColorChanger implements MouseListener {
              private JButton callingButton; //Stores the button that added the Listener
              public ColorChanger(JButton pCallingButton) {  //Constructs a ColorChanger that stores a given JButton
                   callingButton = pCallingButton;
              public void mouseClicked(MouseEvent e) { //When callingButton is clicked, its color changes alternativly to green/red
                   if(isGreen(callingButton) == false)
                        callingButton.setBackground(Color.green);
                   else
                        callingButton.setBackground(Color.red);
              //The 4 methods below are unused leftovers specified by the MouseListener Interface
              public void mouseEntered(MouseEvent arg0) {
              public void mouseExited(MouseEvent arg0) {
              public void mousePressed(MouseEvent arg0) {
              public void mouseReleased(MouseEvent arg0) {
         private boolean isGreen(JButton pButton) { //Returns true if a button's background is green, false otherwise
              if(pButton.getBackground() == Color.green)
                   return true;
              return false;
         public int getColumnCount() { //Returns the number of Columns in a table
              return columns.length;
         public int getRowCount() { //Returns the number of rows in the table
              return rows.length;
         public String getColumnName(int pCollumnIndex) { //Returns the name of the collumn
              return columns[pCollumnIndex];
         public Object getValueAt(int pRow, int pColumn) { //Returns the value at given table coordinates
              return rows[pRow][pColumn];
         public boolean isCellEditable(int pRow, int pColumn) { //Returns true if a cell at given coordinates is editable, false otherwise
                  return false;
         public Class getColumnClass(int pColumnIndex) { //Retrieves the class of the objects in a column
              return getValueAt(0, pColumnIndex).getClass();
    import java.awt.Color;
    import java.awt.Point;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JTable;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.table.TableCellRenderer;
    public class JButtonJTableTest extends JFrame {
         private static final long serialVersionUID = 1;
         private JTable table;
         private TableCellRenderer tableCellRenderer;
         private MouseEvent e2;
         private Class columnClass;
         private JButton button;
         private Point mousePos;
         private int mouseRow, mouseColumn;
         public JButtonJTableTest() {
              super("JButton Table Test");
              table = new JTable(); //Setup the table, assigning the new renderer and model
              tableCellRenderer = table.getDefaultRenderer(JButton.class);
              table.setDefaultRenderer(JButton.class, new JButtonRenderer(tableCellRenderer));
              table.setModel(new ButtonTableModel());
              table.setGridColor(Color.blue);
              table.addMouseListener(new MouseForwarder());
              table.setShowGrid(true);
              add(table); //Add the table to the content pane
         private class MouseForwarder implements MouseListener {
              public void mouseClicked(MouseEvent e) {
                   mousePos = new Point(e.getX(), e.getY()); //Assing mouse coordinates to a point data structure
                   mouseRow = table.rowAtPoint(mousePos);  //Ascertain the mouse's row & column
                   mouseColumn = table.columnAtPoint(mousePos);
                   if(mouseRow == -1 || mouseColumn == -1)  //Ensure that the column is within the table
                        return;
                   columnClass = table.getColumnClass(mouseColumn); //Ascertain the column's class
                   if(columnClass != JButton.class) //If the class is not JButton, exit MouseForwarder
                        return;
                   button = (JButton)table.getValueAt(mouseRow, mouseColumn); //Access the button where the mouse clicked
                   e2 = (MouseEvent)SwingUtilities.convertMouseEvent(table, e, button); //Forward click to button
                   button.dispatchEvent(e2); //Have button take action
                   table.repaint(); //Repaint the table to ensure proper button animation
              //The 4 methods below are unused methods from the MouseListener Interface
              public void mouseEntered(MouseEvent arg0) {
              public void mouseExited(MouseEvent arg0) {
              public void mousePressed(MouseEvent arg0) {
              public void mouseReleased(MouseEvent arg0) {
         public static void main(String[] args) { //Setup and run the window
              JButtonJTableTest test = new JButtonJTableTest();
              test.setSize(300, 300);
              test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              test.setVisible(true);
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    public class JButtonRenderer implements TableCellRenderer {
         private TableCellRenderer defaultRenderer;
         private Component jTableButton;
         public JButtonRenderer(TableCellRenderer pRenderer) {
              defaultRenderer = pRenderer;
         public Component getTableCellRendererComponent(JTable pTable, Object pButton, boolean isSelected,
                                                                     boolean hasFocus, int pRow, int pCollumn) {
              try {
                   jTableButton = (Component)pButton;
                   return (Component)pButton;
              catch(ClassCastException exception) {
                   return defaultRenderer.getTableCellRendererComponent(pTable, pButton, isSelected,
                        hasFocus, pRow, pCollumn);
    }

    This question was crossposted into the Swing forum and should be answered there as that is the correct location for it http://forum.java.sun.com/thread.jspa?threadID=753812

  • How to write an element in a  JTable Cell

    Probably it's a stupid question but I have this problem:
    I have a the necessity to build a JTable in which, when I edit a cell and I push a keyboard button, a new Frame opens to edit the content of the cell.
    But the problem is how to write something in the JTable cell, before setting its model. Because, I know, setCellAT() method of JTree inserts the value in the model and not in the table view. And repainting doesn't function!
    What to do??
    Thanks

    Hi there
    Depending on your table model you should normally change the "cell value" of the tablemodel.
    This could look like:
    JTable table = new JTable();
    TableModel model = table.getModel();
    int rowIndex = 0, columnIndex = 0;
    model.setValueAt("This is a test", rowIndex, columnIndex);
    The tablemodel should then fire an event to the view (i.e. JTable) and the table should be updated.
    Hope this helps you

  • Problem in event handling of combo box in JTable cell

    Hi,
    I have a combo box as an editor for a column cells in JTable. I have a event listener for this combo box. When ever I click on the JTable cell whose editor is combo box,
    I get the following exception,
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.setDispatchComponent(Unknown Source)
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.mousePressed(Unknown Source)
         at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Can any one tell me how to over come this problem.
    Thanks,
    Raghu

    Here's an example of the model I used in my JTable. I've placed 2 comboBoxes with no problems.
    Hope this helps.
    public class FileModel5 extends AbstractTableModel
    public boolean isEditable = false;
    protected static int NUM_COLUMNS = 3;
    // initialize number of rows to start out with ...
    protected static int START_NUM_ROWS = 0;
    protected int nextEmptyRow = 0;
    protected int numRows = 0;
    static final public String file = "File";
    static final public String mailName = "Mail Id";
    static final public String postName = "Post Office Id";
    static final public String columnNames[] = {"File", "Mail Id", "Post Office Id"};
    // List of data
    protected Vector data = null;
    public FileModel5()
    data = new Vector();
    public boolean isCellEditable(int rowIndex, int columnIndex)
    // The 2nd & 3rd column or Value field is editable
    if(isEditable)
    if(columnIndex > 0)
    return true;
    return false;
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c)
    return getValueAt(0, c).getClass();
    * Retrieves number of columns
    public synchronized int getColumnCount()
    return NUM_COLUMNS;
    * Get a column name
    public String getColumnName(int col)
    return columnNames[col];
    * Retrieves number of records
    public synchronized int getRowCount()
    if (numRows < START_NUM_ROWS)
    return START_NUM_ROWS;
    else
    return numRows;
    * Returns cell information of a record at location row,column
    public synchronized Object getValueAt(int row, int column)
    try
    FileRecord5 p = (FileRecord5)data.elementAt(row);
    switch (column)
    case 0:
    return (String)p.file;
    case 1:
    return (String)p.mailName;
    case 2:
    return (String)p.postName;
    catch (Exception e)
    return "";
    public void setValueAt(Object aValue, int row, int column)
    FileRecord5 arow = (FileRecord5)data.elementAt(row);
    arow.setElementAt((String)aValue, column);
    fireTableCellUpdated(row, column);
    * Returns information of an entire record at location row
    public synchronized FileRecord5 getRecordAt(int row) throws Exception
    try
    return (FileRecord5)data.elementAt(row);
    catch (Exception e)
    throw new Exception("Record not found");
    * Used to add or update a record
    * @param tableRecord
    public synchronized void updateRecord(FileRecord5 tableRecord)
    String file = tableRecord.file;
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    boolean addedRow = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    { //update
    data.setElementAt(tableRecord, index);
    else
    if (numRows <= nextEmptyRow)
    //add a row
    numRows++;
    addedRow = true;
    index = nextEmptyRow;
    data.addElement(tableRecord);
    //Notify listeners that the data changed.
    if (addedRow)
    nextEmptyRow++;
    fireTableRowsInserted(index, index);
    else
    fireTableRowsUpdated(index, index);
    * Used to delete a record
    public synchronized void deleteRecord(String file)
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    data.removeElementAt(i);
    nextEmptyRow--;
    numRows--;
    fireTableRowsDeleted(START_NUM_ROWS, numRows);
    * Clears all records
    public synchronized void clear()
    int oldNumRows = numRows;
    numRows = START_NUM_ROWS;
    data.removeAllElements();
    nextEmptyRow = 0;
    if (oldNumRows > START_NUM_ROWS)
    fireTableRowsDeleted(START_NUM_ROWS, oldNumRows - 1);
    fireTableRowsUpdated(0, START_NUM_ROWS - 1);
    * Loads the values into the combo box within the table for mail id
    public void setUpMailColumn(JTable mapTable, ArrayList mailList)
    TableColumn col = mapTable.getColumnModel().getColumn(1);
    javax.swing.JComboBox comboMail = new javax.swing.JComboBox();
    int s = mailList.size();
    for(int i=0; i<s; i++)
    comboMail.addItem(mailList.get(i));
    col.setCellEditor(new DefaultCellEditor(comboMail));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for mail Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Mail Id to see a list of choices");
    * Loads the values into the combo box within the table for post office id
    public void setUpPostColumn(JTable mapTable, ArrayList postList)
    TableColumn col = mapTable.getColumnModel().getColumn(2);
    javax.swing.JComboBox combo = new javax.swing.JComboBox();
    int s = postList.size();
    for(int i=0; i<s; i++)
    combo.addItem(postList.get(i));
    col.setCellEditor(new DefaultCellEditor(combo));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for post office Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Post Office Id to see a list of choices");
    }

  • Update jtable cell via numeric keypad

    Hi,
    I have a problem, trying to figure out how to input numbers in a jtextfield in a jtable cell, from a group of jbuttons (rendered as a numeric keypad). I can get the cell to focus, but when I click on one of the jbuttons in the keypad, the cell loses focus and nothing is printed. I can update the cell by directly typing from the keyboard; that works fine. But I'm lost when trying to do it from the touch-screen keypad. Can anyone point me in the right direction. I assume I need to attach additional listeners somewhere.
    Thanks in-advance.
    Lee

    I can get the cell to focus, Then the code for you button would need to be something like:
    String text = (String)table.getValueAt(...);
    String updated = text + button.getText();
    table.setValueAt(updated, ...);

  • Way to listen for change in JTable cell?

    I am having troubles trying to catch a key event while the user is entering text inside a given JTable cell (x/y location). The JTable only seems to manage String objects in it's cells so I can't place a JTextField in there with a KeyListener on it.
    Currently, I can only get control of the application once the user has left the cell they are editing.
    Does anyone have an example of a JTable 'cell KeyListener' scenario? At this point I want to see if I can print 'hello world' each time I type a character within a cell. Then I'll go from there....

    If you want to know when the contents of a cell have been updated you should use a TableModelListener.
    If you want to know when a character is added/removed from the cell editor then you need to first understand how this works with a simple text field.
    Typically you would use a DocumentListener to receive notifies of a change to the text field. However, within the DocumentEvent you wouldn't be able to change the text field as this notification comes after the text field has already been updated.
    If you need to ability to intercept changes to the text field before they happen, then you would need to use a DocumentFilter. An example of using a DocumentFilter is given in the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#filter]Text Component Features.
    Once you get your regular text field working the way you want, the next step to create a DefaultCellEditor using this JTextField and use this editor in your JTable. The above tutorial also has a section on using editors in a table.

  • Using two editor instances within JTable

    Hello,
    I'm struggling around using component editors within JTable. E.g. selectAll text on entering a JTextField cell or immediately raising the popup while entering a JComboBox cell.
    In my analysis most of these problems arises due the re-use of the cell editor.
    The event sequence is doing things in the context of the old cell while preparing the editor for the new cell has already been started.
    Because it is the same component and some things are bound deep inside the L&F it seems not easy to handle them properly.
    Just an idea from me is to avoid such problems by working with two instances for the editors in general. This should avoid all problems coming out of overlapping event processing. (To provide each cell with an own component is of course no solution)
    Any comment on such an approach?
    Thanks in advance
    Wolfgang R.

    No, it wasn't the custom JTable extension.
    By entering a cell a popup will be shown for a short moment. This is only by using Windows L&F (not Metal). Within the L&F a togglePopup() is called which may cause this problem.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.util.EventObject;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    public class JTableExt extends JTable {
         public static class ComboBoxEnumRenderer extends JComboBox implements
                   TableCellRenderer {
              public ComboBoxEnumRenderer() {
                   setEditable(false);
                   setBackground(Color.WHITE);
              public Component getTableCellRendererComponent(JTable table, Object value,
                        boolean isSelected, boolean hasFocus, int row, int column) {
                   this.removeAllItems();
                   this.addItem(value);
                   return this;
         public static class ComboBoxEnumEditor extends DefaultCellEditor {
              private static String[] values = null;
              public ComboBoxEnumEditor() {
                   super(new JComboBox());
                   values = new String[50000];
                   for (int i = 0; i < values.length; i++) {
                        values[i] = "row_" + i;
              public Component getTableCellEditorComponent(JTable table, Object value,
                        boolean isSelected, int row, int column) {
                   JComboBox combo = (JComboBox) getComponent();
                   combo.removeAllItems();
                   for (int i = 0; i < values.length; i++) {
                        combo.addItem(values);
                   combo.setSelectedIndex(0);
                   return super.getTableCellEditorComponent(table, value, isSelected, row,
                             column);
         public JTableExt() {
              super();
              init();
         // invoke editor on cell entry
         public void changeSelection(final int row, final int column, boolean toggle,
                   boolean extend) {
              super.changeSelection(row, column, toggle, extend);
              if (editCellAt(row, column))
                   getEditorComponent().requestFocusInWindow();
         private void init() {
              setDefaultEditor(Object.class, new ComboBoxEnumEditor());
              setDefaultRenderer(Object.class, new ComboBoxEnumRenderer());
         private static void setUI() {
              String lnfName = "";
              //lnfName = "com.jgoodies.plaf.plastic.Plastic3DLookAndFeel";
              lnfName = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
              try {
                   UIManager.setLookAndFeel(lnfName);
              } catch (Exception exc) {
         public static void main(String args[]) {
              try {
                   setUI();
                   javax.swing.JFrame frame = new javax.swing.JFrame();
                   frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                   frame.getContentPane().setLayout(new BorderLayout());
                   final JTableExt demo = new JTableExt();
                   Object[][] data = new Object[30][1];
                   demo.setModel(new DefaultTableModel(data, new String[] { "first column" }));
                   frame.getContentPane().add("Center", new JScrollPane(demo));
                   frame.setSize(600, 600);
                   frame.setVisible(true);
              } catch (Throwable t) {
                   System.exit(0);
    //end

  • MouseListener for JTable cells using html

    Hello,
    I'm trying to write a MouseListener that determines whether the cursor is positioned over a certain string within a JTable cell. The cell contains an html string to allow for some formatting.
    For instance, the table data for a certain cell could be "<html><b>SomeBoldText</b>moreText<html>". I would like to detect when a mouse click occurs on the bold text.
    My current solution is to create the glyph vector corresponding to the cell content stripped of all html tags and then check if the cursor position is within one of the glyphs that form the string. However, that obviously doesn't take into account the formatting done by html, so its not working very well.
    Any suggestions?

    the only way you could possibly do this, if you used JEditorPane as a renderer. even then i'm not sure.

  • Implementing Copy and Paste on JTable cells.

    Hi to all,
    Can anybody suggest as how to impose copy and paste with Ctrl-C and Ctrl-V by using keys on JTable cells.
    Thanks in advance.
    khiz_eng

    First, add a key listener to the table itself (most likely in the constructor for your table), like so:
      addKeyListener(new KeyListener()
        public void keyTyped(KeyEvent e) {}
        public void keyReleased(KeyEvent e) {}
        public void keyPressed(KeyEvent e)
          tableKeyPressed(e);
      });Next, add the code for the "tableKeyPressed" method. Here's a skeleton you can use as a starting point (obviously, the exact code to copy and paste will depend on the nature of the data you are trying to transfer).
      protected void tableKeyPressed(KeyEvent e)
        // Get selected cols and rows:
        int[] selectedRows = getSelectedRows();
        int[] selectedCols = getSelectedColumns();
        // A "copy" is signified by either ctrl+c, meta+c, or the "copy" button on a Sun keyboard.
        // Unfortunately, Java does not abstract this for us, so we have to test each of these conditions:
        if ((e.getKeyCode() == KeyEvent.VK_COPY) ||
            ((e.getKeyCode() == KeyEvent.VK_C) && e.isControlDown()) ||
            ((e.getKeyCode() == KeyEvent.VK_C) && e.isMetaDown()))
          // Grab the cell(s) that are currently selected by using the selectedRows
          // and selectedCols arrays from above.  Then copy this data to the clipboard.
        // A "paste" is signified by either ctrl+v, meta+v, or the "paste" button on a Sun keyboard.
        // Again, Java does not abstract this for us, so each condition must be tested:
        else if ((e.getKeyCode() == KeyEvent.VK_PASTE) ||
             ((e.getKeyCode() == KeyEvent.VK_V) && e.isControlDown()) ||
             ((e.getKeyCode() == KeyEvent.VK_V) && e.isMetaDown()))
          // Make sure there is valid data in the clipboard.
          // If so, paste it into the selected cell(s).
      }(By the way, this code assumes that you are running on a Sun machine with a Sun keyboard. If you are only targeting windows boxes, then the only key press you really need to worry about is CTRL+C. There's no harm in leaving the other keys in, though.
    Hope that helps,
    Steve

  • Clickable button in jtable header

    Here is a modification of camickr code to make buttons clickable in the jtable cells. The question is how to modify it to make them clickable in the table headers. It looks like there is quite a different behavior in cells and headers (naturally it probably should be this way). More specifically, I guess my question is how do you modify MyColHeaderRenderer class in the code below. Btw, this is also an example I've mentioned in one of the previous posts when a component responds to a press mouse event but not click event when first pressed.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    * @author
    public class Example4a extends JFrame {
        MyCell[][] data = {{new MyCell("A1"), new MyCell("A2")}};
        MyColHeader[] headers = {new MyColHeader("col 1"), new MyColHeader("col 2")};
        /** Creates a new instance of Example5 */
        public Example4a() {
            setTable();
            setSize(200, 200);
            setVisible(true);
            super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public void setTable() {
            DefaultTableModel model = new DefaultTableModel(data, headers){
                public Class getColumnClass(int column) {
                    return MyCell.class;
            MyTable table = new MyTable(model);       
            JScrollPane scrollpane = new JScrollPane(table);
            JPanel top_panel = new JPanel();
            top_panel.setLayout(new BorderLayout());
            getContentPane().add(top_panel);
            top_panel.add(scrollpane, BorderLayout.CENTER);
        public static void main(String[] args) {
            Example4a ex = new Example4a();
        class MyTable extends JTable {
            public MyTable(TableModel model) {
                super(model);
                MyCellRenderer cell_renderer = new MyCellRenderer();
                MyColHeaderRenderer header_renderer = new MyColHeaderRenderer();
                TableColumnModel columnModel = getColumnModel();
                for(int i=0; i<columnModel.getColumnCount(); i++) {
                    TableColumn column = columnModel.getColumn(i);
                    column.setCellRenderer(cell_renderer);
                    column.setCellEditor(cell_renderer);
                    column.setHeaderRenderer(header_renderer);
                this.setRowHeight(50);
        class MyCellRenderer extends AbstractCellEditor
                implements TableCellRenderer, TableCellEditor {
            MyCell editCell;
            public MyCellRenderer() {
            public Component getTableCellRendererComponent(JTable table,
                Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                return (MyCell)value;
            public Component getTableCellEditorComponent(
                    JTable table, Object value, boolean isSelected, int row, int column)  {
                editCell = (MyCell)value;
                return editCell;
            public Object getCellEditorValue() {       
                return editCell;
        class MyCell extends JPanel {
            String text;
            JButton button;
            public MyCell(String text_) {
                text = text_;
                setLayout(new GridBagLayout());
                button = new JButton(text);
                button.addMouseListener(new MouseListener() {
                    public void mouseClicked(MouseEvent e) {
                        System.out.println("cell button is clicked");
                    public void mouseEntered(MouseEvent e) {                   
                    public void mouseExited(MouseEvent e) {
                    public void mousePressed(MouseEvent e) {
                        System.out.println("cell button is pressed");                   
                    public void mouseReleased(MouseEvent e) {
                add(button, new GridBagConstraints(0, 0, 1, 1, 0, 100.0
                    ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(10, 5, 10, 5), 20, 10));
        class MyColHeader extends JPanel {
            String text;
            JButton button;
            public MyColHeader(String text_) {
                text = text_;
                setLayout(new GridBagLayout());
                setBorder(BorderFactory.createEtchedBorder());
                button = new JButton(text);
                button.addMouseListener(new MouseListener() {
                    public void mouseClicked(MouseEvent e) {
                        System.out.println("column header button is clicked");
                    public void mouseEntered(MouseEvent e) {                   
                    public void mouseExited(MouseEvent e) {
                    public void mousePressed(MouseEvent e) {
                        System.out.println("column header button is pressed");                   
                    public void mouseReleased(MouseEvent e) {
                add(button, new GridBagConstraints(0, 0, 1, 1, 0, 0.0
                    ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(3, 0, 3, 0), 5, 0));
        class MyColHeaderRenderer implements TableCellRenderer {
            public Component getTableCellRendererComponent(JTable table,
                Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                return headers[column];
    }

    draw a shape and ensure it is selected
    in the Inspector > hyperlink > enable as hyperlink > click slide button and enter the slide number
    place the object in slide 2 and create a dissolve to automatically build on entry for the object

  • Modifying Components within a cell table not working

    Hello,
    I am displaying JTextFields within JPanels in each cell of a JTable, but when I select a cell I am unable to enter text into the text boxes. Why has this been disabled now that these components are withing a JTable cell?
    Thanks,
    Emily

    Do I have the CellEditor just return the same Panel the renderer returns?It depends and I suppose rather not.. The JTable invokes editor to provide editing component with cell object as parameter. The editor method is then expected, in your case, to set appropiate values to all components in panel and return this panel. However, JTable may also need to draw another cells while you are editing. It will then ask renderer to provide panel for that - if you use exactly same object you may have a "crostalk" between renderer and editor.
    Whatever you will do, the behaviour of JPanel build in JTable cell will be litle different than standalone JPanel - if for example user double clicks in JTextField in cell, this click won't select JTextField - it will start editor only. Single click may not work at all. I did experimented with JComboBox as an editor and found, that to not confuse user too much it is better to have different view for renderer and editor - this way user will be aware about switching between edit and select/view mode.
    Also, any listeners may get confused in JPanel embeded in JTable - they will recive extra events when you prepre panel to display/edit and may miss many mouse events since they will be attached to event pump only while JTable keeps cell in edit mode.
    You need some experiments, I think. I would start from having two instances of same JPanel subclass - one which will work as a renderer and second, which will work as an editor.

Maybe you are looking for

  • IPhone 6 Plus bent twice

    Hi, I bought my iPhone 6 Plus 128GB on launch day and I have since had it replaced twice. The first time it had hundreds of stuck/dead pixels on the screen and the second time it was bent. Around 2 weeks after getting the second replacement, I placed

  • Private browsing crash

    Ok now i realize that the update has private browsing open in a new window, however there is a problem with it. It leaves the original window open so i close it because i only want the private browsing open when i private browse (this is why this ide

  • Stuck in catch-22, please help !

    Since I cannot afford to purchase new Macbooks, I have always relied on eBay for my purchases. I recently "upgraded" from an early 2008 MB to a late 2010 MB. Because the previous owner had not cleared his data, I used instructions that I found here i

  • Inspection lot status MCAN - Lot marked for cancellation

    Hi QM Team, Once we cancel lot through QA02 or if we cancel document then system cancell lot accordingly & put the lot status as "LTCA". But in my system I have seen couple of lot with status "MCAN - Lot marked for cancellation". Can you suggest me h

  • Set delegation and substitution by adminsitrator

    Hi, is there a way to activate delegation and substitution for another user, for example using an adminstrator account? Or is there an API do to this and if yes, does anyone have some sample code? I am working with NWCE 7.2. Thanks, Kevin