How can I add KeyListener to JTable editor

Hi, I want to know how can I add a KeyListener to a JTable editor?
I want to capture the event when any of the cell in the jtable has a key typed.

If your goal is to check the entered value, it's more elegant to do this in overriding
DefaultCellEditor#stopCellEditing and return false when the value is not correct.
Example from a DateEditor:
        @Override public boolean stopCellEditing() {
            String value = ((JTextField)getComponent()).getText();
            if(!value.equals("")) {
                try {
                    formatterE.parse(value);
                } catch (ParseException e) {
                    ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));
                    return false;
            return super.stopCellEditing();
        }

Similar Messages

  • How can i add rows to a JTable at run time ??????

    hi there
    how can i add a row to a JTable at run time? and display the table after the change? thank you.

    For adding or removing the rows from the JTable, you have to use the methods on the table model. I would show you a simple implementation of table model.
    public class MyTableModel extends AbstractTableModel {
    private ArrayList rowsList = null;
    private String [] columns = { "Column 1" , "Column 2", "Column 3"};
    public MyTableModel() {
    rowsList = new ArrayList();
    public int getRowCount() {
    return rowsList.size();
    public int getColumnCount() {
    return columns.length;
    public void addRow(MyRow myRow) {
    //MyRow is any of your object.
    rowsList.add(myRow);
    fireTableDataChanged();
    public void removeRow(int rowIndex) {
    rowsList.remove(rowIndex);
    fireTableRowsDeleted(rowIndex, rowIndex);
    public Object getValueAt(int row, in col) {
    MyRow currentRow = (MyRow)rowsList.get(row);
    switch (col) {
    case 0:
    //return the value of first cell
    break;
    case 1 :
    //return the value of second cell
    break;
    case 2 :
    //return the value of third cell
    break;
    }Then create the table using the TableModel using the constructor new JTable(TableModel) and then when you want to add/remove a row from the table, call myTableModel.addRow(MyRow) or myTableModel.removeRow(rowIndex)....I hope that this solves your problem.

  • How can i add a MouseMotionlistener  to the cells in the JTable?

    hi !
    how can i add a MouseMotionlistener to the cells in the JTable?

    yes i have.but that is different from adding MouseMotionlistener to the cells for me .
    i just want get the values where the mouse moves to .

  • How can I add new row/column into existing jTable?

    Hi add!
    Can you help me how can I add new row/column into existing jTable?
    Tnx in adv!

    e.g
    Create two buttons inside the Table ( "Add New Row" ) and ("Add new Column")
    their handlers are:
    add new row:
    //i supose u already have
    DefaultTabelModel tablemodel = new DefaultTableModel(rowdata, columnNames);
    //and   
       JTabel jtable = new JTable(tablemodel);
    // Handler (row)
    jbtAddRow.addActionListener(new ActionListener(){
       public void actionPerformed(ActionEvent e) {
          if(jtable.getSelectedRow() >= 0 )
              tablemodel.insertRow(jtable.getSelectedRow(), new java.util.Vector());  
           else  
                tablemodel.addRow(new java.util.Vector());
        });to add new columns its the same but inside actionPerformed method:
    ask for e.g "Whats the name for the new column"
    then,
       tablemodel.addColumn(nameOfColumn, new java.util.Vector());   Joao
    Message was edited by:
    Java__Estudante

  • How can I add a row into a JTable with JButton

    Hi all. I have the following code:
    package gui;
    import db.*;
    import javax.swing.table.AbstractTableModel;
    import java.util.ArrayList;
    public class FoundersTable extends AbstractTableModel{
        private static final int COLUMNS = 8;
        private String columnNames[] = {"��� ����", "���", "�������", "�������", "���������", "��������",
                "����� �� ����������", "������ �� ����, �����"};
        private ArrayList data;
        public FoundersTable(){
            data = new ArrayList();
        public int getRowCount() {
            return data.size();
        public int getColumnCount() {
            return columnNames.length;
        public String getColumnName(int colIndex) {
            return columnNames[colIndex];
        public Object getValueAt(int rowIndex, int columnIndex) {
            return ((ArrayList)data.get(rowIndex)).get(columnIndex);
        public void setValueAt(Object value, int rowIndex, int columnIndex) {
            ((ArrayList)data.get(rowIndex)).set(columnIndex, value);
            fireTableCellUpdated(rowIndex, columnIndex);
        public void addRow(ArrayList neueZeile) {
            data.add(neueZeile);
            int index = data.size() - 1;
            fireTableRowsInserted(index, index);
        public void removeRow(int index) {
            data.remove(index);
            fireTableRowsDeleted(index, index);
        public void removeAllRows() {
            data.clear();
            fireTableRowsDeleted(0, 0);
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return true;
    }Now in my MainJFrame class I have one button for additing and one button for removing a selected row. How can I add/remove rows with this two buttons.
    Thanks

    No my question is how can I add and remove rows WITH buttons My point was the code is the same. You use the addRow(...) method. Why did you write an addRow(...) method if you aren't going to use it?
    I don't understand your problem. Do you not know how to write an ActionListener?

  • How can I add action listener to a cell or row in a table?

    hi there
    I need to be able to click on one cell or one row in a table, and perform some action, like openning a dialog or something. how can i add listener?

    // See How to Use Tables in tutorial. You will get one idea about Table Renderer and Editors.
    // If u understand the concept, ur problem is very easy to solve by adding Editor to your column.
    "You can think of the renderer as a configurable ink stamp that the table uses to stamp appropriately formatted data onto each cell. When the user starts to edit a cell's data, a cell editor takes over the cell, controlling the cell's editing behavior.
    Here, While tabing thru the table row, default all cell editors are JLabels. (Not editables)
    So u can make it those cells are editable JTextFields or JComboBoxes based on the column while tabbing. And you can add Listeners to that fields too. So those editable fields are called Editor Components.
    // see javax.swing.DefaultCellEditor class for more description
    Here i am adding my own JTextField editor to 3rd column of a table by using
    mytable.getColumnModel().getColumn(2).setCellEditor(editor );
    Here editor is a obj of below class. (Not complete..class)
    public class JbuiEditor extends DefaultCellEditor implements // any listener {
    public JbuiEditor(JTextField tField) {
    super(tField);
    setClickCountToStart(1);
    tField.addFocusListener(this);
    this.editorComponent = tField;
    public Component getComponent(){
         return editorComponent;
    public Component getTreeCellEditorComponent(JTree tree, Object value,
                                  boolean isSelected,
                                  boolean expanded,
                                  boolean leaf, int row) {
         String StringValue = tree.convertValueToText(value, isSelected,
                             expanded, leaf, row, false);
         delegate.setValue(stringValue);
         return editorComponent;
    public Object getCellEditorValue() {
    return super.getCellEditorValue();
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,int row, int column) {
    super.getTableCellEditorComponent(table,value,isSelected,row,column);
    ((JTextField)editorComponent).setText(value.toString());
    //Here u can add any type of listener to this Editor component.like..
    ((JTextField)editorComponent).addActionListener(..);
    ((JTextField)editorComponent).addFocusListener(..);
    return editorComponent;
    Hope gives some idea.

  • How can I add the listener to the CellRenderer

    My class named NoteColumnRenderer extends DefaultTableCellRenderer
    and thhe getTableCellRendererComponent() returns JButton .
    My question is how can I add MouseMotionListener to the JButton
    or how can I add MouseMotionListener to the NoteColumnRenderer ?
    The code below,and there is no effect
    public class NoteColumnRenderer extends DefaultTableCellRenderer {
    public NoteColumnRenderer(boolean multiSelection) {
    super();
    System.out.println("b="+this.getListeners(MouseMotionListener.class).length);
    this.addMouseMotionListener(new MouseMotionListener(){
    public void mouseDragged(MouseEvent e) {
    System.out.println("mouse+++++++");
    public void mouseMoved(MouseEvent e) {
    System.out.println("mouse-------");
    m_button.addMouseMotionListener(new MouseMotionListener(){
    public void mouseDragged(MouseEvent e) {
    // TODO Auto-generated method stub
    System.out.println("mouse=====");
    public void mouseMoved(MouseEvent e) {
    // TODO Auto-generated method stub
    System.out.println("mouse=======");
    System.out.println("a="+this.getListeners(MouseMotionListener.class).length);
    m_multiSelection = multiSelection;
    if (m_multiSelection) {
         m_check = new JCheckBox();
    m_check.setMargin(new Insets(0, 0, 0, 0));
    m_check.setHorizontalAlignment(JLabel.CENTER);
              } else
    m_button.setMargin(new Insets(0, 0, 0, 0));
    m_button.setSize(new Dimension(5, 5));
    m_combobox = new JComboBox();
         } // IDColumnRenderer
         /** Mult-Selection flag */
         private boolean m_multiSelection;
         /** The Single-Selection renderer */
         private JButton m_button=new JButton();
         /* The Multi-Selection renderer */
         private JCheckBox m_check;
         private JComboBox m_combobox;
         protected void setValue(Object value) {
              if (m_multiSelection) {
                   boolean sel = false;
                   if (value == null)
         else if (value instanceof Boolean)
              sel = ((Boolean) value).booleanValue();
                   else
              sel = value.toString().equals("Y");
                   m_check.setSelected(sel);
              else
                   if (value == null)
                   else
         if(value.toString().length()>10)
    m_button.setText(value.toString().substring(0,10)+"...");
                        else
                             m_button.setText(value.toString());
                        m_button.setBackground(Color.WHITE);
         public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
              setValue(value);
              if (m_multiSelection)
                   return m_check;
              else
                   return m_button;
    }

    Listener can be added to a cell editor, not cell renderer.
    Set relevent cess(s) to setEditable == true when you use your custom cell editor.

  • How Can I set up a JTable columns?

    Dear All,
    How can I set up my JTable columns to have the amount the user specifies?
    for example when the user types in 50 in JTextField 1 I want the JTables columns to then set to 50.
    How can this be done?
    Thanks
    lol
    import javax.swing.*;
    import javax.swing.table.TableModel;
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class si1 extends javax.swing.JFrame implements ActionListener {
        JTextField name = new JTextField(15);
        JTextField name1 = new JTextField(15);
        public si1() {
            super("DataBase Loader");
            setSize(1025,740);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel pane = new JPanel();
            JPanel pane1 = new JPanel();
            JPanel pane2 = new JPanel();
            JPanel pane3 = new JPanel();
            JPanel pane4 = new JPanel();
            pane.setLayout(new GridLayout(20,1));
            pane1.setLayout(new BorderLayout());
            int j=10;
            String[][] data = new String[j][2];
            for (int k=0; k<j; k++){
               String[] row = {"",""};
               data[k] = row;
            String[] columnNames = {"First Name", "Last Name"};
            JTable perstab = new JTable(data, columnNames);
            perstab.setGridColor(Color.yellow);
            perstab.setPreferredScrollableViewportSize(new Dimension(500,500));
            JScrollPane scrollPane = new JScrollPane(perstab);
            pane1.add(new JPanel(), BorderLayout.EAST);
            JButton btn = new JButton("What are the names?");
            btn.addActionListener(this);
            btn.putClientProperty("DATABASE", perstab);
            pane1.add(new JPanel().add(btn), BorderLayout.SOUTH);
            pane2.add(name);
            pane3.add(name1);
            pane.add(pane2);
            pane.add(pane3);
            pane1.add(pane, BorderLayout.WEST);
            pane4.add(scrollPane);
            pane1.add(pane4, BorderLayout.CENTER);
            setContentPane(pane1);
            show();
        public static void main(String[] args) {
            si1 frame = new si1();
            frame.setVisible(true);
        public void actionPerformed(ActionEvent e) {
            JTable table = (JTable)((JButton)e.getSource()).getClientProperty("DATABASE");
            TableModel model = table.getModel();
            int count = model.getRowCount();
            String[] firstnames = new String[count];
            String[] lastnames = new String[count];
            for (int i=0; i < count; i++) {
               firstnames[i] = (String)model.getValueAt(i, 0);
                System.out.println("first name at row " + i + ": " + firstnames);
    lastnames[i] = (String)model.getValueAt(i, 1);
    System.out.println("lastname name at row " + i + ": " + lastnames[i]);

    As you can see I have tried this, but no success.
    If I am doing something wrong please accept my apology, and address me in the right direction.
    Thanks
    Lol
    import javax.swing.*;
    import javax.swing.table.TableModel;
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class si1 extends javax.swing.JFrame implements ActionListener {
        JTextField name = new JTextField(15);
        JTextField name1 = new JTextField(15);
        public si1() {
            super("DataBase Loader");
            setSize(1025,740);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel pane = new JPanel();
            JPanel pane1 = new JPanel();
            JPanel pane2 = new JPanel();
            JPanel pane3 = new JPanel();
            JPanel pane4 = new JPanel();
            pane.setLayout(new GridLayout(20,1));
            pane1.setLayout(new BorderLayout());
            int j=10;
            String[][] data = new String[j][2];
            for (int k=0; k<j; k++){
               String[] row = {"",""};
               data[k] = row;
            String[] columnNames = {"First Name", "Last Name"};
            JTable perstab = new JTable(data, columnNames);
         ((DefaultTableModel)perstab.getModel()).setColumnCount(Integer.parseInt(name.getText()));
            perstab.setGridColor(Color.yellow);
            perstab.setPreferredScrollableViewportSize(new Dimension(500,500));
            JScrollPane scrollPane = new JScrollPane(perstab);
            pane1.add(new JPanel(), BorderLayout.EAST);
            JButton btn = new JButton("What are the names?");
            btn.addActionListener(this);
            btn.putClientProperty("DATABASE", perstab);
            pane1.add(new JPanel().add(btn), BorderLayout.SOUTH);
            pane2.add(name);
            pane3.add(name1);
            pane.add(pane2);
            pane.add(pane3);
            pane1.add(pane, BorderLayout.WEST);
            pane4.add(scrollPane);
            pane1.add(pane4, BorderLayout.CENTER);
            setContentPane(pane1);
            show();
        public static void main(String[] args) {
            si1 frame = new si1();
            frame.setVisible(true);
        public void actionPerformed(ActionEvent e) {
            JTable table = (JTable)((JButton)e.getSource()).getClientProperty("DATABASE");
            TableModel model = table.getModel();
            int count = model.getRowCount();
            String[] firstnames = new String[count];
            String[] lastnames = new String[count];
            for (int i=0; i < count; i++) {
               firstnames[i] = (String)model.getValueAt(i, 0);
                System.out.println("first name at row " + i + ": " + firstnames);
    lastnames[i] = (String)model.getValueAt(i, 1);
    System.out.println("lastname name at row " + i + ": " + lastnames[i]);

  • Query by example - how can I display VCRow in JTable?

    I would like to provide the user with a searchable table.
    Actually I would like to use two tables: one, displaying one row where the user can specify the search criteria. And the second table should display the data found.
    I could store the entered criteria locally in a hashmap in TableModel, for example, then create a WHERE clause. This solution is quite messy, since the user can add, remove and rearrange the columns of both tables.
    Or I could use -I hope- the query-by-example feature, like this:
    am = app.getApplicationModule();
    ViewObject vo = am.createViewObject( "MyVO", "mypackage1.PatView" );
    ViewCriteria vc = vo.createViewCriteria();
    ViewCriteriaRow vcr = vc.createViewCriteriaRow();
    Now I can set attributes and use vo.applyViewCriteria() to find my data.
    But how can I bring the first JTable to display this single ViewCriteriaRow, so that the user can do the editing?
    The JUNavigationBar does it, if I am not mistaken. It switches the PanelBinding to find mode, and then a JTable displays a ViewCriteriaRow (?) instead of the ViewObject's data. But I don't want to use the bar. How do I create this behaviour manually?
    The javadoc of JUPanelBinding says:
    "Sets this panel and all its associated iterators into find mode."
    So I guess that setting iterators into find mode is what I need. But I cannot figure out how to do that. Who can?

    You cannot set the iterators in a panelBinding to separate find/data modes individually.
    However you can create two JUPanelBinding objects one for the findMode form and one that displays Data.
    here's what I did to modify a generated SingleForm, to display two panels of the same type one in find mode and other in data mode.
    I changed the jbInit method of the "LayoutPanel" class to be like:
    //declare this as a member of the class.
    JButton findBtn;
    public void jbInit() throws Exception
    // Panel layout
    masterViewPanel = new PanelDeptView(panelBinding);
    //create another instance of PanelBinding for a second (findform) DeptView panel.
    JUPanelBinding binding = new JUPanelBinding("Project3.Mypackage1Module", this);
    binding.setApplication(panelBinding.getApplication());
    masterViewPanel1 = new PanelDeptView(binding); //create second instance
    findBtn = masterViewPanel1.navBar.getButton(JUNavigationBar.BUTTON_FIND);
    findBtn.doClick(); //set the second instance in find mode.
    //add a listener on the second instance's execute button so that it resets the form into find mode
    //this forces the second instance to be in find mode when execute button is pressed.
    masterViewPanel1.navBar.getButton(JUNavigationBar.BUTTON_EXECUTE).addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ev)
    SwingUtilities.invokeLater(new Runnable() {
    public void run()
    findBtn.doClick();
    this.setLayout(panelLayout);
    add(masterViewPanel, BorderLayout.WEST);
    //add the second instance.
    add(masterViewPanel1, BorderLayout.EAST);
    I also had to call findBtn.doClick() again in the "constructor" that takes (JUApplication, boolean) after the panelBinding is executed,
    to force the initial startup of this panel in findmode

  • How can I add the "Profile Removal Password Payload"  to a configuration Profile?

    How can I add the “Profile Removal Password Payload”  to a configuration Profile?
    I’m not seeing an option to add this option when I edit the configuration profile within Apple Configurator.
    Do I have to edit the configuration profile(xml file) within a text editor?
    FYI:
    https://developer.apple.com/library/ios/featuredarticles/iPhoneConfigurationProf ileRef/Introduction/Introduction.html
    Profile Removal Password Payload
    The Removal Password payload is designated by specifying com.apple.profileRemovalPassword value as the PayloadType value.
    A password removal policy payload provides a password to allow users to remove a locked configuration profile from the device. If this payload is present and has a password value set, the device asks for the password when the user taps a profile's Remove button. This payload is encrypted with the rest of the profile.
    Key
    Type
    Value
    RemovalPassword
    String
    Optional. Specifies the removal password for the profile.

    You have found where it is stored in Thunderbird?
    Delete it. When Thunderbird needs it again, it will ask you for it.

  • How can I add a library of flash movies to my site?

    I posted this same question on the Dreamweaver forum and a suggestion was made that I try over here for help, so please excuse the duplicate question.
    How can I add a library of flash movies to my site?
    Hey there everyone and thanks for reading my question.
    I have a library of flash movies (specifically a library of maps) and when the map movies are run in Flash they call each other just fine (i.e. the USA map will load the Georgia map when Georgia is clicked on the USA map, etc etc etc for each state).
    HOWEVER, when I insert the USA map in one of my site pages (I'm working on the site using Dreamweaver CS4) the USA map page will load, but when a state is clicked the area on the page for the map goes blank and the state map does not load.
    Short of coding a specific path in each of my state maps (in the Flash editor) is there a way to tell Dreamweaver there is a library of maps, look there for the sub-map?
    and if I do have to code the path to the map, can I code a relative path rather than a specific URL address for the maps?
    I know this is probably one of those simple things, but I'm not seeing it (can you tell I'm new at this??)
    Thanks in advance for any help!
    Frances

    Hey again,
    Thanks for the helpful suggestions. Everyone's comments got me to thinking about what the path was in the calls from the maps.
    here is what finally worked:
    on (release)
    loadMovie("../FlashIMapDownloads/georgia.swf", 0);  
    this script code is in the action script for the "georgia" button of my main map - a US Map. (I hope I'm describing all this correctly).
    I'll post this same info in the Dreamweaver forum too.
    Thanks again!
    Frances

  • How can I add a PSD logo watermark file to an image in CS4 or Lightroom3?

    Hi,
    I have a psd file with my company logo as a watermark. How can I add that file to an image in CS4 or Lightroom3. I am sure it is really simple and I am just a bit dopey but would appreciate the help.
    Thanks.
    Natalie

    This is fully explained in the help file. Hit F1 and go to using the watermark editor, you will see there is is also a video tutorial so I won't repeat the advice here.
    You will need to change the PSD to a PNG in order to use it and retain any transparency layers. Open the file in Photoshop and choose save for web, then select either the PNG 8 or PNG 24 preset and save a copy of the file.

  • How can i add text to photo in iphoto?

    How can I add text to photo in iphoto without having lion or mtn lion?

    You can't add text to a Photo in iPhoto. You need an external editor for that:
    In order of price here are some suggestions:
    Seashore (free)
    The Gimp (free)
    Graphic Coverter ($45 approx)
    Acorn ($50 approx)
    Pixelmator ($50 approx)
    Photoshop Elements ($75 approx)
    There are many, many other options. Search on MacUpdate. You can set Photoshop (or any image editor) as an external editor in iPhoto. (Preferences -> General -> Edit Photo: Choose from the Drop Down Menu.) This way, when you double click a pic to edit in iPhoto it will open automatically in Photoshop or your Image Editor, and when you save it it's sent back to iPhoto automatically. This is the only way that edits made in another application will be displayed in iPhoto.

  • How can I add an iView to the Detailed Navigation itself

    How can I add an iView to the Detailed Navigation itself and hides the other hyperlinks?

    To add an iview on the Detailed navigation side of a page:
    1.Double click the page which brings up the page editor.
    2.Click the Display dropdown box and choose Dynamic Navigation.
    3.Add an ivew to it.Save and add the page to a role to see the results.
    if this is not u wanted, post back here.
    Regards.

  • How can I add the presets to new catalog or sync info to both catalogs?

    I have lightroom on my main laptop was advised to create a new catalog on my external (my laptop is almost out of space). I just upload some presets to lightroom,--when I use my Lightroom catalog on my external the presets are not loaded at all. How can I add the presets or sync both catalogs. Thank you

    Listener can be added to a cell editor, not cell renderer.
    Set relevent cess(s) to setEditable == true when you use your custom cell editor.

Maybe you are looking for

  • Rule on LOP for 30 days

    Dear Team,    I havea requirement, where LOP is calculated on 30 days basis.    If an employee is taking LOP in month of march.   then LOP calculation should be ( amount / 30 ) * (30 - Lop days).   this I am able to acheive.. and it is working fine.

  • Trouble Creating View Using Derived Values From With

    I want to use the two values derived from the sql statements in my WITH to use in a view. This is my code: WITH a AS( SELECT CASE WHEN (SELECT stvterm_code FROM stvterm WHERE sysdate >= stvterm_start_date AND sysdate <= stvterm_end_date) IS NOT NULL

  • Document literal client

    Hi All, I am trying to access a document literal client service exposed by tibco business works. I modified the sample/jax-rpc/advanced/DIIHelloClient.java to access the service. I am stuck up now in this problem regarding serializers. ( i donno why

  • Applet is not working in IE 5.0

    Hello, I've programmend a Applet which uses only Java 1.1 programming but it doesn't work in IE 5.0 with Opera 5.02 it works fine . Now somebody told me that I either need to install a plugin in IE 5.0 or look for a Java 1.1 Compiler. Is this wright

  • Error message - media being played is of an unsupported format

    This is a known issue that is a pain in the butt.  Your media player is locked up as well.  Look here: http://www.blackberry.com/btsc/microsites/search.do?cmd=displayKC&docType=kc&externalId=KB20612&slic... 0 522224469