Date editing in a JTable

Hello,
whereas a JFormattedTextField with a mask formatter can be used as editor in a
JTable just like in a container, a JFormattedTextField with a date formatter
obviously cannot. The tutorial warns us that table cells are NOT components,
but in what cases do we have to care?
I also understand the tutorial in the way that while editing, the editor is
responsible for displaying the cell, and the cell renderer takes over again
when editing is stopped. Is that right? If yes, I would not have to care for
a special renderer, for I'm quite happy with the default one.
I'm trying to use a JFormattedTextField which would, if working, need only
little code, for the solutions I found in the net are quite expanded.
The code below is in many ways defective:
1) Without renderer
When editing of the date column starts, the date is displayed in the
"dow mon dd hh:mm:ss zzz yyyy" form, and doesn't revert even when no edits
are performed. This doesn't happen if the JFormattedTextField is used
outside a table.
2) With renderer
The value arrives in the renderer sometimes as Object, sometimes as String
(I suppose the editor is responsible for that.)
But before I pursue this approach I would like to ask you, whether you
generally discourge using a JFormattedTextField in a date column.
If not, please comment my understanding and direct me to a solution.
import java.awt.*;
import java.text.*; // ParseException
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*; // MaskFormatter
import javax.swing.table.*;
public class FTFTable extends JFrame {
  public FTFTable() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(200, 200);
    setTitle("FTFTable");
    Container cp = getContentPane();
    String headers[] = {"Date", "Mask: #-##"};
    DateFormat format= new SimpleDateFormat("dd.MM.yyyy");
    DateFormatter df= new DateFormatter(format);
    JFormattedTextField ftfDate= new JFormattedTextField(df);
    MaskFormatter mf1= null;
    try {
      mf1= new MaskFormatter("#-##");
      mf1.setPlaceholderCharacter('_');
    catch (ParseException e) {
      System.out.println(e);
    JFormattedTextField ftf= new JFormattedTextField(mf1);
    final DefaultTableModel dtm= createTableModel(headers);
    dtm.addRow(new Object[]{new java.util.Date(), "1-23"});
    JTable table= new JTable(dtm);
    DefaultTableColumnModel dcm=(DefaultTableColumnModel)table.getColumnModel
//  Use custom editors
    dcm.getColumn(0).setCellEditor(new DefaultCellEditor(ftfDate));
//    dcm.getColumn(0).setCellRenderer(new MyDateRenderer());
    dcm.getColumn(1).setCellEditor(new DefaultCellEditor(ftf));
    JScrollPane scrollPane = new JScrollPane(table);
    cp.add(scrollPane, BorderLayout.CENTER);
    setVisible(true);
  public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
     new FTFTable();
  private DefaultTableModel createTableModel(Object[] columnNames) {
    DefaultTableModel tblModel= new DefaultTableModel(columnNames, 0) {
      public Class getColumnClass(int column) {
     Class returnValue;
     if (column>=0 && column<getColumnCount()) {
       returnValue= getValueAt(0, column).getClass();
     else {
       returnValue= Object.class;
     return returnValue;
    return tblModel;
  class MyDateRenderer extends DefaultTableCellRenderer {
    DateFormat format;
    public MyDateRenderer() {
      super();
      format= new SimpleDateFormat("dd.MM.yyyy");
    public void setValue(Object value) {
      if (value instanceof String) System.out.println("Is String");
      if (value instanceof Object) System.out.println("Is Object");
      System.out.println(value);
      System.out.println(format.format(value)); // Crashes if String
      setText((value == null) ? "" : format.format(value));
}

Thanks Rob, that was helpful advice.
If one needs the date displayed only in the form of one's own locale, there's
no need to implement a cell renderer. Using a JFormattedTextField provides the
additional facility of using the arrow keys to modify days, months or year.
import java.awt.*;
import java.text.*; // ParseException
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.text.*; // MaskFormatter
import javax.swing.table.*;
public class FTFTable extends JFrame {
  public FTFTable() {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(200, 200);
    setTitle("FTFTable");
    Container cp = getContentPane();
    String headers[] = {"Date", "Mask: #-##"};
    MaskFormatter mf1= null;
    try {
      mf1= new MaskFormatter("#-##");
      mf1.setPlaceholderCharacter('_');
    catch (ParseException e) {
      System.out.println(e);
    JFormattedTextField ftf= new JFormattedTextField(mf1);
    DefaultTableModel dtm= createTableModel(headers);
    dtm.addRow(new Object[]{new Date(), "1-23"});
    JTable table= new JTable(dtm);
//    Locale.setDefault(Locale.FRANCE);
//  Use custom editors
    table.setDefaultEditor(Date.class, new DateEditorSupply().getEditor());
    DefaultTableColumnModel dcm=(DefaultTableColumnModel)table.getColumnModel();
    dcm.getColumn(1).setCellEditor(new DefaultCellEditor(ftf));
    JScrollPane scrollPane = new JScrollPane(table);
    cp.add(scrollPane, BorderLayout.CENTER);
    setVisible(true);
  public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
     new FTFTable();
  private DefaultTableModel createTableModel(Object[] columnNames) {
    DefaultTableModel tblModel= new DefaultTableModel(columnNames, 0) {
      public Class getColumnClass(int column) {
     Class returnValue;
     if (column>=0 && column<getColumnCount()) {
       returnValue= getValueAt(0, column).getClass();
     else {
       returnValue= Object.class;
     return returnValue;
    return tblModel;
  public class DateEditorSupply {
    DateEditor editor;
    SimpleDateFormat format;
    public DateEditorSupply() {
//     To be modified according to the locale's default.
//      this("dd MMM yyyy"); // FRANCE
//      this("dd.MM.yyyy"); // GERMANY
      this("dd-MMM-yyyy"); // UK
//      this("MMM d, yyyy"); // US
//Currently this constructor can only be used with the locale's default pattern.
// If you need various patterns, you have to implement a cell renderer as well.
    public DateEditorSupply(String pattern) {
      format= new SimpleDateFormat(pattern);
      format.setLenient(false);
      editor= new DateEditor();
    public DefaultCellEditor getEditor() {
      return editor;
    private class DateEditor extends DefaultCellEditor {
      public DateEditor() {
     super(new JFormattedTextField(new DateFormatter(format)));
      @Override
      public Object getCellEditorValue() {
     try {
       java.sql.Date value= new java.sql.Date(format.parse(
               ((JTextField)getComponent()).getText()).getTime());
       return value;
     catch (ParseException ex) {
       return null;
      @Override
      public Component getTableCellEditorComponent(
          final JTable table, final Object value,
          final boolean isSelected, final int row, final int column) {
     JTextField tf= ((JTextField)getComponent());
     tf.setBorder(new LineBorder(Color.black));
     try {
       tf.setText(format.format(value));
     catch (Exception e) {
       tf.setText("");
     return tf;
      public boolean parseDate(String value) {
     ParsePosition pos= new ParsePosition(0);
     format.parse(value, pos); // updates pos.
     if (pos.getIndex()!=value.length() ||
         format.getCalendar().get(Calendar.YEAR)>2500) return false;
     return true;
      @Override
      public boolean stopCellEditing() {
     String value = ((JTextField)getComponent()).getText();
     if (!value.equals("")) {
/*       This code would accept alphabetic characters within or at the end of
//       the year in a dd.MM.yyyy pattern, as well as more than 4-digits in the
//       year string.
       try {
         format.parse(value);
       catch (ParseException e) {
         ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));
         return false;
       We avoid this in using "parseDate(value)" instead.
       if (!parseDate(value)) {
         ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));
         return false;
     return super.stopCellEditing();
    } // end DateEditor
}Thanks to André for sharing his .
Edited by: Joerg22 on 03.07.2010 14:11
I made some changes to the DateEditorSupply class, so that the code can easily be used when storing the table date in a database.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • I get unwanted duplicate lines when editing the data content of my JTable

    I have created an editable JTable (filled with data from an SQL) with a modified instance of AbstractDataModel.
    I have a phenomenon that I cannot explain nor fix: each time I edit a data field in the JTable and press ENTER or leave the field, the edited line is duplicated. The extra content is not sent to my SQL (if I recreate the table everything is fine, except that certainly the changed value is lost). The problem must come from the Java code.
    Ok, I admit, that I am not a Java pro and might have made a really stupid error, but I cannot find it.
    Has someone already seen such a behavior?
    Thanks
    CCH
    Message was edited by:
    CCHuser

    Now we are drifting away a little from Java and start getting into philosophy ... :-) But one last reply I will do:
    I agree that just playing around with the fuse box is dangerous and brings no benefit. But I am not that unknowing in Java... Technically saying I work in IT, but just not as a programmer but rather as a business consultant (I write the functional concepts that later the programmers have to implement and then I have to talk to them to fix functional errors and do the testing). Besides, I hold an official Java Programmer degree. But when not programming professionally and continuously gaining experience, it is very hard to keep your skill up. Therefore I do one or another hobby project with Java that I could also do better and faster with other tools such as Excel, Access or a simple batch job.
    My concept for trying new things is to get a piece of code from the internet from which I assume I know roughly what it does. Then I use it in my programs, and while altering it to my needs, I continuously keep searching in API, documentation and tutorials or simple trial and error to get better insight into the details.
    And as a scientist you know what I mean when I say that if I try something new, I simply accept for certain details that they work without knowing how. And over time I then take the time for the "how". Many famous people made their inventions by trial and error and while then testing their new observation and changing the surrounding conditions found out why they work. Not that I would claim for myself to be anything close to a genius inventor but I found that the approach works for me to advance in my insights of a solution.
    Sincerely CCH
    Message was edited by:
    CCHuser

  • Reflection errors in Field Data Edit Scripting context(Line Item class)

    Hello Experts,
    I have a script that does some validation in the Field Data Edit Scripting context of the "Line Item" class, and I  have "MATERIAL" as my target. when i try throwing an Application Exception in this context I get a reflection error message box instead of the message I have passed to the Application Exception constructor.
    your help will be greatly appreciated.
    kind regards,

    One thing to be aware of is that no matter how you choose to construct your exception in field, field data edit and collection scripts, the attribute is always set to the be the taget field/collection. Have you noticed that? The script designers made things that way. What's going on here is that the exception raised in the Interprer is caught by the Script Manager and rethrown with the script target as the attribute and your raised exception as the exception.
    One other thing I would point out is that scripts set to execute on the Collection Member Lifecycle event tend to be poor performers.  You can get a faster result if you edit whole collection and chain the errors onto one ChainException. I can only speculate as to why, but I have seen major improvements in complex scripts if I iterate the whole collection, versus implementing a collection memeber lifecycle validate event. This is counter-intuitive, but there it is.
    Finally, exceptions raised in Collection Lifecycle Events that interupt the overall save process in the prescence of parent document Lifecycle Validation events can result in partially saved data. I observed this issue a few years back and it may be resolved now. The only member lifecycle event I use is Created, to lock, default, etc.
    So, for your particular problem, you may want to rethink your strategy and see if you can get things to work for you bypassing that reflection issue. If you still can't raise the exception on MATERIAL, maybe you can raise it on another field, because another advantage of this approach is that you have full control to raise any error on any field on the Line Items.

  • How to remove mandatory field for Last Name in Personal Data Editing Screen

    Hello All,
    CUrrently we are using BP_ ERP5ESS1.31 SP5 & SAP_ESS  603 SP5.
    All my ESS Services are Displaying fine and working from Portal.I am having the requirement like I need to make Last Name as Non-Mandatory field in Personal Data. While Editing the PD Screen, there  i will find the * mark for Last Name filed, i checked through the Global Personalization Make as Mandatory is Not Personalized its showing, i think its defualt prpoerty,so i am unable make any changes from Portal w.r.t Global Personalization.
    I checked in SPRO-- Personal Admin> Custmomizing User Interfaces>Change Screen Modifications, there i find the respective Module pool for those Infotypes and country Specific..
    I cheked forModulePool MP000200--> P0002 and Variable Key-40(For India)  P0002 - NACHIN -- LastName only OF Radio Button is Selected all other Rado buttons are not selected.
    I Checked in V_T588MFPROPS view there for 0002 Infotype P0002 -- NACHN Mandatory check box is Checked all other check boxes are Unchecked.
    How to make that Last Name field as Non-Mandatory in Personal Data Edit Screen, where i need to make the changes.'
    Please list out the Steps..Where i need to do the configuration. And i assigned all the required ESS roles on the backend.
    Thanks in Advance
    Adapag

    Hi,
    I don't think supressing through Global Personalization will change the business logic. Within the Business Logic it checks for the mandatory field.
    After the changes I guess you need to make the changes accordingly.
    The below link might be of some help.
    http://wiki.sdn.sap.com/wiki/pages/viewpage.action?spaceKey=profile&title=ESSPersonalInformationUIenhancementwithoutmodification&decorator=printable
    Please correct if I am wrong.
    Cheers-
    Pramod

  • How to make Birth date field (GBDAT) under IT0002 Personal data editable

    Hello Consultants,
    We had initially  Birth date field (GBDAT) under IT0002 Personal data editable ...But after upgrade is made non editable...
    We want to make it editable again..
    Kindly suggest how we can proceed abt this....

    Hi Anju,
    1. Go to PA30 >> Infotype 0002 >> On Date of Birth Field >> Enter F1 and find the Technical Parameter and idenfity which Screen is being Used... say for Eg: MP000200 / 2010
    2. Go to Feature P0002 in PE03 and then identify the Return code for the Molga and Co. Code.
    This Return feature is nothing but the Variable Key. Say for Example: 10
    3. Now Go to SM30 >> T588M.....
    3. Idenfity the Screen that you found in the  step 1 and Variable Key you found in Step 2.
    i.e. MP000200 / 2010 / 10
    5. Double Click on that record and Find the Screen Field P0002-GBDAT... this has been set to Output Field... change it to Standard and it will work.
    Hope this helps !!!
    Kumarpal Jain.

  • If I use Informatica Big Data Edition do I still need to use Hadoop or MapR or any other similar systems to process data? What all activities will be specific to Informatica BD or Hadoop?

    If I use Informatica Big Data Edition do I still need to use Hadoop or MapR or any other similar systems to process data? What all activities will be specific to Informatica BD and Hadoop?1. My query is to process both structured and unstructured data in real time, so is Informatica Big Data Edition suffecient of do I have to use Hadoop or MapR or Cloudera etc to process data. If so then what all activities will be performed be Informatica and what all activities will require Hadoop.2. Also for scheduling do I need to go for ActiveBatch or I can perform it be native Informatica Scheduler itself?

    If I use Informatica Big Data Edition do I still need to use Hadoop or MapR or any other similar systems to process data? What all activities will be specific to Informatica BD and Hadoop?1. My query is to process both structured and unstructured data in real time, so is Informatica Big Data Edition suffecient of do I have to use Hadoop or MapR or Cloudera etc to process data. If so then what all activities will be performed be Informatica and what all activities will require Hadoop.2. Also for scheduling do I need to go for ActiveBatch or I can perform it be native Informatica Scheduler itself?

  • Editable JComboBox in JTable

    There is a bug in Jdk1.5 (bug#4684090) - When TAB out from Editable Jcombobox in JTable, the focus is moved to outside JTable instead of next cell.
    What is the best workaround for thsi bug.
    Thanks,
    VJ

    I was using java 1.5.0_06 in my application and I had this problem
    When I upgraded to java 1.6.0_01, I no longer had this issue.
    This seems to be a bug in 1.5 version of Java that has been fixed in 1.6
    thanks,

  • Keypressed event for a particular  edited cell of jtable

    hi friend,
    how to write the key pressed event for the edited cell of jtable which having focus on that particular cell.
    pls help me out.

    [http://catb.org/~esr/faqs/smart-questions.html]
    [http://mindprod.com/jgloss/sscce.html]
    db

  • How to diasable Data Edit in Query Builder?

    Is there a way to disable Data Edit in Query Builder in Dev6? When QB was part of Discoverer as Browser it was possible via BROWSER_PROFILE. The QB now ignores this neither it have any table instead. There is note in help that the feature is disabled by default and admin should have to enable it, but, seems, it is occasionally left from previous releases.
    TIA,
    Uldis

    Hi,
    What did you mean the “string”? What did you want to do to use the string parameter?
    Did you mean managed properties?
    If you mean the managed properties, you can just select the managed properties in the query builder, the query builder would automatically generate the path.
    There are some articles about the query builder for your reference.
    http://en.share-gate.com/blog/sharepoint-2013-content-search-site-portal
    http://blogs.technet.com/b/mspfe/archive/2013/02/01/how-query-rules-and-result-sources-can-be-used-to-customize-search-results.aspx
    What’s more, there are some restrictions for KQL, you can also have a look at it.
    http://msdn.microsoft.com/library/ee558911(v=office.15)
    Thanks & Regards,
    Jason
    Jason Guo
    TechNet Community Support

  • Can I use an OLE DB Command Task to call a parameterized stored procedure, perform some data editing and pass variables back to the SSIS for handling?

    I am using a Data Flow and an OLE DB Source to read my staged 3rd party external data. I need to do various Lookups to try and determine if I can find the external person in our database...by SSN...By Name and DOB...etc...
    Now I need to do some more data verification based on the Lookup that is successful. Can I do those data edits against our SQL server application database by utilizing an OLE DB Command? Using a Stored Procedure or can I sue straight SQL to perform my edit
    against every staging row by using a parameter driven query? I'm thinking a Stored Procedure is the way to go here since I have multiple edits against the database. Can I pass back the result of those edits via a variable and then continue my SSIS Data Flow
    by analyzing the result of my Stored Procedure? And how would I do that.
    I am new to the SSIS game here so please be kind and as explicit as possible. If you know of any good web sites that walk through how to perform SQL server database edits against external data in SSIS or even a YouTube, please let me know.
    Thanks!

    Thanks for that...but can I do multiple edits in my Stored Procedure Vaibhav and pass back something that I can then utilize in my SSIS? For example...
    One and Only one Member Span...so I'd be doing a SELECT COUNT(*) based on my match criteria or handle the count accordingly in my Stored Procedure and passing something back via the OLE DB Command and handling it appropriately in SSIS
    Are there "Diabetes" claims...again probably by analyzing a SELECT COUNT(*)
    Am I expecting too much from the SSIS...should I be doing all of this in a Stored Procedure? I was hoping to use the SSIS GUI for everything but maybe that's just not possible. Rather use the Stored Procedure to analyze my stged data, edit accordingly, do
    data stores accordingly...especially the data anomalies...and then use the SSIS to control navigation
    Your thoughts........
    Could you maybe clarify the difference between an OLE DB Command on the Data Flow and the Execute SQL Task on the Control Flow...
    You can get return values from oledb comand if you want to pipeline.
    see this link for more details
    http://josef-richberg.squarespace.com/journal/2011/6/30/ssis-oledb-command-and-procedure-output-params.html
    The procedure should have an output parameter defined for that
    I belive if you've flexibility of using stored procedure you may be better off doing this in execute sql task in control flow. Calling sp in data flow will cause it to execute sp once for each row in dataset whereas in controlflow it will go for set based
    processing
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Load All Data From RecordSet to JTable

    How Load All Data From RecordSet to JTable by JTable to be base on Applet

    Create one table model and setValueAt your data

  • How to edit databases from JTable?

    Hello everyone, I would like to ask your help on how we can edit JTable cells that would be reflected into the database, or how do we change the database via a JTable.
    I have the installer of an application which I made with Java SE called FuelStation.exe
    My class files are ready for sharing along with its source files.
    I have placed it in this location in my website:
    http://www.apachevista.com/alphaprojects/runfiles/
    It is complete with full details about databases, proposed mysql embed, and so on. Please see the file and notify me at [email protected]
    Here is my sample code:
    // DisplayQueryResults.java
    // Display the contents of the Authors table in the
    // Books database.
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.sql.SQLException;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.JTable;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.Box;
    import javax.swing.JInternalFrame;
    import java.util.*; // for the Bundle
    import javax.swing.event.InternalFrameEvent;
    import javax.swing.event.InternalFrameListener;
    import javax.swing.event.InternalFrameAdapter;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.event.*; // step 1
    import javax.swing.table.TableModel; // step 1
    public class DisplayQueryResults extends JInternalFrame implements TableModelListener { // step 2
    // JDBC driver, database URL, username and password
    ResourceBundle bundle = ResourceBundle.getBundle("Accounting");
    final String JDBC_DRIVER = bundle.getString("Driver");
    final String DATABASE_URL = bundle.getString("URL");
    final String USERNAME = bundle.getString("User");
    final String PASSWORD = bundle.getString("Password");
    // default query retrieves all data from authors table
    //static final String DEFAULT_QUERY = "SELECT authors.lastName, authors.firstName, titles.title, titles.editionNumber FROM titles INNER JOIN (authorISBN INNER JOIN authors ON authorISBN.authorID=authors.authorID) ON titles.isbn=authorISBN.isbn";
    final String DEFAULT_QUERY = bundle.getString("Query");
    private ResultSetTableModel tableModel;
    private JTextArea queryArea;
    static final int xOffset = 0, yOffset = 200;
    private boolean ALLOW_COLUMN_SELECTION = false;
    private boolean ALLOW_ROW_SELECTION = true;
    // create ResultSetTableModel and GUI
    public DisplayQueryResults() {  
    super("Sales of the Day",
    true, //resizable
    true, //closable
    true, //maximizable
    false);//iconifiable
    //...Create the GUI and put it in the window...
    //Set the window's location.
    setLocation(xOffset, yOffset);
    // create ResultSetTableModel and display database table
    try {
    // create TableModel for results of query SELECT * FROM authors
    tableModel = new ResultSetTableModel(JDBC_DRIVER, DATABASE_URL,
    USERNAME, PASSWORD, DEFAULT_QUERY);
    // set up JTextArea in which user types queries
    queryArea = new JTextArea(DEFAULT_QUERY, 1, 100);
    queryArea.setWrapStyleWord(true);
    queryArea.setLineWrap(true);
    JScrollPane scrollPane = new JScrollPane(queryArea,
    ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    // set up JButton for submitting queries
    JButton submitButton = new JButton("Submit Query");
    // create Box to manage placement of queryArea and
    // submitButton in GUI
    Box box = Box.createHorizontalBox();
    box.add(scrollPane);
    box.add(submitButton);
    // create JTable delegate for tableModel
    JTable resultTable = new JTable(tableModel);
    resultTable.setFillsViewportHeight(true); // Makes the empty space heights white
    resultTable.setRowSelectionAllowed(true);
    resultTable.getModel().addTableModelListener(this); // step 3
    // place GUI components on content pane
    add(box, BorderLayout.NORTH);
    add(new JScrollPane(resultTable), BorderLayout.CENTER);
    // create event listener for submitButton
    submitButton.addActionListener(
    new ActionListener()
    // pass query to table model
    public void actionPerformed(ActionEvent event)
    // perform a new query
    try
    tableModel.setQuery(queryArea.getText());
    } // end try
    catch ( SQLException sqlException)
    JOptionPane.showMessageDialog(null,
    sqlException.getMessage(), "Database error",
    JOptionPane.ERROR_MESSAGE);
    // try to recover from invalid user query
    // by executing default query
    try {
    tableModel.setQuery(DEFAULT_QUERY);
    queryArea.setText(DEFAULT_QUERY);
    } // end try
    catch (SQLException sqlException2) {
    JOptionPane.showMessageDialog(null,
    sqlException2.getMessage(), "Database error",
    JOptionPane.ERROR_MESSAGE);
    // ensure database connection is closed
    tableModel.disconnectFromDatabase();
    System.exit(1); // terminate application
    } // end inner catch
    } // end outer catch
    } // end actionPerformed
    } // end ActionListener inner class
    ); // end call to addActionListener
    //...Then set the window size or call pack...
         setSize(750,300);
    setVisible(true); // display window
    } // end try
    catch (ClassNotFoundException classNotFound) {
    JOptionPane.showMessageDialog(null,
    "MySQL driver not found", "Driver not found",
    JOptionPane.ERROR_MESSAGE);
    System.exit(1); // terminate application
    } // end catch
    catch (SQLException sqlException) {
    JOptionPane.showMessageDialog(null, sqlException.getMessage(),
    "Database error", JOptionPane.ERROR_MESSAGE);
    // ensure database connection is closed
    tableModel.disconnectFromDatabase();
    System.exit(1); // terminate application
    } // end catch
    // dispose of window when user quits application (this overrides
    // the default of HIDE_ON_CLOSE)
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    // ensure database connection is closed when user quits application
    addInternalFrameListener(
    new InternalFrameAdapter() {
    // disconnect from database and exit when window has closed
    public void windowClosed(WindowEvent event) {
    tableModel.disconnectFromDatabase();
    System.exit(0);
    } // end method windowClosed
    } // end WindowAdapter inner class
    ); // end call to addWindowListener
    } // end DisplayQueryResults constructor
    public void tableChanged(TableModelEvent e) { // step 4
    int row = e.getFirstRow();
    int column = e.getColumn();
    TableModel model = (TableModel)e.getSource();
    String columnName = model.getColumnName(column);
    Object tableModel = model.getValueAt(row, column);
    // Do something with the data...
    System.out.println(tableModel);
    System.out.println("data");
    // execute application
    public static void main(String args[]) {
    new DisplayQueryResults();
    } // end main
    } // end class DisplayQueryResults
    My question is in lines 177-187:
    public void tableChanged(TableModelEvent e) { // step 4
    int row = e.getFirstRow();
    int column = e.getColumn();
    TableModel model = (TableModel)e.getSource();
    String columnName = model.getColumnName(column);
    Object tableModel = model.getValueAt(row, column);
    // Do something with the data...
    System.out.println(tableModel);
    System.out.println("data");
    Why is my listener not working or why is it not implemented when I click the cells in the JTable and why is it not reflected into the JTable or into the console?
    If this is Flash, Things can be done easily, but this is Java, and I dont know much about this language. I admit that I am new to this -intirely new.
    PS:
    When you have solved the problem, please notify me with the code that's changed
    and please share it to others if you like so.
    Best Wishes: Oliver Bob Lagumen
    Email: [email protected]
    website: www.apachevista.com
    Oliver Bob Lagumen
    Edited by: Oliverbob on Jan 24, 2008 9:03 PM

    Why is my listener not working or why is it not implemented when I click the cells in the JTable and why is it not reflected into the JTable or into the console?What does happen when you click on the cells?
    Does the ResultSetTableModel report the cells as editable? If not you will never get to edit their contents, and so the table's model won't change, and so the table model listener will never get invoked.
    When you post code here use the code tags. Basically you put {code} at the start of your code and again at the end. That way the code will be readable.
    Try to post minimal examples with which others can reproduce your problem. In this case "minimal" would involve removing or drastically simplifying a lot of the GUI stuff which is just noise. But "reproduce" would involve including the ResultSetTableModel.
    When you have solved the problem, please notify me with the code that's changedAvoid this.
    What you say here is quite possibly not what you mean. But, in any event, while there might be plenty of interest in helping with specific problems there will likely be none in writing your code. Your problem remains yours. But your solution and your code - prompted by whatever help you might recieve - will also be yours.

  • How can i make perticular row or perticular cell Editable  of a JTable

    Dear al,
    can u help me by guiding me for the problem of...
    i am having a JTable, in which a (first)column of each row is having a checkbox field.
    If the checkbox is checked then and then i should able to modify the cells in that row where the checkbox is.
    I have created the table with AbstractTableModel of which the isCellEditable(int row, int col) method is overwriten. Whatever return value (true/false) reflects the perticular
    cells becomes editable/non-editable respectively.
    but at run time...(mean the table is created now) and now i want to make the cells editable/non-editable depending on the checkbox value...
    how can i implement it.........
    please suggest.........
    thank you.........

    here is the sample code from tutorial.......
    * TableRenderDemo.java requires no other files.
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    * TableRenderDemo is just like TableDemo, except that it explicitly initializes
    * column sizes and it uses a combo box as an editor for the Sport column.
    @SuppressWarnings("serial")
    public class TableRenderDemo extends JPanel {
         private boolean DEBUG = true;
         public TableRenderDemo() {
              super(new GridLayout(1, 0));
              JTable table = new JTable(new MyTableModel());
              // table.setEditingColumn(0);
              // table.editCellAt(0, 0);
              table.setPreferredScrollableViewportSize(new Dimension(500, 100));
              // Create the scroll pane and add the table to it.
              JScrollPane scrollPane = new JScrollPane(table);
              // Set up column sizes.
              initColumnSizes(table);
              // Fiddle with the Sport column's cell editors/renderers.
              setUpSportColumn(table, table.getColumnModel().getColumn(2));
              // Add the scroll pane to this panel.
              add(scrollPane);
          * This method picks good column sizes. If all column heads are wider than
          * the column's cells' contents, then you can just use
          * column.sizeWidthToFit().
         private void initColumnSizes(JTable table) {
              MyTableModel model = (MyTableModel) table.getModel();
              TableColumn column = null;
              Component comp = null;
              int headerWidth = 0;
              int cellWidth = 0;
              Object[] longValues = model.longValues;
              TableCellRenderer headerRenderer = table.getTableHeader()
                        .getDefaultRenderer();
              for (int i = 0; i < 5; i++) {
                   column = table.getColumnModel().getColumn(i);
                   comp = headerRenderer.getTableCellRendererComponent(null, column
                             .getHeaderValue(), false, false, 0, 0);
                   headerWidth = comp.getPreferredSize().width;
                   comp = table.getDefaultRenderer(model.getColumnClass(i))
                             .getTableCellRendererComponent(table, longValues, false,
                                       false, 0, i);
                   cellWidth = comp.getPreferredSize().width;
                   if (DEBUG) {
                        System.out.println("Initializing width of column " + i + ". "
                                  + "headerWidth = " + headerWidth + "; cellWidth = "
                                  + cellWidth);
                   // XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
                   column.setPreferredWidth(Math.max(headerWidth, cellWidth));
         public void setUpSportColumn(JTable table, TableColumn sportColumn) {
              // Set up the editor for the sport cells.
              JComboBox comboBox = new JComboBox();
              comboBox.addItem("Snowboarding");
              comboBox.addItem("Rowing");
              comboBox.addItem("Knitting");
              comboBox.addItem("Speed reading");
              comboBox.addItem("Pool");
              comboBox.addItem("None of the above");
              sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
              // Set up tool tips for the sport cells.
              DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for combo box");
              sportColumn.setCellRenderer(renderer);
         class MyTableModel extends AbstractTableModel {
              private String[] columnNames = { "First Name", "Last Name", "Sport",
                        "# of Years", "Vegetarian" };
              private Object[][] data = {
                        { "Mary", "Campione", "Snowboarding", new Integer(5),
                                  new Boolean(false) },
                        { "Alison", "Huml", "Rowing", new Integer(3), new Boolean(true) },
                        { "Kathy", "Walrath", "Knitting", new Integer(2),
                                  new Boolean(false) },
                        { "Sharon", "Zakhour", "Speed reading", new Integer(20),
                                  new Boolean(true) },
                        { "Philip", "Milne", "Pool", new Integer(10),
                                  new Boolean(false) } };
              public final Object[] longValues = { "Sharon", "Campione",
                        "None of the above", new Integer(20), Boolean.TRUE };
              public int getColumnCount() {
                   return columnNames.length;
              public int getRowCount() {
                   return data.length;
              public String getColumnName(int col) {
                   return columnNames[col];
              public Object getValueAt(int row, int col) {
                   return data[row][col];
              * 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();
              * Don't need to implement this method unless your table's editable.
              public boolean isCellEditable(int row, int col) {
                   // Note that the data/cell address is constant,
                   // no matter where the cell appears onscreen.
                   // return false;
                   return true;
              * Don't need to implement this method unless your table's data can
              * change.
              public void setValueAt(Object value, int row, int col) {
                   if (DEBUG) {
                        System.out.println("Setting value at " + row + "," + col
                                  + " to " + value + " (an instance of "
                                  + value.getClass() + ")");
                   data[row][col] = value;
                   fireTableCellUpdated(row, col);
                   if (DEBUG) {
                        System.out.println("New value of data:");
                        printDebugData();
              private void printDebugData() {
                   int numRows = getRowCount();
                   int numCols = getColumnCount();
                   for (int i = 0; i < numRows; i++) {
                        System.out.print(" row " + i + ":");
                        for (int j = 0; j < numCols; j++) {
                             System.out.print(" " + data[i][j]);
                        System.out.println();
                   System.out.println("--------------------------");
         * Create the GUI and show it. For thread safety, this method should be
         * invoked from the event-dispatching thread.
         private static void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new JFrame("TableRenderDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Create and set up the content pane.
              TableRenderDemo newContentPane = new TableRenderDemo();
              newContentPane.setOpaque(true); // content panes must be opaque
              frame.setContentPane(newContentPane);
              // Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args) {
              // Schedule a job for the event-dispatching thread:
              // creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();

  • Directly enter edit mode of JTable cell

    Hi Everyone,
    On my UI, i am showing editable JTable. When I click on table's row / cell, it selects the row. Fine.
    But I want that it should directly enter edit mode of cell and the whole text is to be selected and highlighted and focussed.
    Thus, user can directly type the new text.
    Please suggest correct approach to handle this scenario.
    Thanks in advance.
    Girish Varde.

    Here is my attempt at solving this problem:
    **  For text selection you have two choices. Remove the "xxx" from either
    **  editCellAt() or prepareEditor() method.
    **  The difference is in how mouse double clicking works
    **  To place a cell directly into edit mode, use the changeSelection() method.
    **  Be aware this will generate a TableModelEvent every time you leave a cell.
    **  You can also use either of the above text selection methods.
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    public class TableEditCell extends JFrame
         public TableEditCell()
              String[] columnNames = {"Number", "Letter"};
              Object[][] data = { {"1", "A"}, {"2", "B"}, {"3", "C"} };
              JTable table = new JTable(data, columnNames)
                   //  Place cell in edit mode when it 'gains focus'
                   public void xxxchangeSelection(
                        int row, int column, boolean toggle, boolean extend)
                        super.changeSelection(row, column, toggle, extend);
                        if (editCellAt(row, column))
                             getEditorComponent().requestFocusInWindow();
                   //  Select the text when the cell starts editing
                   //  a) text will be replaced when you start typing in a cell
                   //  b) text will be selected when you use F2 to start editing
                   //  c) text will be selected when double clicking to start editing
                   public boolean xxxeditCellAt(int row, int column, EventObject e)
                        boolean result = super.editCellAt(row, column, e);
                        final Component editor = getEditorComponent();
                        if (editor != null && editor instanceof JTextComponent)
                             if (e == null)
                                  ((JTextComponent)editor).selectAll();
                             else
                                  SwingUtilities.invokeLater(new Runnable()
                                       public void run()
                                            ((JTextComponent)editor).selectAll();
                        return result;
                   //  Select the text when the cell starts editing
                   //  a) text will be replaced when you start typing in a cell
                   //  b) text will be selected when you use F2 to start editing
                   //  c) caret is placed at end of text when double clicking to start editing
                   public Component xxxprepareEditor(
                        TableCellEditor editor, int row, int column)
                        Component c = super.prepareEditor(editor, row, column);
                        if (c instanceof JTextComponent)
                             ((JTextField)c).selectAll();
                        return c;
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableEditCell frame = new TableEditCell();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • Retrieving Data From Database To JTable

    I'm new to JTable and i'm not sure how do i retrieve the data and put it inside the JTable.
    As from previous example i found on the net, i've tried to incorporate the database but i get various error.
    Here is the sample of the code.
    Object data[];
            String[] columnNames = {"First Name",
                                    "Last Name",
                                    "Sport",
                                    "# of Years",
                                    "Vegetarian"};
              String sqlQuery = ("Select * From Sales_Transaction");
              try{
                   rs = stmt.executeQuery(sqlQuery);
                   while(rs.next()){
            data[] = {
                {rs.getString(1),rs.getString(1),
                 rs.getString(1), rs.getString(1), rs.getString(1)},
              }catch(SQLException sqlex){
                   JOptionPane.showMessageDialog(null,"LOL");
            final JTable table = new JTable(data, columnNames);Any help is appreciated, have been researching hi and low for guides.
    Edited by: zeropulse on Mar 25, 2008 3:01 AM

    data[] = { {rs.getString(1), rs.getString(1), rs.getString(1), rs.getString(1), rs.getString(1)} };Not sure what you expect that to do, you are adding the same value to the array 4 times.
    Don't use arrays when dealing with dynamic data, you don't know the proper size to make the arry. Use a Vector which can grow with each row or column of data. Something like this:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=614671

Maybe you are looking for

  • ICloud account on Mail is frozen

    Hi there, My (paid) iCloud account seems to be locked in Apple Mail (6.2).  It will neither send nor receive messages.  I removed the account from Mail, closed Mail, then re-opened it, the account re-appeared.  Still the same problem. I can access it

  • Menu Module v2 support for selected state?

    I can't figure out if menu module v2 supports the selected state. I remember reading somewhere that it was slated in the future, but it seems the file /ModuleTemplates/Menu/Default/container.html has accommodations for it. A resource if so, would be

  • Fireworks Nav menus to Dreamweaver (CS3) not working

    Hi! Having used Dreamweaver and Fireworks V8 for a while (2 years) i upgraded to CS3 versions, and then went to update a menu from http://www.hernebayhigh.kent.sch.uk/welcome2.html (edit popup menu) within Fireworks which went fine and exported the H

  • Doubts regarding sound in timeline

    Hi,           The site in which I am developing, i have to play a sound. So I played that sound on the timeline. The problem is that I need to implement an On/Off button for sound. How can i implement this, if i played sound on the timeline? Thanks a

  • OAF vs Fusion Technology Stack

    Hi all, We have developed custom business processes (similar to SSHR actions like Termination, Salary Change, etc...) where you enter data through an OAF page or pages, optionally go through approvals and then update Apps or some other application th