PlainDocument

How to find the text fields name in Document class ?
am using two or more text field and all of them using PlainDocument
How i cam find which textfield is currently am typing
each text field r used for different purpouse
Thanks & Regards
vipin

actually my need is
when am typing in to text field the text will be get and .to use this data select some data on data base and it will be display on a table
for example iam typing 'A" the data start with a will be display on table
it is working properly
But the problem is am using two or more text and and inner class extended by palinDocument .the result on the table will be depends up on the which text field is currently am using
How i cam find which text field is currently am using with out using any listeners

Similar Messages

  • Retrieving AttributeSet from PlainDocument

    In looking at the composition of javax.swing.text.Element and the Document and AttributeSet interfaces - it appears as if I should be able to retrieve an AttributeSet that was assigned to a particular location when a string is inserted into a Document.
    However, the code snippet I tried does not return the AttributeSet I sent into the document with insertString. I tried this with both a PlainDocument (usint a JEditorPane) and a DefaultStyledDocument (using JTextPane).
    Is my understanding incorrect? If I do an insertString against a document - supplying an AttributeSet (contents different from items on other side) - shouldn't I be able to get the AttributeSet back by retrieving the element at that offset?
    Code snippet attached,
    jgr
    Document doc = jEditorPane.getDocument();
    String tag = "TAG";
    SimpleAttributeSet attrs = new SimpleAttributeSet();
    attrs.addAttribute(tag,"a test tag");
    int insertLocation = 0;
    doc.insertString(insertLocation, "ABCD", attrs);
    int index = doc.getDefaultRootElement().getElementIndex(insertLocation);
    Element element = doc.getDefaultRootElement().getElement(index);
    AttributeSet eAttrs = element.getAttributes();
    // I thought this would display "a test tag" - but it doesn't.
    // it returns null.
    System.out.println(" entry contents=" + eAttrs.getAttribute(tag));

    AttributeSet eAttrs = element.getAttributes();I think this set should be a Java runtime implementation of one of four predefined attribute sets
    which are, by definition, immutable.

  • Error with class myDocPattern extends PlainDocument

    hi everyone,
    I have made a Pattern in class myDocPattern to make double type validation while typing and goes well, but now it looks like I can't get data ( jText.getText() )
    from text fields which I applied the pattern with.....I need to get the sum of 3 text fields after I applied the pattern
    jtlogic.setDocument(new myDocPattern());
    jtsystem.setDocument(new myDocPattern());
    jtpascal.setDocument(new myDocPattern());
    double totalNum = ( (Double.parseDouble(jtlogic.getText())) + Double.parseDouble(jtsystem.getText())) + (Double.parseDouble(jtpascal.getText())) );but it doesn't seem to work....hoping anybody could help..
    Thanx
    Code:
    class myDocPattern extends PlainDocument
      public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
        String oldText = this.getText(0,this.getLength());
        if (str.length() > 2 || "0123456789.".indexOf(str) < 0 || (str.equals(".") && offs <= 0) ||
           (oldText.length() > 3 && (oldText+str).indexOf(".") <= 1) || (oldText+str).length() > 7)
          java.awt.Toolkit.getDefaultToolkit().beep();
          return;
        super.insertString(offs, str, a);
    }

    That exception is derived from javax.servlet.ServletException.
    That exception has a method called getRootCause(). That returns an exception which will tell you the real cause of the problem.
    By the way are you sure 'Upload' is a File rather than just using a File. The first is inheritence the second is composition.

  • PlainDocument and JFormattedTextField don't work together

    Hello everyone,
    I wrote a PlainDocument only allowing a certain amount of numeric chars to be inserted. This works smoothly with a JTextField.
    The problem is, I need to get it running with a JFormattefTextField, where I added an InternationalFormatter. What happens is, that with each character stringToValue (in InternationalFormatter) is called, insertString (in PlainDocument) is only called on a commitEdit.
    Does anyone know how to change this behaviour?
    Thanks,
    Marc Johnen

    Once again from the java docs
    Warning: As the AbstractFormatter will typically install a DocumentFilter on the Document, and a NavigationFilter on the JFormattedTextField you should not install your own. If you do, you are likely to see odd behavior in that the editing policy of the AbstractFormatter will not be enforced.
    Rereading your post, I thing your international formatter is your conflict point.
    My advice is to use the JFormattedText field as is or don't use it.
    FYI: I tried using JFormattedTextField on my current project and the qa team pretty much hated the fell of it from the get go. I ended up pulling it and writing custome InputVerifier / DocumentFilters where I needed to limit input.
    Hope this helps,
    Todd

  • How to extend PlainDocument for an extremely large Jtextarea?

    I'm trying to extend the PlainDocument class in order to use an external file for saving an extremely large document that's being scrolled in a jtextarea. The document is read-only after it's created. My class uses its own insertString to capture the document as it's created, and sets the length to be passed back by the getLength method. However, the getText requests seem to ignore this length, and only ask for the first character of the document. Any ideas on how to get this to work correctly, or is there a better approach to the general problem?
    Thanks,
    Hartley

    Some more background on this is that when running without the document model, it ran out of heap space. The heap space required was about 4 times the size of the total length I was trying to display, and from research, I think that this is due to the default gap management in the document, keeping possibly multip[le copies of the individual strings that I was appeanding into the text area.  I'm aware that I could split the large input into some individual segments, but the user requirement is to be able to search the document for specific text occurrences, which would not be possible with one search if there were multiple segments.  The obvious solution seemed to be the use of the PlainDocument to manage the storage myself.  I did a lot of searching for examples of how to use it, but they all seemed to be limited to invoking the remove(...) method to cut down on the size, or to do some sort of editing as lines were inserted.  I've actually tried several different ways of handling the getText and insertString methods, and tracing the arguments they're called with.  I just can't figure out why the basic theory of what I'm doing doesn't work - there's more involved but I can't find out what it is.
    Hartley                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Could PlainDocument set Foreground Color Attribute?

    PlainDocument class has a method called
    insertString(int pos,String str,AttributeSet a)
    It looks like we could add attributes to PlainDocument ,but
    when I assign it a Attribute Set ,the foreground color doesn't
    change, could anyone tell me how to change attributes
    in PlainDocument?
    Thanks a lot!
    Caton

    Yes, I tried these two already,but it still doesn,t work.
    I found whether I use JEditorPane or JTextPane ,it does not change anything.
    In the subclass of the JEditorPane ,called SubEditorPane, I write the code
    setContentType("text/plain"); -->to get the DefaultEditor instance for SubEditorPane
    PlainDocument doc = (PlainDocument)getEditorKit().createDefaultDocument();
    -->to get PlainDocument instance
    then I use doc.insertString(0,"This is a Test Words",style);
    where the style is a NamedStyle instance :
    StyleContext sct = new StyleContext();
    Style style = sct.addStyle("test",null);
    style.addAttribute(StyleConstants.Foreground,Color.blue);
    But it doesn't change anything :foreground color is still black!!
    I don't know where I do the wrong thing ,style instance or else ?
    Thanks!
    Caton

  • JInternalFrame size issue

    I'm trying to make an IDE, and have started trying to create a nopepad type editor. My problem occurs when clicking new to create a new internal frame, the frame is created to be the same size as a maximised internal frame would be. I've tryed adding setBounds, setSize, setPreferredSize, setMaximumSize, setMinimumSize functions to the frame, but to no avail. This is the full listing of my code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.text.*;
       Java IDE (Integrated Development Environment)
       IDE.java
       Sets up constants and main viewing frame.
       Advanced 2nd Year HND Project
       @author Mark A. Standen
       @Version 0.2 18/04/2002
    //=========================================================
    //   Main (public class)
    //=========================================================
    public class IDE extends JFrame
          Application Wide Constants
       /**   The Name of the Application   */
       private static final String APPLICATION_NAME = "Java IDE";
       /**   The Application Version   */
       private static final String APPLICATION_VERSION = "0.2";
       /**   The Inset from the edges of the screen of the main viewing frame   */
       private static final int INSET = 50;
       /**   The main frame   */
       private static IDE frame;
          MAIN
       public static void main (String[] Arguments)
          //Adds Cross-Platform functionality by adapting GUI
          try
             UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
             //Adapts to current system look and feel - e.g. windows
          catch (Exception e) {System.err.println("Can't set look and feel: " + e);}
          frame = new IDE();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setVisible(true);
          This Constructor creates an instance of Main, the main view frame.
          @param sizeX Width of the main view Frame in pixels
          @param sizeY Height of the main view Frame in pixels
       public IDE()
          super (APPLICATION_NAME + " (Version " + APPLICATION_VERSION + ")");
          Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          this.setBounds( INSET, INSET, screenSize.width - (INSET * 2), screenSize.height - (INSET * 3) );
          JDesktopPane mainPane = new JDesktopPane();
          mainPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
          this.setContentPane(mainPane);
          this.getContentPane().setLayout( new BorderLayout() );
          this.getContentPane().add("North", new ToolBar() );
    //===================================================================
    //   ToolBar (private class)
    //===================================================================
       private class ToolBar extends JToolBar implements ActionListener
          /*   Create toolbar buttons   */
          private JButton newBox;
          private JButton load;
          private JButton save;
             Creates an un-named toolbar,
             with New, Load, and Save options.
          public ToolBar () {
                Use to make toolbar look nice later on
                ImageIcon imageNew = new ImageIcon("imgNew.gif");
                JButton toolbarNew = new JButton(imageNew);  
                ImageIcon imageLoad = new ImageIcon("imgLoad.gif");
                JButton toolbarLoad = new JButton(imageLoad);  
                ImageIcon imageSave = new ImageIcon("imgSave.gif");
                JButton toolbarSave = new JButton(imageSave);
                temp toolbar buttons for now
             newBox = new JButton("New");
             load = new JButton("Load");
             save = new JButton("Save");
             this.setFloatable(false);
             this.setOrientation(JToolBar.HORIZONTAL);
             this.add(newBox);
             this.add(load);
             this.add(save);
             newBox.addActionListener(this);
             load.addActionListener(this);
             save.addActionListener(this);
             Checks for button presses, and calls the relevant functions
          public void actionPerformed (ActionEvent event)
             Object source = event.getSource();
             /*   If new has been clicked   */
             if (source == newBox)
                TextDisplayFrame textBox = new TextDisplayFrame();
                Rectangle rect = this.getParent().getBounds();
                textBox.setBounds( rect.x - INSET, rect.y - INSET, rect.width - (INSET * 2), rect.height - (INSET * 2) );
                this.getParent().add(textBox);
                textBox.setVisible(true);
             /*   If load has been clicked   */
             else if (source == load)
                TextDisplayFrame textBox = new TextDisplayFrame();
                frame.getContentPane().add(textBox);
                System.out.println(textBox + "");
                textBox.loadDoc();
             /*   If save has been clicked   */
             else if (source == save)
    //====================================================================
    //   Menu (private class)
    //====================================================================
       private class Menu extends JMenu
          public Menu()
             JMenuBar menuBar = new JMenuBar();
             JMenu menu = new JMenu("Document");
             menu.setMnemonic(KeyEvent.VK_D);
             JMenuItem menuItem = new JMenuItem("New");
             menuItem.setMnemonic(KeyEvent.VK_N);
             menuItem.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                      TextDisplayFrame textBox = new TextDisplayFrame();
                      //this.getContentPane().add(textBox);
             menu.add(menuItem);
             menuBar.add(menu);
             menuBar.setVisible(true);
    //====================================================================
    //   TextDisplayFrame (private class)
    //====================================================================
       private class TextDisplayFrame extends JInternalFrame
          /**   The Default Title of an internal pane   */
          private static final String DEFAULT_TITLE = "untitled";
          /**   Path to the current File   */
          private File filePath = new File ("C:" + File.separatorChar + "test.txt");
          /*   Swing Components   */
          private JTextArea mainTextArea;
          private JScrollPane scrollPane;
             Creates a TextDisplayFrame with the given arguments
             @param title Title of the TextDisplayFrame
          public TextDisplayFrame(String title)
             super(title, true, true, true, true); //creates resizable, closable, maximisable, and iconafiable internal frame
             this.setContentPane( textBox() );
             this.setPreferredSize( new Dimension (150, 100) );
             this.setMaximumSize( new Dimension (300, 300) );
             this.setVisible(true);
             Creates a resizable frame with the default title
          public TextDisplayFrame()
             this(DEFAULT_TITLE);
             Creates a blank, resizable central text area, for the entering of text
             @return Returns a JPanel object
          private JPanel textBox()
             mainTextArea = new JTextArea( new PlainDocument() );
             mainTextArea.setLineWrap(false);
             mainTextArea.setFont( new Font("monospaced", Font.PLAIN, 14) );
             scrollPane = new JScrollPane( mainTextArea );
             JPanel pane = new JPanel();
             BorderLayout bord = new BorderLayout();
             pane.setLayout(bord);
             pane.add("Center", scrollPane);
             return pane;
             @return Returns a JTextComponent to be used as document object
          public JTextComponent getDoc()
             return mainTextArea;
          public void loadDoc()
             /* Create blank Document */
             Document textDoc = new PlainDocument();
             /* Attempt to load the document in the filePath into the blank Document object*/
             try
                Reader fileInput = new FileReader(filePath);
                char[] charBuffer = new char[1000];
                int numChars;
                while (( numChars = fileInput.read( charBuffer, 0, charBuffer.length )) != -1 )
                   textDoc.insertString(textDoc.getLength(), new String( charBuffer, 0, numChars ), null);
             catch (IOException error) {System.out.println(error); }
             catch (BadLocationException error) {System.out.println(error); }
             /* Set the loaded document to be the text of the JTextArea */
             this.getDoc().setDocument( textDoc );
    }I would appreciate all/any help that can be offered.

    i have tried out your source and have made some modifications and now it works fine.
    move the desktoppane to be a private variable of the class, so that you can add the InternalFrame to it directly. also the setBounds() needs to be given lil' corrections to c that the InternalFrame appear on the visible area.
    i'm posting entire source just to make sure you don't confuse abt the changes. This is a working version. Hope it serves.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.text.*;
    Java IDE (Integrated Development Environment)
    IDE.java
    Sets up constants and main viewing frame.
    Advanced 2nd Year HND Project
    @author Mark A. Standen
    @Version 0.2 18/04/2002
    //=========================================================
    // Main (public class)
    //=========================================================
    public class IDE extends JFrame
    Application Wide Constants
    /** The Name of the Application */
    private static final String APPLICATION_NAME = "Java IDE";
    /** The Application Version */
    private static final String APPLICATION_VERSION = "0.2";
    /** The Inset from the edges of the screen of the main viewing frame */
    private static final int INSET = 50;
    /** The main frame */
    private static IDE frame;
    /*********** CHANGED HERE ****************/
    private JDesktopPane mainPane;
    /*********** END CHANGE ****************/
    MAIN
    public static void main (String[] Arguments)
    //Adds Cross-Platform functionality by adapting GUI
    try
    UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
    //Adapts to current system look and feel - e.g. windows
    catch (Exception e) {System.err.println("Can't set look and feel: " + e);}
    frame = new IDE();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    This Constructor creates an instance of Main, the main view frame.
    @param sizeX Width of the main view Frame in pixels
    @param sizeY Height of the main view Frame in pixels
    public IDE()
    super (APPLICATION_NAME + " (Version " + APPLICATION_VERSION + ")");
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    this.setBounds( INSET, INSET, screenSize.width - (INSET * 2), screenSize.height - (INSET * 3) );
              /*********** CHANGED HERE ****************/
    mainPane = new JDesktopPane();
    mainPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    //this.setContentPane(mainPane);
    this.getContentPane().setLayout( new BorderLayout() );
    this.getContentPane().add(new ToolBar(), java.awt.BorderLayout.NORTH);
         this.getContentPane().add(mainPane, java.awt.BorderLayout.CENTER);
         /*********** END CHANGE ****************/
    //===================================================================
    // ToolBar (private class)
    //===================================================================
    private class ToolBar extends JToolBar implements ActionListener
    /* Create toolbar buttons */
    private JButton newBox;
    private JButton load;
    private JButton save;
    Creates an un-named toolbar,
    with New, Load, and Save options.
    public ToolBar () {
    Use to make toolbar look nice later on
    ImageIcon imageNew = new ImageIcon("imgNew.gif");
    JButton toolbarNew = new JButton(imageNew);
    ImageIcon imageLoad = new ImageIcon("imgLoad.gif");
    JButton toolbarLoad = new JButton(imageLoad);
    ImageIcon imageSave = new ImageIcon("imgSave.gif");
    JButton toolbarSave = new JButton(imageSave);
    temp toolbar buttons for now
    newBox = new JButton("New");
    load = new JButton("Load");
    save = new JButton("Save");
    this.setFloatable(false);
    this.setOrientation(JToolBar.HORIZONTAL);
    this.add(newBox);
    this.add(load);
    this.add(save);
    newBox.addActionListener(this);
    load.addActionListener(this);
    save.addActionListener(this);
    Checks for button presses, and calls the relevant functions
    public void actionPerformed (ActionEvent event)
    Object source = event.getSource();
    /* If new has been clicked */
    if (source == newBox)
    TextDisplayFrame textBox = new TextDisplayFrame();
    Rectangle rect = mainPane.getBounds();
    /*********** CHANGED HERE ****************/
    //textBox.setBounds( rect.x - INSET, rect.y - INSET, rect.width - (INSET * 2), rect.height - (INSET * 2) );
    //this.getParent().add(textBox);
    mainPane.add(textBox, javax.swing.JLayeredPane.DEFAULT_LAYER);
    textBox.setBounds(rect.x, rect.y, 500, 500);
    /*********** END CHANGE ****************/
    textBox.setVisible(true);
    /* If load has been clicked */
    else if (source == load)
    TextDisplayFrame textBox = new TextDisplayFrame();
    frame.getContentPane().add(textBox);
    System.out.println(textBox + "");
    textBox.loadDoc();
    /* If save has been clicked */
    else if (source == save)
    //====================================================================
    // Menu (private class)
    //====================================================================
    private class Menu extends JMenu
    public Menu()
    JMenuBar menuBar = new JMenuBar();
    JMenu menu = new JMenu("Document");
    menu.setMnemonic(KeyEvent.VK_D);
    JMenuItem menuItem = new JMenuItem("New");
    menuItem.setMnemonic(KeyEvent.VK_N);
    menuItem.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    TextDisplayFrame textBox = new TextDisplayFrame();
    //this.getContentPane().add(textBox);
    menu.add(menuItem);
    menuBar.add(menu);
    menuBar.setVisible(true);
    //====================================================================
    // TextDisplayFrame (private class)
    //====================================================================
    private class TextDisplayFrame extends JInternalFrame
    /** The Default Title of an internal pane */
    private static final String DEFAULT_TITLE = "untitled";
    /** Path to the current File */
    private File filePath = new File ("C:" + File.separatorChar + "test.txt");
    /* Swing Components */
    private JTextArea mainTextArea;
    private JScrollPane scrollPane;
    Creates a TextDisplayFrame with the given arguments
    @param title Title of the TextDisplayFrame
    public TextDisplayFrame(String title)
    super(title, true, true, true, true); //creates resizable, closable, maximisable, and iconafiable internal frame
    this.setContentPane( textBox() );
    this.setPreferredSize( new Dimension (150, 100) );
    /*********** CHANGED HERE ****************/
    //this.setMaximumSize( new Dimension (300, 300) );
    this.setNormalBounds(new Rectangle(300,300));
    /*********** END CHANGE ****************/
    this.setVisible(true);
    Creates a resizable frame with the default title
    public TextDisplayFrame()
    this(DEFAULT_TITLE);
    Creates a blank, resizable central text area, for the entering of text
    @return Returns a JPanel object
    private JPanel textBox()
    mainTextArea = new JTextArea( new PlainDocument() );
    mainTextArea.setLineWrap(false);
    mainTextArea.setFont( new Font("monospaced", Font.PLAIN, 14) );
    scrollPane = new JScrollPane( mainTextArea );
    JPanel pane = new JPanel();
    BorderLayout bord = new BorderLayout();
    pane.setLayout(bord);
    pane.add("Center", scrollPane);
    return pane;
    @return Returns a JTextComponent to be used as document object
    public JTextComponent getDoc()
    return mainTextArea;
    public void loadDoc()
    /* Create blank Document */
    Document textDoc = new PlainDocument();
    /* Attempt to load the document in the filePath into the blank Document object*/
    try
    Reader fileInput = new FileReader(filePath);
    char[] charBuffer = new char[1000];
    int numChars;
    while (( numChars = fileInput.read( charBuffer, 0, charBuffer.length )) != -1 )
    textDoc.insertString(textDoc.getLength(), new String( charBuffer, 0, numChars ), null);
    catch (IOException error) {System.out.println(error); }
    catch (BadLocationException error) {System.out.println(error); }
    /* Set the loaded document to be the text of the JTextArea */
    this.getDoc().setDocument( textDoc );

  • Problems with updating data in excel spreadsheet using ODI

    That's my first post on this forum, therefore I'd like to say Hello to everybody reading it before I present my problem.
    First I configured the ODBC connection to the xls file which conteins my data - the file isn't defined as read-only in the ODBC connection. The next step was setting up a Microsoft Excel Data Server in the topology manager in which I inserted the physical model and of course a logical one referencing the physical one. These steps allowed me to insert a model with my table in the Designer - I can view data throug the option 'view data' appearing after the right-click on the datastore. One of the columns was defined as primary key in constraints. I can use this xls file datastore as a source in an interface - loading the target finishes with a success. But I can't update the data in the xls file using the 'data' option appearing after right-click on the datastore correspondig to it in the designer. The new window with data from file appears without any problem, but when I try to update any of the fields I recieve an error:
    *"See com.borland.dx.dataset.DataSetException error code: BASE+37*
    *com.borland.dx.dataset.DataSetException: DataSet has no unique row identifiers.*
    *Note: For QueryDataSets you need to disable metaDataUpdate.ROWID in the MetaDataUpdate property, in addition to setting the RowId property on a column.* - don't know where to configure it
    at com.borland.dx.dataset.DataSetException.c(Unknown Source)
    at com.borland.dx.dataset.DataSetException.kb(Unknown Source)
    at com.borland.dx.dataset.StorageDataSet.fb(Unknown Source)
    at com.borland.dx.dataset.StorageDataSet.a(Unknown Source)
    at com.borland.dx.dataset.DataSet.startEditCheck(Unknown Source)
    at com.borland.dx.dataset.DataSet.startEdit(Unknown Source)
    at com.borland.dbswing.TableMaskCellEditor.textModified(TableMaskCellEditor.java:340)
    at com.borland.dbswing.TableMaskCellEditor.insertUpdate(TableMaskCellEditor.java:319)
    at javax.swing.text.AbstractDocument.fireInsertUpdate(Unknown Source)
    at javax.swing.text.AbstractDocument.handleInsertString(Unknown Source)
    at javax.swing.text.AbstractDocument.insertString(Unknown Source)
    at javax.swing.text.PlainDocument.insertString(Unknown Source)
    at com.borland.dbswing.DBPlainDocument.insertString(DBPlainDocument.java:77)
    at javax.swing.text.AbstractDocument.replace(Unknown Source)
    at javax.swing.text.JTextComponent.replaceSelection(Unknown Source)
    at javax.swing.text.DefaultEditorKit$DefaultKeyTypedAction.actionPerformed(Unknown Source)
    at javax.swing.SwingUtilities.notifyAction(Unknown Source)
    at javax.swing.JComponent.processKeyBinding(Unknown Source)
    at javax.swing.JComponent.processKeyBindings(Unknown Source)
    at javax.swing.JComponent.processKeyEvent(Unknown Source)
    at com.borland.dbswing.TableMaskCellEditor.processKeyEvent(TableMaskCellEditor.java:627)
    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.KeyboardFocusManager.redispatchEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.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.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)"
    What should I do to be able to modify data from the xls file that way (is it possible in any way)?

    It is not possible to update the data directly from ODI on some technologies, mainly due to some driver limitations.
    I would suggest to edit the spreadsheet in Excel.
    Thanks,
    Julien

  • Problem with addRow and MultiLine Cell renderer

    Hi ,
    Ive a problem with no solution to me .......
    Ive seen in the forum and Ivent found an answer.......
    The problem is this:
    Ive a JTable with a custom model and I use a custom multiline cell renderer.
    (becuse in the real application "way" hasnt static lenght)
    When I add the first row all seem to be ok.....
    when I try to add more row I obtain :
    java.lang.ArrayIndexOutOfBoundsException: 1
    at javax.swing.SizeSequence.insertEntries(SizeSequence.java:332)
    at javax.swing.JTable.tableRowsInserted(JTable.java:2926)
    at javax.swing.JTable.tableChanged(JTable.java:2858)
    at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableMo
    del.java:280)
    at javax.swing.table.AbstractTableModel.fireTableRowsInserted(AbstractTa
    bleModel.java:215)
    at TableDemo$MyTableModel.addRow(TableDemo.java:103)
    at TableDemo$2.actionPerformed(TableDemo.java:256)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:17
    64)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Abstra
    ctButton.java:1817)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:419)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
    istener.java:245)
    at java.awt.Component.processMouseEvent(Component.java:5134)
    at java.awt.Component.processEvent(Component.java:4931)
    at java.awt.Container.processEvent(Container.java:1566)
    at java.awt.Component.dispatchEventImpl(Component.java:3639)
    at java.awt.Container.dispatchEventImpl(Container.java:1623)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
    at java.awt.Container.dispatchEventImpl(Container.java:1609)
    at java.awt.Window.dispatchEventImpl(Window.java:1590)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
    read.java:197)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    This seems to be caused by
    table.setRowHeight(row,(getPreferredSize().height+2)); (line 164 of my example code)
    About the model I think its ok.....but who knows :-(......
    Please HELP me in anyway!!!
    Example code :
    import javax.swing.*;
    import javax.swing.table.*;
    import java.text.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class TableDemo extends JFrame {
    private boolean DEBUG = true;
    MyTableModel myModel = new MyTableModel();
    MyTable table = new MyTable(myModel);
    int i=0;
    public TableDemo() {
    super("TableDemo");
    JButton bottone = new JButton("Aggiungi 1 elemento");
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(bottone,BorderLayout.NORTH);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    bottone.addActionListener(Add_Action);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    class MyTable extends JTable {
    MultiLineCellRenderer multiRenderer=new MultiLineCellRenderer();
    MyTable(TableModel tm)
    super(tm);
    public TableCellRenderer getCellRenderer(int row,int col) {
              if (col==1) return multiRenderer;
              else return super.getCellRenderer(row,col);
    class MyTableModel extends AbstractTableModel {
    Vector data=new Vector();
    final String[] columnNames = {"Name",
    "Way",
    "DeadLine (ms)"
    public int getColumnCount() { return 3; }
    public int getRowCount() { return data.size(); }
    public Object getValueAt(int row, int col) {
    Vector rowdata=(Vector)data.get(row);
                                                                return rowdata.get(col); }
    public String getColumnName(int col) {
    return columnNames[col];
    public void setValueAt (Object value, int row,int col)
         //setto i dati della modifica
    Vector actrow=(Vector)data.get(row);
    actrow.set(col,value);
         this.fireTableCellUpdated(row,col);
         public Class getColumnClass(int c)
              return this.getValueAt(0,c).getClass();
         public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col == 1)
    return false;
    else
    return true;
    public void addRow (String name,ArrayList path,Double dead) {
         Vector row =new Vector();
         row.add(name);
         row.add(path);
         row.add(dead);
         row.add(name); //!!!Mi tengo questo dato da utilizzare come key per andare a
         //prendere il path nella lista dei paths di Project
         //(needed as key to retrive data if name in col. 1 is changed)
         data.add(row);
         //Inspector.inspect(this);
         System.out.println ("Before firing Adding row...."+this.getRowCount());
         this.fireTableRowsInserted(this.getRowCount(),this.getRowCount());
    public void delRow (String namekey)
    for (int i=0;i<this.getRowCount();i++)
    if (namekey.equals(this.getValueAt(i,3)))
    data.remove(i);
    this.fireTableRowsDeleted(i,i);
    //per uscire dal ciclo
    i=this.getRowCount();
    public void delAllRows()
    int i;
    int bound =this.getRowCount();     
    for (i=0;i<bound;i++)     
         {data.remove(0);
         System.out.println ("Deleting .."+data);
    this.fireTableRowsDeleted(0,i);          
    class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {
    private Hashtable rowHeights=new Hashtable();
    public MultiLineCellRenderer() {
    setEditable(false);
    setLineWrap(true);
    setWrapStyleWord(true);
    //this.setBorder(new Border(
    public Component getTableCellRendererComponent(JTable table,Object value,                              boolean isSelected, boolean hasFocus, int row, int column) {
    //System.out.println ("Renderer called"+value.getClass());
    if (value instanceof ArrayList) {
    String way=new String     (value.toString());
    setText(way);
    TableColumn thiscol=table.getColumn("Way");
    //System.out.println ("thiscol :"+thiscol.getPreferredWidth());
    //setto il size della JTextarea sulle dimensioni della colonna
    //per quanto riguarda il widht e su quelle ottenute da screen per l'height
    this.setSize(thiscol.getPreferredWidth(),this.getPreferredSize().height);
    // set the table's row height, if necessary
    //System.out.println ("Valore getPreferred.height"+getPreferredSize().height);
         if (table.getRowHeight(row)!=(this.getPreferredSize().height+2))
         {System.out.println ("Setting Row :"+row);
             System.out.println ("Dimension"+(getPreferredSize().height+2));
             System.out.println ("There are "+table.getRowCount()+"rows in the table ");
             if (row<table.getRowCount())
             table.setRowHeight(row,(getPreferredSize().height+2));
    else
    setText("");
    return this;
    /**Custom JTextField Subclass che permette all'utente di immettere solo numeri
    class WholeNumberField extends JTextField {
    private Toolkit toolkit;
    private NumberFormat integerFormatter;
    public WholeNumberField(int value, int columns) {
    super(columns);
    toolkit = Toolkit.getDefaultToolkit();
    integerFormatter = NumberFormat.getNumberInstance(Locale.US);
    integerFormatter.setParseIntegerOnly(true);
    setValue(value);
    public int getValue() {
    int retVal = 0;
    try {
    retVal = integerFormatter.parse(getText()).intValue();
    } catch (ParseException e) {
    // This should never happen because insertString allows
    // only properly formatted data to get in the field.
    toolkit.beep();
    return retVal;
    public void setValue(int value) {
    setText(integerFormatter.format(value));
    protected Document createDefaultModel() {
    return new WholeNumberDocument();
    protected class WholeNumberDocument extends PlainDocument {
    public void insertString(int offs,
    String str,
    AttributeSet a)
    throws BadLocationException {
    char[] source = str.toCharArray();
    char[] result = new char[source.length];
    int j = 0;
    for (int i = 0; i < result.length; i++) {
    if (Character.isDigit(source))
    result[j++] = source[i];
    else {
    toolkit.beep();
    System.err.println("insertString: " + source[i]);
    super.insertString(offs, new String(result, 0, j), a);
    ActionListener Add_Action = new ActionListener() {
              public void actionPerformed (ActionEvent e)
              System.out.println ("Adding");
              ArrayList way =new ArrayList();
              way.add(new String("Uno"));
              way.add(new String("Due"));
              way.add(new String("Tre"));
              way.add(new String("Quattro"));
              myModel.addRow(new String("Nome"+i++),way,new Double(0));     
    public static void main(String[] args) {
    TableDemo frame = new TableDemo();
    frame.pack();
    frame.setVisible(true);

    In the addRow method, change the line
    this.fireTableRowsInserted(this.getRowCount(),this.getRowCount()); to
    this.fireTableRowsInserted(data.size() - 1, data.size() - 1);Sai Pullabhotla

  • Issue with setting float point in Textfield

    hi
    i have an issue with float input in a textfield.
    what i want to do is.
    when the user start typing numerics it should accept from right hand side and keep appending value from right hand side.
    for ex
    if i want to enter 123.45
    user starts entering
    1 then it should display as 0.01
    2 then it should display as 0.12
    3 then it should display as 1.23
    4 then it should display as 12.34
    5 then it should display as 123.45
    to achive this i have written the code as below
    public class Test{
         public static void main(String[] a){
         try {
    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}
    DecimalFormat format = new DecimalFormat();
    format.setGroupingUsed(true);
    format.setGroupingSize(3);
    format.setParseIntegerOnly(false);
    JFrame f = new JFrame("Numeric Text Field Example");
    final DecimalFormateGen tf = new DecimalFormateGen(10, format);
    // tf.setValue((double) 123456.789);
    tf.setHorizontalAlignment(SwingConstants.RIGHT);
    JLabel lbl = new JLabel("Type a number: ");
    f.getContentPane().add(tf, "East");
    f.getContentPane().add(lbl, "West");
    tf.addKeyListener(new KeyAdapter(){
         public void keyReleased(KeyEvent ke){
              char ch = ke.getKeyChar();
              char key;
              int finalres =0;
              String str,str1 = null,str2 =null,str3 = null,str4= null;
              if(ke.getKeyChar() == KeyEvent.VK_0 || ke.getKeyChar() == KeyEvent.VK_0 ||
                        ke.getKeyChar() == KeyEvent.VK_0 || ke.getKeyChar() == KeyEvent.VK_1 || ke.getKeyChar() == KeyEvent.VK_2 ||
                             ke.getKeyChar() == KeyEvent.VK_3 || ke.getKeyChar() == KeyEvent.VK_4 || ke.getKeyChar() == KeyEvent.VK_5 ||
                             ke.getKeyChar() == KeyEvent.VK_6 || ke.getKeyChar() == KeyEvent.VK_7 || ke.getKeyChar() == KeyEvent.VK_8 ||
                             ke.getKeyChar() == KeyEvent.VK_9 ){
                   double value1 = Double.parseDouble(tf.getText());
                   int position = tf.getCaretPosition();
                   if(tf.getText().length() == 1){
                        if(tf.getText() != null || tf.getText() != ""){
                        value1 = value1 / 100;
                        tf.setText(String.valueOf(value1));
                   /*else if(tf.getText().length() == 3){
                        str = tf.getText();
                        for(int i=0;i<str.length();i++){
                             if(str.charAt(i) == '.'){
                                  str1 = str.substring(0,i);
                                  str2 = str.substring(i+1,str.length()-1);
                                  break;
                        key = ke.getKeyChar();
                        finalres = calculate.calculate1(str2,key);
                        str3 = merge.merge1(str1,finalres);
                        tf.setText(str3);
                        System.out.println(key);
                        System.out.println(str1);
                        System.out.println(str2);
                   else{
                        value1 = Float.parseFloat(tf.getText());
                        value1 = value1*10;
                        tf.setText(String.valueOf(value1));
    tf.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    try {
    tf.normalize();
    Long l = tf.getLongValue();
    System.out.println("Value is (Long)" + l);
    } catch (ParseException e1) {
    try {
    Double d = tf.getDoubleValue();
    System.out.println("Value is (Double)" + d);
    } catch (ParseException e2) {
    System.out.println(e2);
    f.pack();
    f.setVisible(true);
    import javax.swing.JTextField;
    * Created on May 25, 2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author jagjeevanreddyg
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.text.DecimalFormat;
    import java.text.ParseException;
    import java.text.ParsePosition;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.UIManager;
    import javax.swing.text.AbstractDocument;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    import javax.swing.text.PlainDocument;
    import javax.swing.text.AbstractDocument.Content;
    public class DecimalFormateGen extends JTextField implements
    NumericPlainDocument.InsertErrorListener {
         public DecimalFormateGen() {
         this(null, 0, null);
         public DecimalFormateGen(String text, int columns, DecimalFormat format) {
         super(null, text, columns);
         NumericPlainDocument numericDoc = (NumericPlainDocument) getDocument();
         if (format != null) {
         numericDoc.setFormat(format);
         numericDoc.addInsertErrorListener(this);
         public DecimalFormateGen(int columns, DecimalFormat format) {
         this(null, columns, format);
         public DecimalFormateGen(String text) {
         this(text, 0, null);
         public DecimalFormateGen(String text, int columns) {
         this(text, columns, null);
         public void setFormat(DecimalFormat format) {
         ((NumericPlainDocument) getDocument()).setFormat(format);
         public DecimalFormat getFormat() {
         return ((NumericPlainDocument) getDocument()).getFormat();
         public void formatChanged() {
         // Notify change of format attributes.
         setFormat(getFormat());
         // Methods to get the field value
         public Long getLongValue() throws ParseException {
         return ((NumericPlainDocument) getDocument()).getLongValue();
         public Double getDoubleValue() throws ParseException {
         return ((NumericPlainDocument) getDocument()).getDoubleValue();
         public Number getNumberValue() throws ParseException {
         return ((NumericPlainDocument) getDocument()).getNumberValue();
         // Methods to install numeric values
         public void setValue(Number number) {
         setText(getFormat().format(number));
         public void setValue(long l) {
         setText(getFormat().format(l));
         public void setValue(double d) {
         setText(getFormat().format(d));
         public void normalize() throws ParseException {
         // format the value according to the format string
         setText(getFormat().format(getNumberValue()));
         // Override to handle insertion error
         public void insertFailed(NumericPlainDocument doc, int offset, String str,
         AttributeSet a) {
         // By default, just beep
         Toolkit.getDefaultToolkit().beep();
         // Method to create default model
         protected Document createDefaultModel() {
         return new NumericPlainDocument();
         // Test code
         public static void main(String[] args) {
         try {
         UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
         } catch (Exception evt) {}
         DecimalFormat format = new DecimalFormat("#,###.###");
         format.setGroupingUsed(true);
         format.setGroupingSize(3);
         format.setParseIntegerOnly(false);
         JFrame f = new JFrame("Numeric Text Field Example");
         final DecimalFormateGen tf = new DecimalFormateGen(10, format);
         tf.setValue((double) 123456.789);
         JLabel lbl = new JLabel("Type a number: ");
         f.getContentPane().add(tf, "East");
         f.getContentPane().add(lbl, "West");
         tf.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
         try {
         tf.normalize();
         Long l = tf.getLongValue();
         System.out.println("Value is (Long)" + l);
         } catch (ParseException e1) {
         try {
         Double d = tf.getDoubleValue();
         System.out.println("Value is (Double)" + d);
         } catch (ParseException e2) {
         System.out.println(e2);
         f.pack();
         f.setVisible(true);
         class NumericPlainDocument extends PlainDocument {
         public NumericPlainDocument() {
         setFormat(null);
         public NumericPlainDocument(DecimalFormat format) {
         setFormat(format);
         public NumericPlainDocument(AbstractDocument.Content content,
         DecimalFormat format) {
         super(content);
         setFormat(format);
         try {
         format
         .parseObject(content.getString(0, content.length()), parsePos);
         } catch (Exception e) {
         throw new IllegalArgumentException(
         "Initial content not a valid number");
         if (parsePos.getIndex() != content.length() - 1) {
         throw new IllegalArgumentException(
         "Initial content not a valid number");
         public void setFormat(DecimalFormat fmt) {
         this.format = fmt != null ? fmt : (DecimalFormat) defaultFormat.clone();
         decimalSeparator = format.getDecimalFormatSymbols()
         .getDecimalSeparator();
         groupingSeparator = format.getDecimalFormatSymbols()
         .getGroupingSeparator();
         positivePrefix = format.getPositivePrefix();
         positivePrefixLen = positivePrefix.length();
         negativePrefix = format.getNegativePrefix();
         negativePrefixLen = negativePrefix.length();
         positiveSuffix = format.getPositiveSuffix();
         positiveSuffixLen = positiveSuffix.length();
         negativeSuffix = format.getNegativeSuffix();
         negativeSuffixLen = negativeSuffix.length();
         public DecimalFormat getFormat() {
         return format;
         public Number getNumberValue() throws ParseException {
         try {
         String content = getText(0, getLength());
         parsePos.setIndex(0);
         Number result = format.parse(content, parsePos);
         if (parsePos.getIndex() != getLength()) {
         throw new ParseException("Not a valid number: " + content, 0);
         return result;
         } catch (BadLocationException e) {
         throw new ParseException("Not a valid number", 0);
         public Long getLongValue() throws ParseException {
         Number result = getNumberValue();
         if ((result instanceof Long) == false) {
         throw new ParseException("Not a valid long", 0);
         return (Long) result;
         public Double getDoubleValue() throws ParseException {
         Number result = getNumberValue();
         if ((result instanceof Long) == false
         && (result instanceof Double) == false) {
         throw new ParseException("Not a valid double", 0);
         if (result instanceof Long) {
         result = new Double(result.doubleValue());
         return (Double) result;
         public void insertString(int offset, String str, AttributeSet a)
         throws BadLocationException {
         if (str == null || str.length() == 0) {
         return;
         Content content = getContent();
         int length = content.length();
         int originalLength = length;
         parsePos.setIndex(0);
         // Create the result of inserting the new data,
         // but ignore the trailing newline
         String targetString = content.getString(0, offset) + str
         + content.getString(offset, length - offset - 1);
         // Parse the input string and check for errors
         do {
         boolean gotPositive = targetString.startsWith(positivePrefix);
         boolean gotNegative = targetString.startsWith(negativePrefix);
         length = targetString.length();
         // If we have a valid prefix, the parse fails if the
         // suffix is not present and the error is reported
         // at index 0. So, we need to add the appropriate
         // suffix if it is not present at this point.
         if (gotPositive == true || gotNegative == true) {
         String suffix;
         int suffixLength;
         int prefixLength;
         if (gotPositive == true && gotNegative == true) {
         // This happens if one is the leading part of
         // the other - e.g. if one is "(" and the other "(("
         if (positivePrefixLen > negativePrefixLen) {
         gotNegative = false;
         } else {
         gotPositive = false;
         if (gotPositive == true) {
         suffix = positiveSuffix;
         suffixLength = positiveSuffixLen;
         prefixLength = positivePrefixLen;
         } else {
         // Must have the negative prefix
         suffix = negativeSuffix;
         suffixLength = negativeSuffixLen;
         prefixLength = negativePrefixLen;
         // If the string consists of the prefix alone,
         // do nothing, or the result won't parse.
         if (length == prefixLength) {
         break;
         // We can't just add the suffix, because part of it
         // may already be there. For example, suppose the
         // negative prefix is "(" and the negative suffix is
         // "$)". If the user has typed "(345$", then it is not
         // correct to add "$)". Instead, only the missing part
         // should be added, in this case ")".
         if (targetString.endsWith(suffix) == false) {
         int i;
         for (i = suffixLength - 1; i > 0; i--) {
         if (targetString
         .regionMatches(length - i, suffix, 0, i)) {
         targetString += suffix.substring(i);
         break;
         if (i == 0) {
         // None of the suffix was present
         targetString += suffix;
         length = targetString.length();
         format.parse(targetString, parsePos);
         int endIndex = parsePos.getIndex();
         if (endIndex == length) {
         break; // Number is acceptable
         // Parse ended early
         // Since incomplete numbers don't always parse, try
         // to work out what went wrong.
         // First check for an incomplete positive prefix
         if (positivePrefixLen > 0 && endIndex < positivePrefixLen
         && length <= positivePrefixLen
         && targetString.regionMatches(0, positivePrefix, 0, length)) {
         break; // Accept for now
         // Next check for an incomplete negative prefix
         if (negativePrefixLen > 0 && endIndex < negativePrefixLen
         && length <= negativePrefixLen
         && targetString.regionMatches(0, negativePrefix, 0, length)) {
         break; // Accept for now
         // Allow a number that ends with the group
         // or decimal separator, if these are in use
         char lastChar = targetString.charAt(originalLength - 1);
         int decimalIndex = targetString.indexOf(decimalSeparator);
         if (format.isGroupingUsed() && lastChar == groupingSeparator
         && decimalIndex == -1) {
         // Allow a "," but only in integer part
         break;
         if (format.isParseIntegerOnly() == false
         && lastChar == decimalSeparator
         && decimalIndex == originalLength - 1) {
         // Allow a ".", but only one
         break;
         // No more corrections to make: must be an error
         if (errorListener != null) {
         errorListener.insertFailed(this, offset, str, a);
         return;
         } while (true == false);
         // Finally, add to the model
         super.insertString(offset, str, a);
         public void addInsertErrorListener(InsertErrorListener l) {
         if (errorListener == null) {
         errorListener = l;
         return;
         throw new IllegalArgumentException(
         "InsertErrorListener already registered");
         public void removeInsertErrorListener(InsertErrorListener l) {
         if (errorListener == l) {
         errorListener = null;
         public interface InsertErrorListener {
         public abstract void insertFailed(NumericPlainDocument doc, int offset,
         String str, AttributeSet a);
         protected InsertErrorListener errorListener;
         protected DecimalFormat format;
         protected char decimalSeparator;
         protected char groupingSeparator;
         protected String positivePrefix;
         protected String negativePrefix;
         protected int positivePrefixLen;
         protected int negativePrefixLen;
         protected String positiveSuffix;
         protected String negativeSuffix;
         protected int positiveSuffixLen;
         protected int negativeSuffixLen;
         protected ParsePosition parsePos = new ParsePosition(0);
         protected static DecimalFormat defaultFormat = new DecimalFormat();
    this is not working as desired pls help me.
    can we use this code and get the desired result or is there any other way to do this.
    it is very urgent for me pls help immediately
    thanks in advance

    Hi camickr
    i learned how to format the code now, and u also responded for my testarea problem , iam very much thankful to u, and now i repeat the same problem what i have with a text field.
    actually i have window with a textfield on it and while end user starts entering data in it , it should be have as follows
    when the user start typing numerics it should accept from right hand side and keep appending value from right hand side.
    first the default value should be as 0.00 and as the user starts entering
    then it is as follows
    for ex
    if i want to enter 123.45
    user starts entering
    1 then it should display as 0.01
    2 then it should display as 0.12
    3 then it should display as 1.23
    4 then it should display as 12.34
    5 then it should display as 123.45
    i hope u will give me quick reply because this is very hard time for me.

  • Line Number in JTextPane

    Hi Experts;
    How do I add a caret listener on this code so that it will just add a number
    when the user goes to the next line.
    import java.awt.*;
    import javax.swing.*;
    public class LineNumber extends JComponent
         private final static Color DEFAULT_BACKGROUND = new Color(213, 213, 234);
         private final static Color DEFAULT_FOREGROUND = Color.white;
         private final static Font DEFAULT_FONT = new Font("arial", Font.PLAIN, 11);
         // LineNumber height (abends when I use MAX_VALUE)
         private final static int HEIGHT = Integer.MAX_VALUE - 1000000;
         // Set right/left margin
         private final static int MARGIN = 5;
         // Line height of this LineNumber component
         private int lineHeight;
         // Line height of this LineNumber component
         private int fontLineHeight;
         // With of the LineNumber component
         private int currentRowWidth;
         // Metrics of this LineNumber component
         private FontMetrics fontMetrics;
          * Convenience constructor for Text Components
         public LineNumber(JComponent component)
              if (component == null)
                   setBackground( DEFAULT_BACKGROUND );
                   setForeground( DEFAULT_FOREGROUND );
                   setFont( DEFAULT_FONT );
              else
                   setBackground( DEFAULT_BACKGROUND );
                   setForeground( DEFAULT_FOREGROUND );
                   setFont( component.getFont() );
              setPreferredSize( 99 );
         public void setPreferredSize(int row)
              int width = fontMetrics.stringWidth( String.valueOf(row) );
              if (currentRowWidth < width)
                   currentRowWidth = width;
                   setPreferredSize( new Dimension(2 * MARGIN + width, HEIGHT) );
         public void setFont(Font font)
              super.setFont(font);
              fontMetrics = getFontMetrics( getFont() );
              fontLineHeight = fontMetrics.getHeight();
          * The line height defaults to the line height of the font for this
          * component. The line height can be overridden by setting it to a
          * positive non-zero value.
         public int getLineHeight()
              if (lineHeight == 0)
                   return fontLineHeight;
              else
                   return lineHeight;
         public void setLineHeight(int lineHeight)
              if (lineHeight > 0)
                   this.lineHeight = lineHeight;
         public int getStartOffset()
              return 4;
         public void paintComponent(Graphics g)
               int lineHeight = getLineHeight();
               int startOffset = getStartOffset();
               Rectangle drawHere = g.getClipBounds();
               g.setColor( getBackground() );
               g.fillRect(drawHere.x, drawHere.y, drawHere.width, drawHere.height);
               g.setColor( getForeground() );
               int startLineNumber = (drawHere.y / lineHeight) + 1;
               int endLineNumber = startLineNumber + (drawHere.height / lineHeight);
               int start = (drawHere.y / lineHeight) * lineHeight + lineHeight - startOffset;
               for (int i = startLineNumber; i <= endLineNumber; i++)
               String lineNumber = String.valueOf(i);
               int width = fontMetrics.stringWidth( lineNumber );
               g.drawString(lineNumber, MARGIN + currentRowWidth - width, start);
               start += lineHeight;
               setPreferredSize( endLineNumber );
    } Thanks for your time . . .
    The_Developer

    Here's what I use. It behaves correctly WRT wrapped lines, and should work equally well with a JTextArea or a JTextPane.
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Rectangle;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.BorderFactory;
    import javax.swing.JComponent;
    import javax.swing.SizeSequence;
    import javax.swing.UIManager;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    import javax.swing.text.Element;
    import javax.swing.text.JTextComponent;
    * LineNumberView is a simple line-number gutter that works correctly
    * even when lines are wrapped in the associated text component.  This
    * is meant to be used as the RowHeaderView in a JScrollPane that
    * contains the associated text component.  Example usage:
    *<pre>
    *   JTextArea ta = new JTextArea();
    *   ta.setLineWrap(true);
    *   ta.setWrapStyleWord(true);
    *   JScrollPane sp = new JScrollPane(ta);
    *   sp.setRowHeaderView(new LineNumberView(ta));
    *</pre>
    * @author Alan Moore
    public class LineNumberView extends JComponent
      // This is for the border to the right of the line numbers.
      // There's probably a UIDefaults value that could be used for this.
      private static final Color BORDER_COLOR = Color.GRAY;
      private static final int WIDTH_TEMPLATE = 99999;
      private static final int MARGIN = 5;
      private FontMetrics viewFontMetrics;
      private int maxNumberWidth;
      private int componentWidth;
      private int textTopInset;
      private int textFontAscent;
      private int textFontHeight;
      private JTextComponent text;
      private SizeSequence sizes;
      private int startLine = 0;
      private boolean structureChanged = true;
       * Construct a LineNumberView and attach it to the given text component.
       * The LineNumberView will listen for certain kinds of events from the
       * text component and update itself accordingly.
       * @param startLine the line that changed, if there's only one
       * @param structureChanged if <tt>true</tt>, ignore the line number and
       *     update all the line heights.
      public LineNumberView(JTextComponent text)
        if (text == null)
          throw new IllegalArgumentException("Text component cannot be null");
        this.text = text;
        updateCachedMetrics();
        UpdateHandler handler = new UpdateHandler();
        text.getDocument().addDocumentListener(handler);
        text.addPropertyChangeListener(handler);
        text.addComponentListener(handler);
        setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, BORDER_COLOR));
       * Schedule a repaint because one or more line heights may have changed.
       * @param startLine the line that changed, if there's only one
       * @param structureChanged if <tt>true</tt>, ignore the line number and
       *     update all the line heights.
      private void viewChanged(int startLine, boolean structureChanged)
        this.startLine = startLine;
        this.structureChanged = structureChanged;
        revalidate();
        repaint();
      /** Update the line heights as needed. */
      private void updateSizes()
        if (startLine < 0)
          return;
        if (structureChanged)
          int count = getAdjustedLineCount();
          sizes = new SizeSequence(count);
          for (int i = 0; i < count; i++)
            sizes.setSize(i, getLineHeight(i));
          structureChanged = false;
        else
          sizes.setSize(startLine, getLineHeight(startLine));
        startLine = -1;
      /* Copied from javax.swing.text.PlainDocument */
      private int getAdjustedLineCount()
        // There is an implicit break being modeled at the end of the
        // document to deal with boundary conditions at the end.  This
        // is not desired in the line count, so we detect it and remove
        // its effect if throwing off the count.
        Element map = text.getDocument().getDefaultRootElement();
        int n = map.getElementCount();
        Element lastLine = map.getElement(n - 1);
        if ((lastLine.getEndOffset() - lastLine.getStartOffset()) > 1)
          return n;
        return n - 1;
       * Get the height of a line from the JTextComponent.
       * @param index the line number
       * @param the height, in pixels
      private int getLineHeight(int index)
        int lastPos = sizes.getPosition(index) + textTopInset;
        int height = textFontHeight;
        try
          Element map = text.getDocument().getDefaultRootElement();
          int lastChar = map.getElement(index).getEndOffset() - 1;
          Rectangle r = text.modelToView(lastChar);
          height = (r.y - lastPos) + r.height;
        catch (BadLocationException ex)
          ex.printStackTrace();
        return height;
       * Cache some values that are used a lot in painting or size
       * calculations. Also ensures that the line-number font is not
       * larger than the text component's font (by point-size, anyway).
      private void updateCachedMetrics()
        Font textFont = text.getFont();
        FontMetrics fm = getFontMetrics(textFont);
        textFontHeight = fm.getHeight();
        textFontAscent = fm.getAscent();
        textTopInset = text.getInsets().top;
        Font viewFont = getFont();
        boolean changed = false;
        if (viewFont == null)
          viewFont = UIManager.getFont("Label.font");
          changed = true;
        if (viewFont.getSize() > textFont.getSize())
          viewFont = viewFont.deriveFont(textFont.getSize2D());
          changed = true;
        viewFontMetrics = getFontMetrics(viewFont);
        maxNumberWidth = viewFontMetrics.stringWidth(String.valueOf(WIDTH_TEMPLATE));
        componentWidth = 2 * MARGIN + maxNumberWidth;
        if (changed)
          super.setFont(viewFont);
      public Dimension getPreferredSize()
        return new Dimension(componentWidth, text.getHeight());
      public void setFont(Font font)
        super.setFont(font);
        updateCachedMetrics();
      public void paintComponent(Graphics g)
        updateSizes();
        Rectangle clip = g.getClipBounds();
        g.setColor(getBackground());
        g.fillRect(clip.x, clip.y, clip.width, clip.height);
        g.setColor(getForeground());
        int base = clip.y - textTopInset;
        int first = sizes.getIndex(base);
        int last = sizes.getIndex(base + clip.height);
        String text = "";
        for (int i = first; i <= last; i++)
          text = String.valueOf(i+1);
          int x = MARGIN + maxNumberWidth - viewFontMetrics.stringWidth(text);
          int y = sizes.getPosition(i) + textFontAscent + textTopInset;
          g.drawString(text, x, y);
      class UpdateHandler extends ComponentAdapter
          implements PropertyChangeListener, DocumentListener
         * The text component was resized. 'Nuff said.
        public void componentResized(ComponentEvent evt)
          viewChanged(0, true);
         * A bound property was changed on the text component. Properties
         * like the font, border, and tab size affect the layout of the
         * whole document, so we invalidate all the line heights here.
        public void propertyChange(PropertyChangeEvent evt)
          Object oldValue = evt.getOldValue();
          Object newValue = evt.getNewValue();
          String propertyName = evt.getPropertyName();
          if ("document".equals(propertyName))
            if (oldValue != null && oldValue instanceof Document)
              ((Document)oldValue).removeDocumentListener(this);
            if (newValue != null && newValue instanceof Document)
              ((Document)newValue).addDocumentListener(this);
          updateCachedMetrics();
          viewChanged(0, true);
         * Text was inserted into the document.
        public void insertUpdate(DocumentEvent evt)
          update(evt);
         * Text was removed from the document.
        public void removeUpdate(DocumentEvent evt)
          update(evt);
         * Text attributes were changed.  In a source-code editor based on
         * StyledDocument, attribute changes should be applied automatically
         * in response to inserts and removals.  Since we're already
         * listening for those, this method should be redundant, but YMMV.
        public void changedUpdate(DocumentEvent evt)
    //      update(evt);
         * If the edit was confined to a single line, invalidate that
         * line's height.  Otherwise, invalidate them all.
        private void update(DocumentEvent evt)
          Element map = text.getDocument().getDefaultRootElement();
          int line = map.getElementIndex(evt.getOffset());
          DocumentEvent.ElementChange ec = evt.getChange(map);
          viewChanged(line, ec != null);
    }

  • Line number in JEditorPane

    I would like to know the line number of the current caret position in a JEditorPane. The getLineOfOffset(int offset) method in JTextArea offers exactly what I want. How come there's no method to find out about line number in JEditorPane?
    As a workaround, I copied the Swing code from the JTextArea.getLineOfOffset method and used it in my class which extends from JEditorPane. It seems to work fine, but it feels like a bad hack. Will the JTextArea code always work in JEditorPane? Any alternatives? I just think that it's tedious and inefficient to deal with StringTokenizer or manually searching for new line charactors on CaretEvent's.
        public int getLineOfOffset(int offset) throws BadLocationException {
            Document doc = getDocument();
            if (offset < 0) {
                throw new BadLocationException("Can't translate offset to line", -1);
            } else if (offset > doc.getLength()) {
                throw new BadLocationException("Can't translate offset to line", doc.getLength()+1);
            } else {
                Element map = getDocument().getDefaultRootElement();
                return map.getElementIndex(offset);
        }

    It's not a hack. Any document used with a Swing text component is supposed to have the same basic element structure, i.e., a default root element whose children represent logical lines. It's just that with some kinds of documents, like HTML, line numbers don't really mean anything. But JTextArea is hard-coded to use a PlainDocument, which means a logical line always represents a paragraph (or a line of code, or something meaningful), so it made sense for it to provide those convenience methods.

  • Help with code to print HTML in Java 5

    Hi,
    The following code works and runs successfully..
    However, the printing in Java 1.4.2_03 is better than Java 5 (latest version).
    i.e in particular the characters are not monospaced compared with compiling with Java 1.4.2_03. e.g si so ss squashed together.
    This issue does not seem to occur when running the same code in Java 1.4.2_03. (I haven't tried other 1.4.2 java versions).
    Any help would be appreciated. We really need this working under Java 5 or bust.
    Here is the complete listing ... PrintHtml.java (it uses the DocumentRenderer)
    and following this is the input file.
    import javax.swing.text.html.HTMLDocument;
    import java.net.URL;
    import java.net.MalformedURLException;
    import java.io.IOException;
    import java.io.DataInputStream;
    import java.io.InputStream;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import java.lang.reflect.*;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.Shape;
    import java.awt.print.PageFormat;
    import java.awt.print.Printable;
    import java.awt.print.PrinterException;
    import java.awt.print.PrinterJob;
    import javax.swing.JEditorPane;
    import javax.swing.text.Document;
    import javax.swing.text.PlainDocument;
    import javax.swing.text.View;
    import javax.swing.text.html.HTMLDocument;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    import java.text.ParseException;
    public class PrintHtml {
         * Utility helper to convert HTML Text to HTML Document.
         * @param baseUrl URL to be used in order
         * to resolve relative HTML references, in lieu of an
         * HTML BASE tag. May be null, if not required or HTML
         * BASE tag is to be used.
         * @see jbox.view.jfx.JboxHtmlEditor
         * @see jbox.utility.JboxPrint
         * @see jbox.utility.JboxPrintUtil
      public static HTMLDocument htmlTextToHtmlDoc(String htmlText, URL baseUrl)
              try
              //  JboxHtmlEditorKit editorKit = new JboxHtmlEditorKit();
                HTMLEditorKit editorKit = new HTMLEditorKit();
                HTMLDocument doc = (HTMLDocument)editorKit.createDefaultDocument();
                   if (baseUrl != null)
                        try
                             doc.setBase(baseUrl);
                        catch(Exception e)
                             //JboxTraceManager.trace(e);
                   StringReader reader = new StringReader(htmlText);
                   editorKit.read(reader, doc, 0);
             return doc;
              catch(Exception e)
                   //JboxTraceManager.trace(e);
                   return null;
       public static void main(String[] args) {
          System.out.println("printing...");
          HTMLDocument x = new HTMLDocument();
          DocumentRenderer invoice = new DocumentRenderer();
          //invoice.setScaleWidthToFit(false);
          String s = "";
          try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("mark.html"));
            InputStreamReader in = new InputStreamReader(bis , "ASCII");
            StringWriter sw = new StringWriter();
            while (true) {
               int datum = in.read();
               if (datum == -1) break;
               sw.write(datum);
            in.close();
            s = sw.toString();
            System.out.println("s="+s);
          catch (IOException e) {
             System.err.println(e);
          HTMLDocument htmldoc = htmlTextToHtmlDoc(s, null);
          invoice.print(htmldoc);
    // the good old infamous DocumentRenderer.
    /*  Copyright 2002
        Kei G. Gauthier
        Suite 301
        77 Winsor Street
        Ludlow, MA  01056
    class DocumentRenderer implements Printable {
    /*  DocumentRenderer prints objects of type Document. Text attributes, including
        fonts, color, and small icons, will be rendered to a printed page.
        DocumentRenderer computes line breaks, paginates, and performs other
        formatting.
        An HTMLDocument is printed by sending it as an argument to the
        print(HTMLDocument) method. A PlainDocument is printed the same way. Other
        types of documents must be sent in a JEditorPane as an argument to the
        print(JEditorPane) method. Printing Documents in this way will automatically
        display a print dialog.
        As objects which implement the Printable Interface, instances of the
        DocumentRenderer class can also be used as the argument in the setPrintable
        method of the PrinterJob class. Instead of using the print() methods
        detailed above, a programmer may gain access to the formatting capabilities
        of this class without using its print dialog by creating an instance of
        DocumentRenderer and setting the document to be printed with the
        setDocument() or setJEditorPane(). The Document may then be printed by
        setting the instance of DocumentRenderer in any PrinterJob.
      protected int currentPage = -1;               //Used to keep track of when
                                                    //the page to print changes.
      protected JEditorPane jeditorPane;            //Container to hold the
                                                    //Document. This object will
                                                    //be used to lay out the
                                                    //Document for printing.
      protected double pageEndY = 0;                //Location of the current page
                                                    //end.
      protected double pageStartY = 0;              //Location of the current page
                                                    //start.
      protected boolean scaleWidthToFit = true;     //boolean to allow control over
                                                    //whether pages too wide to fit
                                                    //on a page will be scaled.
    /*    The DocumentRenderer class uses pFormat and pJob in its methods. Note
          that pFormat is not the variable name used by the print method of the
          DocumentRenderer. Although it would always be expected to reference the
          pFormat object, the print method gets its PageFormat as an argument.
      protected PageFormat pFormat;
      protected PrinterJob pJob;
    /*  The constructor initializes the pFormat and PJob variables.
      public DocumentRenderer() {
        pFormat = new PageFormat();
        pJob = PrinterJob.getPrinterJob();
    /*  Method to get the current Document
      public Document getDocument() {
        if (jeditorPane != null) return jeditorPane.getDocument();
        else return null;
    /*  Method to get the current choice the width scaling option.
      public boolean getScaleWidthToFit() {
        return scaleWidthToFit;
    /*  pageDialog() displays a page setup dialog.
      public void pageDialog() {
        pFormat = pJob.pageDialog(pFormat);
    /*  The print method implements the Printable interface. Although Printables
        may be called to render a page more than once, each page is painted in
        order. We may, therefore, keep track of changes in the page being rendered
        by setting the currentPage variable to equal the pageIndex, and then
        comparing these variables on subsequent calls to this method. When the two
        variables match, it means that the page is being rendered for the second or
        third time. When the currentPage differs from the pageIndex, a new page is
        being requested.
        The highlights of the process used print a page are as follows:
        I.    The Graphics object is cast to a Graphics2D object to allow for
              scaling.
        II.   The JEditorPane is laid out using the width of a printable page.
              This will handle line breaks. If the JEditorPane cannot be sized at
              the width of the graphics clip, scaling will be allowed.
        III.  The root view of the JEditorPane is obtained. By examining this root
              view and all of its children, printView will be able to determine
              the location of each printable element of the document.
        IV.   If the scaleWidthToFit option is chosen, a scaling ratio is
              determined, and the graphics2D object is scaled.
        V.    The Graphics2D object is clipped to the size of the printable page.
        VI.   currentPage is checked to see if this is a new page to render. If so,
              pageStartY and pageEndY are reset.
        VII.  To match the coordinates of the printable clip of graphics2D and the
              allocation rectangle which will be used to lay out the views,
              graphics2D is translated to begin at the printable X and Y
              coordinates of the graphics clip.
        VIII. An allocation Rectangle is created to represent the layout of the
              Views.
              The Printable Interface always prints the area indexed by reference
              to the Graphics object. For instance, with a standard 8.5 x 11 inch
              page with 1 inch margins the rectangle X = 72, Y = 72, Width = 468,
              and Height = 648, the area 72, 72, 468, 648 will be painted regardless
              of which page is actually being printed.
              To align the allocation Rectangle with the graphics2D object two
              things are done. The first step is to translate the X and Y
              coordinates of the graphics2D object to begin at the X and Y
              coordinates of the printable clip, see step VII. Next, when printing
              other than the first page, the allocation rectangle must start laying
              out in coordinates represented by negative numbers. After page one,
              the beginning of the allocation is started at minus the page end of
              the prior page. This moves the part which has already been rendered to
              before the printable clip of the graphics2D object.
        X.    The printView method is called to paint the page. Its return value
              will indicate if a page has been rendered.
        Although public, print should not ordinarily be called by programs other
        than PrinterJob.
      public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) {
        double scale = 1.0;
        Graphics2D graphics2D;
        View rootView;
    //  I
        graphics2D = (Graphics2D) graphics;
        disableDoubleBuffering(jeditorPane);
    //  II
        jeditorPane.setSize((int) pageFormat.getImageableWidth(),Integer.MAX_VALUE);
        jeditorPane.validate();
    //  III
        rootView = jeditorPane.getUI().getRootView(jeditorPane);
    //  IV
        if ((scaleWidthToFit) && (jeditorPane.getMinimumSize().getWidth() >
        pageFormat.getImageableWidth())) {
          scale = pageFormat.getImageableWidth()/
          jeditorPane.getMinimumSize().getWidth();
          graphics2D.scale(scale,scale);
    //  V
        graphics2D.setClip((int) (pageFormat.getImageableX()/scale),
        (int) (pageFormat.getImageableY()/scale),
        (int) (pageFormat.getImageableWidth()/scale),
        (int) (pageFormat.getImageableHeight()/scale));
    //  VI
        if (pageIndex > currentPage) {
          currentPage = pageIndex;
          pageStartY += pageEndY;
          pageEndY = graphics2D.getClipBounds().getHeight();
    //  VII
        graphics2D.translate(graphics2D.getClipBounds().getX(),
        graphics2D.getClipBounds().getY());
    //  VIII
        Rectangle allocation = new Rectangle(0,
        (int) -pageStartY,
        (int) (jeditorPane.getMinimumSize().getWidth()),
        (int) (jeditorPane.getPreferredSize().getHeight()));
    //  X
        if (printView(graphics2D,allocation,rootView)) {
          return Printable.PAGE_EXISTS;
        else {
          pageStartY = 0;
          pageEndY = 0;
          currentPage = -1;
          return Printable.NO_SUCH_PAGE;
      /** The speed and quality of printing suffers dramatically if
       *  any of the containers have double buffering turned on.
       *  So this turns if off globally.
       *  @see enableDoubleBuffering
      public static void disableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(false);
      /** Re-enables double buffering globally. */
      public static void enableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(true);
    /*  print(HTMLDocument) is called to set an HTMLDocument for printing.
      public void print(HTMLDocument htmlDocument) {
        setDocument(htmlDocument);
        printDialog();
    /*  print(JEditorPane) prints a Document contained within a JEDitorPane.
      public void print(JEditorPane jedPane) {
        setDocument(jedPane);
        printDialog();
    /*  print(PlainDocument) is called to set a PlainDocument for printing.
      public void print(PlainDocument plainDocument) {
        setDocument(plainDocument);
        printDialog();
    /*  A protected method, printDialog(), displays the print dialog and initiates
        printing in response to user input.
      protected void printDialog() {
        if (pJob.printDialog()) {
          pJob.setPrintable(this,pFormat);
          try {
            pJob.print();
          catch (PrinterException printerException) {
            pageStartY = 0;
            pageEndY = 0;
            currentPage = -1;
            System.out.println("Error Printing Document");
    /*  printView is a recursive method which iterates through the tree structure
        of the view sent to it. If the view sent to printView is a branch view,
        that is one with children, the method calls itself on each of these
        children. If the view is a leaf view, that is a view without children which
        represents an actual piece of text to be painted, printView attempts to
        render the view to the Graphics2D object.
        I.    When any view starts after the beginning of the current printable
              page, this means that there are pages to print and the method sets
              pageExists to true.
        II.   When a leaf view is taller than the printable area of a page, it
              cannot, of course, be broken down to fit a single page. Such a View
              will be printed whenever it intersects with the Graphics2D clip.
        III.  If a leaf view intersects the printable area of the graphics clip and
              fits vertically within the printable area, it will be rendered.
        IV.   If a leaf view does not exceed the printable area of a page but does
              not fit vertically within the Graphics2D clip of the current page, the
              method records that this page should end at the start of the view.
              This information is stored in pageEndY.
      protected boolean printView(Graphics2D graphics2D, Shape allocation,
      View view) {
        boolean pageExists = false;
        Rectangle clipRectangle = graphics2D.getClipBounds();
        Shape childAllocation;
        View childView;
        if (view.getViewCount() > 0 &&
              !view.getElement().getName().equalsIgnoreCase("td")) {
          for (int i = 0; i < view.getViewCount(); i++) {
            childAllocation = view.getChildAllocation(i,allocation);
            if (childAllocation != null) {
              childView = view.getView(i);
              if (printView(graphics2D,childAllocation,childView)) {
                pageExists = true;
        } else {
    //  I
          if (allocation.getBounds().getMaxY() >= clipRectangle.getY()) {
            pageExists = true;
    //  II
            if ((allocation.getBounds().getHeight() > clipRectangle.getHeight()) &&
            (allocation.intersects(clipRectangle))) {
              view.paint(graphics2D,allocation);
            } else {
    //  III
              if (allocation.getBounds().getY() >= clipRectangle.getY()) {
                if (allocation.getBounds().getMaxY() <= clipRectangle.getMaxY()) {
                  view.paint(graphics2D,allocation);
                } else {
    //  IV
                  if (allocation.getBounds().getY() < pageEndY) {
                    pageEndY = allocation.getBounds().getY();
        return pageExists;
    /*  Method to set the content type the JEditorPane.
      protected void setContentType(String type) {
        jeditorPane.setContentType(type);
    /*  Method to set an HTMLDocument as the Document to print.
      public void setDocument(HTMLDocument htmlDocument) {
        jeditorPane = new JEditorPane();
        setDocument("text/html",htmlDocument);
    /*  Method to set the Document to print as the one contained in a JEditorPane.
        This method is useful when Java does not provide direct access to a
        particular Document type, such as a Rich Text Format document. With this
        method such a document can be sent to the DocumentRenderer class enclosed
        in a JEditorPane.
      public void setDocument(JEditorPane jedPane) {
        jeditorPane = new JEditorPane();
        setDocument(jedPane.getContentType(),jedPane.getDocument());
    /*  Method to set a PlainDocument as the Document to print.
      public void setDocument(PlainDocument plainDocument) {
        jeditorPane = new JEditorPane();
        setDocument("text/plain",plainDocument);
    /*  Method to set the content type and document of the JEditorPane.
      protected void setDocument(String type, Document document) {
        setContentType(type);
        jeditorPane.setDocument(document);
    /*  Method to set the current choice of the width scaling option.
      public void setScaleWidthToFit(boolean scaleWidth) {
        scaleWidthToFit = scaleWidth;
    }The sample input file is "mark.html":::
    <html>
    <head>
    <style type="text/css">
    <!--
    ol { list-style-type: decimal; margin-top: 10; margin-left: 50; margin-bottom: 10 }
    u { text-decoration: underline }
    s { text-decoration: line-through }
    p { font-weight: normal; font-size: medium; margin-top: 15 }
    dd p { margin-top: 0; margin-left: 40; margin-bottom: 0 }
    ol li p { margin-top: 0; margin-bottom: 0 }
    address { color: blue; font-style: italic }
    i { font-style: italic }
    h6 { font-weight: bold; font-size: xx-small; margin-top: 10; margin-bottom: 10 }
    h5 { font-weight: bold; font-size: x-small; margin-top: 10; margin-bottom: 10 }
    h4 { font-weight: bold; font-size: small; margin-top: 10; margin-bottom: 10 }
    h3 { font-weight: bold; font-size: medium; margin-top: 10; margin-bottom: 10 }
    dir li p { margin-top: 0; margin-bottom: 0 }
    h2 { font-weight: bold; font-size: large; margin-top: 10; margin-bottom: 10 }
    b { font-weight: bold }
    h1 { font-weight: bold; font-size: x-large; margin-top: 10; margin-bottom: 10 }
    a { color: blue; text-decoration: underline }
    ul li ul li ul li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    menu { margin-top: 10; margin-left: 40; margin-bottom: 10 }
    menu li p { margin-top: 0; margin-bottom: 0 }
    table table { border-color: Gray; margin-right: 0; border-style: outset; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    sup { vertical-align: sup }
    body { margin-right: 0; font-size: 14pt; font-family: SansSerif; color: black; margin-left: 0 }
    ul li ul li ul { list-style-type: square; margin-left: 25 }
    blockquote { margin-right: 35; margin-top: 5; margin-left: 35; margin-bottom: 5 }
    samp { font-size: small; font-family: Monospaced }
    cite { font-style: italic }
    sub { vertical-align: sub }
    em { font-style: italic }
    table table table { border-color: Gray; margin-right: 0; border-style: outset; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    ul li p { margin-top: 0; margin-bottom: 0 }
    ul li ul li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    var { font-weight: bold; font-style: italic }
    table { border-color: Gray; margin-right: 7; border-style: outset; margin-top: 7; margin-left: 7; margin-bottom: 17 }
    dfn { font-style: italic }
    menu li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    strong { font-weight: bold }
    ul { list-style-type: disc; margin-top: 10; margin-left: 50; margin-bottom: 10 }
    center { text-align: center }
    ul li ul { list-style-type: circle; margin-left: 25 }
    kbd { font-size: small; font-family: Monospaced }
    dir li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    th p { font-weight: bold; padding-left: 2; padding-bottom: 3; padding-right: 2; margin-top: 0; padding-top: 3 }
    ul li menu { list-style-type: circle; margin-left: 25 }
    dt { margin-top: 0; margin-bottom: 0 }
    ol li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    li p { margin-top: 0; margin-bottom: 0 }
    strike { text-decoration: line-through }
    dl { margin-top: 10; margin-left: 10; margin-bottom: 10 }
    tt { font-family: Monospaced }
    ul li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    dir { margin-top: 10; margin-left: 40; margin-bottom: 10 }
    pre p { margin-top: 0 }
    th { border-color: Gray; border-style: solid; padding-left: 3; padding-bottom: 3; padding-right: 1; padding-top: 1 }
    pre { font-family: Monospaced; margin-top: 5; margin-bottom: 5 }
    td { border-color: Gray; border-style: inset; padding-left: 3; padding-bottom: 3; padding-right: 1; padding-top: 1 }
    td p { padding-left: 2; padding-bottom: 3; padding-right: 2; margin-top: 0; padding-top: 3 }
    code { font-size: small; font-family: Monospaced }
    small { font-size: x-small }
    big { font-size: x-large }
    -->
    </style>
    </head>
    <body>
    <p style="margin-top: 0">
    </p>
    <table width="500" cellspacing="20" border="1">
    <tr>
    <td height="330" valign="top">
    <table border="0">
    <tr>
    <td>
    <font size="2">This is to certify that [[Client Name]], born
    on [[Client Date of Birth]], of [[Client Residential
                    Address]], was the holder of motor vehicle driver
    licence number [[Client Licence Number]], first issued on
    [[First Issue Date of Holding]] and expired on [[Holding
                    Expiry Date]].<br></font>
    </td>
    </tr>
    </table>
    </td>
    </tr>
    </table>
    <table width="500" border="2">
    <tr>
    <td>
    <table width="480" border="0">
    <tr>
    <td align="right">
    <font size="2"><br>
    <b>Fred Flintstone<br>Manager</b><br>Records Services Division<br>State
    Police<br>An authorised person for the purposes of the
    Road Act 1986</font>
    </td>
    </tr>
    <tr>
    <td align="left">
    <font size="2"><b>User ID: wzvqv7<br>Dated: 29 November 2006</b>
    </font>
    </td>
    </tr>
    </table>
    </td>
    </tr>
    </table>
    </body>
    </html>

    I have finally cracked it!!!!!!!!!!!!!!!!
    The issue is definitely with Java Sun. "Uneven character spacing when printing JTextComponent"
    It is raised on the http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6488219
    And currently in OPEN state, and raised on 31 Oct 2006 and mentions it was caused by fix 4352983.
    So where do we go from here. It's not good because I have tried all later version of the JVM and the issue is still there.
    Why? Because it hasn't been fixed yet. Read the bug report above, as it gives more insight -- and mentions the workaround is NOT good for existing code.
    So the way forward is to use an earlier version of the JVM 5.
    I download the JVM version 1.5.0 (starting version) and works Ok... I would probably think version prior to 4352983 would be Ok too.
    Please vote for this.... We have a workaround (use older version of the JVM).
    So I am very happy.

  • Please help me to avoid this Exception.

    I have a JTextField which will accept only non-negative integer. To get the Document roll_doc for the constructor of JTextField
    I have a class maxLengthText which will make sure that the JTextfield accepts only non-negative integer.
    I have a problem while resetting the content of the JTextField. As I have made sure that only integers are allowed in my text field.
    So while using setText(" "). The code executes the exception in my actionListener. I don't want this exceptuion to get executed when I reset the content of my JTextField using setText(String).
    Please help. Suggest any workaround for this. Thanks in advance
    The code is as follows:
    package marksheet;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.BorderFactory;
    import javax.swing.*;
    import javax.swing.text.*;
    public class SpringApplet1 extends JApplet implements ActionListener {
         JLabel l_instruction1;
         JLabel l_instruction2;
         JLabel l_instruction3;
         JLabel l_instruction4;
         JLabel l_instruction5;
         JLabel l_instruction6;
         JLabel l_instruction7;
         JLabel l_instruction8;
         JLabel l_space;
         JLabel label1;
         JLabel label2;
         JLabel label3;
         JLabel label4;
         JTextField text1;
         JTextField text2;
         JTextField text3;
         JTextField text4;
         JLabel l_name;
         JLabel l_fname;     
         JLabel l_course;
         JLabel l_specialization;
         JLabel l_batch;
         JLabel l_semester;
         JLabel l_rollno;
         JLabel l_enrolno;
         JTextField t_name;
         JTextField t_fname;
         JTextField t_rollno;
         JTextField t_enrollno;
         JComboBox cb_course;
         JComboBox cb_branch;
         JComboBox cb_batch;
         JComboBox cb_semester;
         JCheckBox c_parttime;
         JCheckBox c_fulltime;
         JButton Submit;
         JButton enterMarks;
         JButton reset;
         JTextField txtInt;
         JPanel p;
         JPanel p1;
         JPanel p2;
         JPanel p3;
         public void init () {
         l_space = new JLabel(" ");
         Document roll_doc = new maxLengthText(5); // set maximum length to 5
         Document enroll_doc = new maxLengthText(6); // set maximum length to 6
         t_rollno= new JTextField(roll_doc, "", 6);
         t_enrollno= new JTextField(enroll_doc, "", 7);
         Document name_doc = new maxLengthAlpha(15); // set maximum length to 15
         t_name = new JTextField(name_doc, "", 7);
         l_instruction1 = new JLabel("All names should be alphabets",JLabel.LEFT);
         l_instruction1.setForeground(Color.blue);
         l_instruction1.setVisible(false);
         l_instruction1.setVisible(true);
         l_instruction2 = new JLabel("Name can not be greater than 15 characters",JLabel.LEFT);
         l_instruction2.setForeground(Color.blue);
         l_instruction2.setVisible(false);
         l_instruction2.setVisible(true);
         l_instruction3 = new JLabel("Seperate firstname and last name with a 'space'",JLabel.LEFT);
         l_instruction3.setForeground(Color.blue);
         l_instruction3.setVisible(false);
         l_instruction3.setVisible(true);
         l_instruction4 = new JLabel("All marks are out of 100, Marks obtained are non-negative integers",JLabel.LEFT);
         l_instruction4.setForeground(Color.blue);
         l_instruction4.setVisible(false);
         l_instruction4.setVisible(true);
         l_instruction8 = new JLabel("Marks obtained can not be greater than 100 ",JLabel.LEFT);
         l_instruction8.setForeground(Color.blue);
         l_instruction8.setVisible(false);
         l_instruction8.setVisible(true);
         l_instruction5 = new JLabel("Roll number should be of length 5 and only numeric",JLabel.LEFT);
         l_instruction5.setForeground(Color.blue);
         l_instruction5.setVisible(false);
         l_instruction5.setVisible(true);
         l_instruction6 = new JLabel("Enrolment number should be of length 6 and only numeric",JLabel.LEFT);
         l_instruction6.setForeground(Color.blue);
         l_instruction6.setVisible(false);
         l_instruction6.setVisible(true);
         l_instruction7 = new JLabel("All fields are Mandatory",JLabel.LEFT);
         l_instruction7.setForeground(Color.blue);
         l_instruction7.setVisible(false);
         l_instruction7.setVisible(true);
         l_name = new JLabel("Name",JLabel.LEFT);
         l_name.setForeground(Color.blue);
         l_fname = new JLabel("Father's Name",JLabel.LEFT);
         l_fname.setForeground(Color.blue);
         l_course = new JLabel("Course",JLabel.LEFT);
         l_course.setForeground(Color.blue);
         l_specialization = new JLabel("Specialization",JLabel.LEFT);
         l_specialization.setForeground(Color.blue);
         l_batch = new JLabel("Batch",JLabel.LEFT);
         l_batch.setForeground(Color.blue);
         l_semester = new JLabel("Semester",JLabel.LEFT);
         l_semester.setForeground(Color.blue);
         l_rollno = new JLabel("Roll Number",JLabel.LEFT);
         l_rollno.setForeground(Color.blue);
         l_enrolno = new JLabel("Enrolment Number",JLabel.LEFT);
         l_enrolno.setForeground(Color.blue);
         //t_name = new JTextField(20);
         t_name.setEditable(true);
    //     t_name.setBackground(Color.YELLOW);
         t_fname = new JTextField(20);
         t_fname.setEditable(true);
    //     t_fname.setBackground(Color.YELLOW);
         //t_rollno = new JTextField(20);
         t_rollno.setEditable(true);
    //     t_rollno.setBackground(Color.YELLOW);
         //t_enrollno = new JTextField(20);
         t_enrollno.setEditable(true);
    //     t_enrollno.setBackground(Color.YELLOW);
         label1 = new JLabel("Data Structures",JLabel.LEFT);
         label1.setForeground(Color.blue);
         label1.setVisible(true);
         label2 = new JLabel("Compiler Design",JLabel.LEFT);
         label2.setForeground(Color.blue);
         label2.setVisible(true);
         label3 = new JLabel("Numerical Analysis",JLabel.LEFT);
         label3.setForeground(Color.blue);
         label3.setVisible(true);
         label4 = new JLabel("Discrete Matehmatics",JLabel.LEFT);
         label4.setForeground(Color.blue);
         label4.setVisible(true);
         text1 = new JTextField(20);
         text1.setEditable(false);
    //     text1.setBackground(Color.green);
         text1.setVisible(true);
         text2 = new JTextField(20);
         text2.setEditable(false);
    //     text2.setBackground(Color.green);
         text2.setVisible(true);
         text3 = new JTextField(20);
         text3.setEditable(false);
    //     text3.setBackground(Color.green);
         text3.setVisible(true);
         text4 = new JTextField(20);
         text4.setEditable(false);
    //     text4.setBackground(Color.green);
         text4.setVisible(true);
         String a_course[] =
              {" ","BE","MCA"};
         String a_branch[] =
              {" ","Computer Science","Electronics"};
         String a_batch[] =
              {" ","2000-2001","2001-2002","2002-2003","2003-2004","2004-2005"};
         String a_semester[] =
              {" ","I","II","III","IV","V","VI","VII","VIII"};
         cb_course = new JComboBox(a_course);
         cb_branch = new JComboBox(a_branch);
         cb_batch = new JComboBox(a_batch);
         cb_semester = new JComboBox(a_semester);
         c_parttime = new JCheckBox("Part Time");
         c_fulltime = new JCheckBox("Full Time");
         Submit = new JButton ("Generate Marksheet");
         Submit.setVisible(true);
    //     Submit.addActionListener(this);
         enterMarks = new JButton ("Enter Marks");
         enterMarks.setVisible(true);
    // enterMarks.addActionListener(this);
         reset= new JButton ("Reset");
         reset.setVisible(true);
    //reset.addActionListener(this);
         p = new JPanel(new GridLayout(5,2,2,2));
    p.setBorder(BorderFactory.createTitledBorder("Student Details"));
         p.add(l_name);
         p.add(t_name);
    p.add(l_fname);
         p.add(t_fname);
    p.add(l_rollno);
         p.add(t_rollno);
    p.add(l_enrolno);
         p.add(t_enrollno);
         p.add(l_space);
         p.add(l_space);
         p1 = new JPanel(new GridLayout(0,2,2,2));
         p1.setBorder(BorderFactory.createTitledBorder("Course Details"));
         p1.add(l_course);
         p1.add(cb_course);
         p1.add(l_specialization);
         p1.add(cb_branch);
         p1.add(l_batch);
         p1.add(cb_batch);
         p1.add(l_semester);
         p1.add(cb_semester);
         p1.add(c_parttime);
         p1.add(c_fulltime);
         p1.add(reset);
         p1.add(enterMarks);
         p2 = new JPanel(new GridLayout(0,2,2,2));
         p2.setBorder(BorderFactory.createTitledBorder("Marks Details"));
         p2.add(label1);
         p2.add(text1);
         p2.add(label2);
         p2.add(text2);
         p2.add(label3);
         p2.add(text3);
         p2.add(label4);
         p2.add(text4);
         p2.add(Submit);
         p2.setVisible(true);
         p3 = new JPanel(new GridLayout(0,1,2,2));
         p3.setBorder(BorderFactory.createTitledBorder("Instructions"));
         p3.add(l_instruction1);
         p3.add(l_instruction2);
         p3.add(l_instruction3);
         p3.add(l_instruction4);
         p3.add(l_instruction8);
         p3.add(l_instruction5);
         p3.add(l_instruction6);
         p3.add(l_instruction7);
         JFrame f = new JFrame("Student Marksheet System");
    f.getContentPane().setLayout(new GridLayout(2,2,3,3));
    f.getContentPane().add(p3);
         f.getContentPane().add(p);
    f.getContentPane().add(p1);
         f.getContentPane().add(p2);
         enterMarks.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                   String message = "Are you sure all information is correct";
                   String get_text1;
                   String title = "Confirmation";
                   int getcourseindex;
                   int getbranchindex;
                   int getsemesterindex;
                   int getbatchindex;
                   getcourseindex = cb_course.getSelectedIndex();
                   getbranchindex = cb_branch.getSelectedIndex();
                   getsemesterindex = cb_semester.getSelectedIndex();
                   getbatchindex = cb_branch.getSelectedIndex();
                   if (c_fulltime.isSelected() == false && c_parttime.isSelected() == false)
                        JOptionPane.showMessageDialog(null,"Atleast one mandatory field is missing","TextField",1);
                             return;
                   if(getcourseindex == 0)
                             JOptionPane.showMessageDialog(null,"Atleast one mandatory field is missing","TextField",1);
                             return;
                   if(getbranchindex == 0)
                             JOptionPane.showMessageDialog(null,"Atleast one mandatory field is missing","TextField",1);
                             return;
                   if(getsemesterindex == 0)
                             JOptionPane.showMessageDialog(null,"Atleast one mandatory field is missing","TextField",1);
                             return;
                   if(getbatchindex == 0)
                             JOptionPane.showMessageDialog(null,"Atleast one mandatory field is missing","TextField",1);
                             return;
                   int n = JOptionPane.showConfirmDialog(null,message,title, JOptionPane.YES_NO_OPTION);
                   if(n==0)
                        get_text1 = t_name.getText();
                        t_name.setEditable(false);
                        t_fname.setEditable(false);
                        t_rollno.setEditable(false);
                        t_enrollno.setEditable(false);     
                        cb_course.setEnabled(false);     
                        cb_branch.setEnabled(false);     
                        cb_batch.setEnabled(false);     
                        cb_semester.setEnabled(false);
                        reset.setEnabled(false);
         reset.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                   String message = "Are you sure to reset the fields";
                   String title = "Confirmation";
                   int n = JOptionPane.showConfirmDialog(null,message,title, JOptionPane.YES_NO_OPTION);
                   if(n==0)
                        Submit.setEnabled(true);
                        cb_course.setSelectedIndex(0);
                        cb_branch.setSelectedIndex(0);
                        cb_batch.setSelectedIndex(0);
                        cb_semester.setSelectedIndex(0);
                        t_rollno.setText("");
         Submit.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                   String message = "Confirmation will generate the marksheet";
                   String title = "Confirmation";
                   int n = JOptionPane.showConfirmDialog(null,message,title, JOptionPane.YES_NO_OPTION);
                   if(n==0)
                        Submit.setEnabled(true);
         c_parttime.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                   if (c_fulltime.isSelected() == true)
                        c_fulltime.setSelected(false);
         c_fulltime.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                   if (c_parttime.isSelected() == true)
                        c_parttime.setSelected(false);
    f.pack();
    f.setVisible(true);
         public void paint(Graphics g) {
         //Draw a Rectangle around the applet's display area.
    g.drawRect(0, 0, size().width - 1, size().height - 1);
         public void actionPerformed(ActionEvent event){
         package marksheet;
         import javax.swing.*;
         import javax.swing.text.*;
         import java.awt.*;
         public class maxLengthText extends PlainDocument
              int maxVal=0;
              public maxLengthText(int maxLength)
                   maxVal = maxLength;
              publ1ic void insertString(int offset, String str, AttributeSet a) throws BadLocationException
                   if (getLength() + str.length() > maxVal)
                        return;
                   else
                        try
                             if(!Double.isNaN(Double.parseDouble(str)))
                                  super.insertString(offset, str, a);
                        catch(Exception e)
                             JOptionPane.showMessageDialog(null,"Numbers Only","TextField",1);
                             offset=0;
         }

    When you post code, please use the [co[i]de][co[i]de] tags. There is a code button above the message textfield.

  • Weird problem in JTextFields ..!!

    Hi thr,
    It seems a buffer is held within , when a text in unicode is entered
    in the JTextFields,
    Following is the code snippet from the Class which overrides PlainDocument class
    and attached to a JTextfield
    public void insertString(int r_iOffset, String r_stNewText,
    AttributeSet r_objAttr) throws BadLocationException
         System.out.println( r_stNewText );
    int Entered = (int) r_stNewText.toCharArray()[ r_stNewText.length()-1 ] ;
    if (Entered > 255)
    r_stNewText = "";
    r_objAttr = null;
    return;
    // Further processing for ascii text
    Assuming two keyboard layouts are setup in the OS , one English and other Japanese.
    When the textfield is in focus , the OS keyboard layout is changed to japanese
    by alt+~ keys , and all the japanese keys input are succesfully blocked, but when keys "\\"
    is entered , the hidden buffered string is displayed in the Jtextfield, and all the
    keys therafter has only ascii values !! , and there by bypassing the constraint.
    When System.out is used to debug , each and every character , we can see the new string
    passed , is continually is increasing with evry new charecter , even though we make it
    as empty string.
    can somebody comment this issue ?
    cheers,
    thanks (ver much ) in advance.

    Any suggestions , at least ?

Maybe you are looking for

  • Unable to install HP Laserjet P1005 on a Windows 7 64-bit OS system

    I have attempted to install both the full package and just the driver for an HP Laserjet P1005 local printer to my personal PC which I updated the OS to MS WIndows 7, 64-bit version numerous times and I have been unsuccessful each time. On each attem

  • Right-click Google search - put in new tab or window??

    Safari has a feature that allows one to right-click on some text and then Google that text. When using that feature, it Googles the text, but the new webpage of the Google search for that text appears in the same browser window that one was originall

  • IGoogle doesn't fit in window since I updated, reset zoom didn't help

    Also Google maps is missing print button. Other sites like Wells Fargo bank don't function correctly either.

  • Re: ORA-06550 - while compiling the PL/SQL block.

    yes, there are more than one rows that is returned when i do a Select Into statement. I am trying to resolve by using a cursor C2 inside the already existing cursor C1, i will use a inner loop to get the select statement value to cursor c2 then i wil

  • Transform error in 5.0

    Hi, I migrated from 1.4.2 to 1.5 recently and found that the xslt transformation that worked fine in 1.4.2 is now broke. The following is the problematic code segment try{      System.out.println("Writing to: "+dirString+tableName+"Bean.java");