JTextPane, user input character in different colors

Hi,
I have a class ColorPane extends JTextPane.
I want to control the user input on the pane in the way of having a "change tracking" functionality.
So when a user inserts text, it must be colored green. If the user deletes an existing character it must be colored red instead of really deleted.
But I'm struggling with this.
e.g. I've added a keyListener: addKeyListener(new KeyAdapter() {
     public void keyPressed(KeyEvent e) {
                  switch (e.getKeyCode()) {
                       case KeyEvent.VK_BACK_SPACE:
                            if (getCaretPosition() > 0){
                                 changeColor(Color.RED);
                                 String value = getText().substring(getCaretPosition()-1, getCaretPosition());
                                 e.setKeyCode((int)value.toUpperCase().charAt(0));
                                 break;
     public void keyReleased(KeyEvent e) {
                  switch (e.getKeyCode()) {
                       case KeyEvent.VK_BACK_SPACE:
                            setCaretPosition(getCaretPosition() - 1);
                            break;
}But I can't get the deleted character to be colored red.
Also, if this coding is not the good approach, you can advice me if you want.
Best regards,
Tim
Message was edited by:
timvissers

Okay, I found out about extending DefaultStyledDocument.
But now I'm having the following problem: when removing by using the backspace button, my cursor should move to the left.
See code:
As you see, instead of removing, I put it in red. Side-effect is that the cursor is not moved when using backspace. Does someone know how to do this?
public void remove(int offset, int length) throws BadLocationException {
          // super.remove(offset, length);//DO NOT REMOVE
          doc.setCharacterAttributes(offset, length, red, true);// PUT IN RED!!
          //if backspace set caret length to the left
          //   textPane.setCaretPosition(textPane.getCaretPosition()-length);
          //else
          //   do nothing

Similar Messages

  • Displaying user input

    Hi all,
    Does anyone know how to display user input on a different panel, acitivated by a button press.
    For example in panel a, a textfield is declared to collect user input
    addForenametf = new JTextField(20);
              addForenametf.setFont(userInput);
              addForenametf.addActionListener(this);
              //postion button on grid bag
              c.gridx = 1;
              c.gridy = 1;
              addScreen.add(addForenametf, c);..then a button is pressed to take in the data (there are numerous textfields). When this happens the next screen, panel b appears and displays the values of the text field. Thus in the actionlistener...
    ...     else if(c.equals(confirmButton))
                               String forenameS = myContactMel6.getForename();
                             middle.removeAll();
                    middle.add(confirmScreen);
             }..then in the panel confirmScreen i try to display the string forenameS
         JLabel displayForename = new JLabel("");
              displayForename.setText(forenameS);
              //position button on grid bag
              c.gridx = 0;
              c.gridy = 2;
              confirmScreen.add(displayForename , c);     ...have also tried instead directly accessing the textfield as below but still doesn't print anything
         JLabel displayForename = new JLabel("");
              displayForename.setText(addForenametf.getText());
              //position button on grid bag
              c.gridx = 0;
              c.gridy = 2;
              confirmScreen.add(displayForename , c);Thank you ver much in advance!

    You need to pass in the information to your confirmation panel. One option would be to create a new instance of the confirmation panel each time the user selected the button. In this case you should pass in each value to be displayed to the constructor. Otherwise, you could have a method that accepts all the data needed and it fills the correct text fields. I am assuming that panel a has access to an instance of panel b so that it can pass the data in.

  • Redirect to different pages based on user input value

    Hello,
    Anyone please help.
    I am trying to redirect to different pages based on user inputs. I have a form in which I have one text item and a submit button. For example consider text item to be empno; So once the user enters a empno and hits submit button; I need to redirect to different pages based on this job.
    For Ex: if user inputs empno whose job is 'ANALYST' then redirect to page 1
    if user inputs empno whose job is 'MANAGER' then redirect to page 10
    For this scenario. i wrote a pl/sql process for the submit button; but no luck -- its not at all redirecting instead its in the same page. Below is the process.
    declare
    v_job varchar2(20);
    begin
    select job into v_job from emp where empno = :P9_EMPNO_R;
    if v_job = 'ANALYST' then
    OWA_UTIL.REDIRECT_URL('f?p=&APP_ID.:1:&SESSION.::&DEBUG.::', TRUE);
    end if;
    if v_job = 'MANAGER' then
    OWA_UTIL.REDIRECT_URL('f?p=&APP_ID.:10:&SESSION.::&DEBUG.::', TRUE);
    end if;
    end;Please help. I am using Oracle APEX version 4.2 and database Oracle 11g R2
    Thanks,
    Orton

    orton607 wrote:
    Hello,
    Anyone please help.
    I am trying to redirect to different pages based on user inputs. I have a form in which I have one text item and a submit button. For example consider text item to be empno; So once the user enters a empno and hits submit button; I need to redirect to different pages based on this job.
    For Ex: if user inputs empno whose job is 'ANALYST' then redirect to page 1
    if user inputs empno whose job is 'MANAGER' then redirect to page 10
    For this scenario. i wrote a pl/sql process for the submit button; but no luck -- its not at all redirecting instead its in the same page. Below is the process.
    declare
    v_job varchar2(20);
    begin
    select job into v_job from emp where empno = :P9_EMPNO_R;
    if v_job = 'ANALYST' then
    OWA_UTIL.REDIRECT_URL('f?p=&APP_ID.:1:&SESSION.::&DEBUG.::', TRUE);
    end if;
    if v_job = 'MANAGER' then
    OWA_UTIL.REDIRECT_URL('f?p=&APP_ID.:10:&SESSION.::&DEBUG.::', TRUE);
    end if;
    end;Please help. I am using Oracle APEX version 4.2 and database Oracle 11g R2
    Thanks,
    OrtonI have a similar scenario in my application and this is how I handle it.
    1. Create a page item on the page, say Px_PAGE_NUM
    2. Create a "On Submit - After Computations and Validations" page process to set the above page item. In your case, you can use the same logic that you have already in place (except the call to OWA_UTIL.REDIRECT_URL) :
    declare
    v_job varchar2(20);
    begin
    select job into v_job from emp where empno = :P9_EMPNO_R;
    if v_job = 'ANALYST' then
       :Px_PAGE_NUM := '1';
    end if;
    if v_job = 'MANAGER' then
       :Px_PAGE_NUM := '10';
    end if;
    end;3. Create a "On Submit: After processing" branch. Specify the "Target Type" as "Page in the application" and "Page Number" as &Px_PAGE_NUM. (with the dot).
    I hope the above helps.
    BTW, the following thread in the forum related to OWA_UTIL.REDIRECT_URL might help:
    issue OWA_UTIL.REDIRECT_URL with APEX 4.1.1

  • How to set input ready query cell is different color?

    Dear All
      Hi, everyone, hereby i have a IP question.
      i would like to know, how to set the input ready query's cell different color between those cell which is unable to change value one in workbook..?
    Example :
      For my workbook which have a input ready query,
      i have 4 rows for my input ready query report.
      For the first row which is not input ready cell and unable to change any value for the cell, then following rows's cell can be change value,
      so, i would like to make first row's color cell different with following row's cell.
      In additional, all value of cell is initial zero.
      therefore, is there any mehtod to make different color between able cell and unable cell?
    Thanks a million.
    Regards,
    WenLong.

    Cells in the input ready query result have different styles given by SAP. All rows will have one style, column headings will have one style whereas input ready cells will have one style. If you are in Excel 2003, put cursor in the input ready cell, goto format -> style, you can see one BeX style attached to that cell, apply watever color you want for that style, save the workbook. If you do this for one cell, it will be applied to all the input ready cells by default. In the same way you can give different color to the non input ready cell styles. In Excel 2007, Cell styles are available in Home -> Cell styles. Here you can see all Bex related styles.

  • Typewriter properties set to a different color per user.

    In Std 9 each user can set the properties of the typewriter and arrows etc to a different color.
    This feature appears to be gone in Std XI.
    I am looking for a work around or how to set it up.

    Well, it certainly doesn't appear to be straightfoward in version XI. What I did was use the Add Text Comment (formerly the Typewriter tool) annotation and then set the color/font/size. Next, I had to open the Comments List, select the annotation, and right-click to select the Properties. In the Properties dialog select "Make Properties Default".

  • Different color for JTextPane rows

    Hi!
    Do you know if it's possible to write rows in different colors in a JTextPane or it writes in ForeGround color every row ...
    Thanks!

    You can change colors in a JTextPane by getting the underlying Document and make modifications to it. Here is an example of how to change the current print color:   Document doc = textPane.getDocument();
       MutableAttributeSet attr = new SimpleAttributeSet();
       StyleConstants.setForeground(attr, newColor);
       doc.setCharacterAttributes(attr);

  • Draw a string with one character in a different color

    This problem sounds trivially simple, but I don't have a clue on how to implement it.
    What I'm basically trying to do, is use Graphics2D.drawString() to draw a string...but I want one letter to be in a different color. Guessing from the API this could be possible with an AttributedCharacterIterator, but I don't know how to set 'color' as one of the attributes.
    Does anyone with knowledge of Java 2D havy any solution for this?

    keeskist wrote:
    This problem sounds trivially simple, but I don't have a clue on how to implement it.
    What I'm basically trying to do, is use Graphics2D.drawString() to draw a string...but I want one letter to be in a different color. Guessing from the API this could be possible with an AttributedCharacterIterator, but I don't know how to set 'color' as one of the attributes.
    Does anyone with knowledge of Java 2D havy any solution for this?Here's an example using AttributedString/AttributedCharacterIterator:
    import java.awt.*;
    import java.awt.font.TextAttribute;
    import java.text.AttributedString;
    import javax.swing.*;
    public class AttributedCharacterIteratorDemo extends JFrame {
         public AttributedCharacterIteratorDemo() {
              AttributedString as = new AttributedString("Hello, world!");
              as.addAttribute(TextAttribute.FOREGROUND, Color.RED, 2, 3);
              JPanel cp = new ACRPanel(as);
              cp.setPreferredSize(new Dimension(300,300));
              setContentPane(cp);
              setTitle("AttributedCharacterIterator Demo");
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              pack();
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        new AttributedCharacterIteratorDemo().setVisible(true);
         private class ACRPanel extends JPanel {
              private AttributedString as;
              public ACRPanel(AttributedString as) {
                   this.as = as;
              protected void paintComponent(Graphics g) {
                   g.drawString(as.getIterator(), 40,40);
    }

  • How to make partial text in JTextField in different color

    I have a JTextField for user input but need to initially display something in one color and whatever user types in will be appended to this initial text with different color. I appreciate any help.

    you need a component that can be set up for styled text
    like JTextPane possibly or like that.
    There is a styled text example in demos i think
    and possibly this will help
    http://java.sun.com/docs/books/tutorial/uiswing/components/text.html

  • Changing the text in each dataGrid row to a different color

    Okay I am going to try and be as clear as possible with this,
    so bare with me.
    What I am trying to do is make it so that when my
    arraycollection objects that I have retrieved from a web service
    are loaded in (by using the "dataProvider" attribute) my dataGrid
    that some sort of code will take place changing the color of each
    line of text (all the objects stored in the array collection are
    string types) and display each rows text in a different color.
    Now after looking into it, it seems the only way to alter the
    color of the text is to use some sort of style or format but it
    seems it only effects text in a "textArea, textField, textInput"
    etc... SOOO I figured why not create a itemRenderer that contains
    one of those and put it into the dataGrid... Which I did and still
    can't figure out a way to make it so you can dynamically alter the
    color based on a set of rbg values stored in a array the same size
    as the rowCount of the datagrid.
    so I am rather stumpped in what to do.. I DON'T want to
    change the background color of each row, so alternatingItemColor is
    out of the question, I just want the text displayed in each row to
    be a different color.... And I want all this color changing to
    happen either before the data is inputted into the dataGrid
    (manipulating the arraycollection some how..) or when its all
    already in there, it all needs to happen in code no user
    interaction.
    I was thinking perhaps maybe I could create a item Renderer
    object that contains the compenent (the textArea in it) and just
    make a array of item Renderer objects and pass those into the
    dataGrid, but I don't think that is possible.
    ANY IDEAS AT ALL!! On how to change the color of the text in
    each row of the datagrid to a different color would be a HUGE,
    HUGE!!! help. Or any info on how to setup a datagrid listener that
    listens for when a object (a row) from the arraycollection is added
    to the datagrid... Perhaps I could use that info some how to my
    advantage.
    email me, if you like I don't care I just need a answer to
    this its driving me crazy! I can change the background row color
    based on a array of rgb values but I can't change the color of the
    item in that row based on array of rgb values, ARG!
    [email protected]
    thanx in advanced.

    <mx:itemRenderer>
    <mx:Component>
    <mx:Label color = "red" />
    </mx:Component>
    </mx:itemRenderer>
    want to make it so I can change the color of the label on the
    dynamically by calling some sort of method I have created.. is that
    possible? if so coudl you please give a example, thanx!

  • Showing user input in a JFrame

    i need to be able to take user-given values and display them in a JFrame. i'm testing the input of a sudoku puzzle. i have a sudokuComponent and a sudokuViewer.
    i'm confused as to where to place my code that will do the process of taking user input (via Scanner class) and testing it for certain conditions.
    i dont think figuring out the testing conditions should be hard, i'm just having trouble with getting the input read in correctly and a way of getting it displayed on the JFrame which displays the sudoku puzzle with the values so far.
    i was given a tip that said i needed to use the method repaint() of JFrame to see the updates.
    SUDOKUCOMPONENT
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.geom.Line2D;
    import javax.swing.JPanel;
    import javax.swing.JComponent;
    import java.util.Scanner;
    public class SudokuComponent extends JComponent
         public void paintComponent(Graphics g)
              //recover graphics2s
              Graphics2D g2 = (Graphics2D) g;
              //Construct the Sudoku square
              Rectangle box = new Rectangle(20, 20, 270, 270);
              g2.draw(box);
              g2.draw(new Line2D.Double(20, 110, 290, 110)); //horizontal
              g2.draw(new Line2D.Double(20, 200, 290, 200));
              g2.draw(new Line2D.Double(110, 20, 110, 290)); //vertical
              g2.draw(new Line2D.Double(200, 20, 200, 290));
    }SUDOKUVIEWER
    import javax.swing.JFrame;
    import java.util.Scanner;
    public class SudokuViewer
       public static void main(String[] args)
          JFrame frame = new JFrame();
          final int FRAME_WIDTH = 350;
          final int FRAME_HEIGHT = 350;
          frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
          frame.setTitle("Sudoku Viewer");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          SudokuComponent component = new SudokuComponent();
          frame.add(component);
          frame.setVisible(true);
    }

    I have improved your application to show how it can be programmed.
    For more information you can see about
    KeyListener:
    http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html
    MouseListener:
    http://java.sun.com/docs/books/tutorial/uiswing/events/mouselistener.html
    and of course use repaint() when you want to update your component
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.geom.Line2D;
    import java.util.LinkedList;
    import java.util.List;
    import javax.swing.JComponent;
    public class SudokuComponent extends JComponent {
        SudokuElement currentElement = new SudokuElement();
        List<SudokuElement> elementList = new LinkedList<SudokuElement>();
        public SudokuComponent(){
            addMouseListener(new MyMouseListener());
            setFocusable(true);
            addKeyListener(new MyKeyListener());
        public void paintComponent(Graphics g) {
            //public void paint(Graphics g) {
            //recover graphics2s
            Graphics2D g2 = (Graphics2D) g;
            //Construct the Sudoku square
            Rectangle box = new Rectangle(20, 20, 270, 270);
            g2.draw(box);
            g2.draw(new Line2D.Double(20, 110, 290, 110)); //horizontal
            g2.draw(new Line2D.Double(20, 200, 290, 200));
            g2.draw(new Line2D.Double(110, 20, 110, 290)); //vertical
            g2.draw(new Line2D.Double(200, 20, 200, 290));
            // show place where user can type a digit
            g2.draw(new Line2D.Double(currentElement.x - 10, currentElement.y, currentElement.x + 10, currentElement.y));
            // show all typed digits
            for(SudokuElement elem : elementList ){
               g2.drawString(elem.digit + "", elem.x, elem.y);
        class SudokuElement {
            int digit;
            int x;
            int y;
            SudokuElement getCopy(){
                SudokuElement elem = new SudokuElement();
                elem.x = x;
                elem.y = y;
                elem.digit= digit;
                return elem;
        class MyMouseListener extends MouseAdapter {
            public void mouseClicked(MouseEvent e) {
                System.out.println("mouse clicked: x = "  + e.getX() + " y = " + e.getY());
                currentElement.x = e.getX();  // It is better to use local coordinats 0 .. 9
                currentElement.y = e.getY();
                repaint(); 
        class MyKeyListener extends KeyAdapter {
            public void keyTyped(KeyEvent e) {
                char ch = e.getKeyChar();
                System.out.println("char typed= " + ch);
                if( Character.isDigit(ch) ){  // Filter only digits
                    currentElement.digit = Character.digit(ch, 10);
                    elementList.add(currentElement.getCopy());
                    repaint();
    }

  • How to Create Excel File in Background processing with different colors

    HI All
    I am trying to create Excel file in background & send it to user through e-mail, this i could acheive using fucntion module SO_DOCUMENT_SEND_API1, but here my requirement is i want to put different colors to columns of excel & this should happen in Background processing,
    Initially i completed above requirement by using HTML type of document with attachment type 'ALI'  & formatted output using write statement & used colors, after that i took this o/p using save_list function module & then table compress...etc.
    but i don't know how to achieve same if we need o/p in excel as size of object of excel file is less than that of HTML
    I am thankfull to everybody who will help me.
    Regards
    Lokesh

    Lokesh,
    Iam also trying to populate my text file with colors as an attachment . If you know this please let me know.

  • DUAL MONITOR BUG: One Picture – One Monitor – Different Colors!

    There have been several threads discussing that Photoshop CS4 and OS 10.6. show wrong colors in dual monitor setups.
    The first one to prove this with a screen capture was jb510-LJ0JJQ in August 2009: http://forums.adobe.com/message/2207312#2207312
    Eight months and three OS updates later the problem is still there and makes professional work with more than one monitor a nuisance.
    Here's another actual example: A picture and its 100% identical copy showing different colors on one screen!
    Here's how to repeat it – try this at home ;-)
    1) In the finder make a copy of a rgb picture.
    2) Open one of the two identical pics in photoshop.
    3) Drag it to the other monitor.
    When releasing the mouse button you may see the bug already: the colors will "switch".
    4) To verify this go to system presets - monitors - and change the primary monitor (by dragging the menu bar to the other)
    5) Now open the identical copy you made in step 1) and see the difference!
    Here's a synopsis of suggested workarounds:
    1) disable open GL (which seem to makes no difference on my setup)
    2) click "desaturate monitor colors" but set desaturation to 0 (which prevents visual switching in step 3) (only if openGL is ON) but also leads to a wrong display in step 4+5
    3) make the hardware calibrated monitor your default monitor and strictly avoid changes or dragging pics to the other monitor (which seems to be the only reliable method)
    4) some guys even force both monitors to use the profile of their hardware-calibrated monitor (using color sync) to make sure they see what they should see on at least that one monitor. What a stone-age workaround for the the world's leading imaging program!
    Considering that reliable colors in professional (=multi monitor) settings should be the most basic function of photoshop this mayor malfunction should be solved with CS5! Otherwise we might have to live with it for some more years...
    Have Adobe and Apple realized this bug and on their agenda? Will it be gone with OS 10.6.3? Can anyone explain the reasons for this bad bug? Is there a "officially" recommended workaround?
    Thanks, regards,
    Eric

    There have been several threads dealing with this malfunction. But most faded out in silence or acceptance of the workarounds.
    http://forums.adobe.com/message/2207312#2207312
    http://forums.adobe.com/thread/521483
    http://forums.adobe.com/message/2272192#2272192
    http://forums.adobe.com/thread/311761?start=0&tstart=0
    http://forums.adobe.com/thread/618927?tstart=60
    http://forums.adobe.com/thread/603992?tstart=90
    http://www.wetcanvas.com/forums/showthread.php?t=552977
    http://www.hilfdirselbst.ch/gforum/gforum.cgi?post=368889?search_string=zwei%20monitor#368 889
    But man, this is no minor bug! Consistent colors are the by far most important basic function of photoshop. If you cannot rely on the colors in photoshop you can as well use "Preview" and "Word" for print production ;-)
    Carson, how did Apple react to your complaint? What do you mean with "they don't get it". Do they not see it? Or can't they get it right?
    Shall we open a thread at apple forums to point out that it's not the problem of a single user?

  • How to configure the schema name dynamically based on user input.

    configure the schema name dynamically based on user input.
    For ex:
    We have two schemas:
    Schema1  - base schema having 15 tables.
    Schema2 -  tables which is specific to modules. Having only 10 tables which is also available in Schema1
    Login to application using Schema 1
    Access a particlular module and select the country. Here country selection is identified.
    Based on the country selection, we need to connect the schema respectively.
    If the user selects France --> It should connect Schema1
    If the user selects Germeny --> It should connect schema2.
    Used: Eclipselink

    You may want to have a different persistence unit for each country, then you just need to switch persistence units, and can put the schema in your orm.xml file.
    You may also want to investigate EclipseLink multi-tenant support,
    http://www.eclipse.org/eclipselink/documentation/2.5/jpa/extensions/a_multitenant.htm
    You can the schema in a persistence unit in code using a SessionCustomizer and the tableQualifier.

  • Help needed, Createing Dynamic User input

    Hello,
    I am attempting to create some dynamic user input by "predicting" what the user requires in a text box.
    For example if the user enters "Smi" I have a select list pop up which gives the user all options that begin with "Smi".
    I am able to achieve the popups but the interface is quite jerky and not terribly responsive I am trying to solve this by using a thread which starts and stops when new input is received but it is still not quite right.
    The program uses a Sorted TreeSet to hold the data (I thought this would give me a quick search time) and a simple interface at this stage.
    Any help would be fantastic
    Thanks in advance :P
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.text.*;
    import java.util.*;
       /** This program represents part of a larger user interface for allowing the
       user to select data from a file or database.
       <p>
       When the program starts up, it will read in data from a given file, and hold
       it in some type of container allowing rapid access.
       <p>
       The user may then type in the first few letters of the surname of a person,
       and this program should immediately present in a popup dialog the names which
       match.  The user will be able to click on one of the names in the popup and
       that will cause all data about that person to be displayed in the JTextArea
       at the bottom of the window.
       <p>
       This program requires the FormLayout.class, FormLayout$Placement.class, and
       FormLayout$Constraint.class files in the same directory
       (folder) or in its classpath.  These is provided separately.
    class PartMatch extends JFrame implements Runnable
                        /** Close down the program. */
       JButton quitbtn;
                        /** Field for the surname. */
       JTextField namefld;
                        /** Full details of the person(s). */
       JTextArea  results;
                        /** Popup dialog to display the names and addresses which
                        match the leading characters given in namefld. */
       Chooser matches;
                      /** Default background color for a window. */
       final static  Color            defBackground = new Color(0xD0C0C0);
                      /** Default foreground color for a window. */
       final static  Color            defForeground = new Color(0x000000);
                      /** Default background color for a field */
       final static  Color            fldBackground = new Color(0xFFFFFF);
                      /** Default background color for a button */
       final static  Color            btnBackground = new Color(0xF0E0E0);
       final static  Color            dkBackground = new Color(0xB0A0A0);
                      /** Larger font */
       final static  Font bold = new Font("Helvetica", Font.BOLD, 30);
       TreeSet members;
       String input;
       String[] found;
       public static void main(String arg[])
          UIManager.put("TextField.background",fldBackground);
          UIManager.put("TextField.foreground",defForeground);
          UIManager.put("TextField.selectionBackground",btnBackground);
          UIManager.put("TextArea.background",fldBackground);
          UIManager.put("TextArea.foreground",defForeground);
          UIManager.put("TextArea.selectionBackground",btnBackground);
          UIManager.put("Panel.background",defBackground);
          UIManager.put("Label.background",defBackground);
          UIManager.put("Label.foreground",defForeground);
          UIManager.put("Button.background",btnBackground);
          UIManager.put("Button.foreground",defForeground);
          UIManager.put("CheckBox.background",defBackground);
          UIManager.put("ScrollBar.background",defBackground);
          UIManager.put("ScrollBar.thumb",btnBackground);
          UIManager.put("ComboBox.background",btnBackground);
          UIManager.put("ComboBox.selectionBackground",dkBackground);
          PartMatch trial = new PartMatch(arg);
       public PartMatch( String [] arg )
          super("Part Match");
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          Container cpane = getContentPane();
          FormLayout form = new FormLayout(cpane);
          JLabel lab1 = new JLabel("Fetch details") ;
          lab1.setFont( bold );
          form.setTopAnchor( lab1, 4 );
          form.setLeftAnchor( lab1, 4 );
          JLabel lab2 = new JLabel("Surname: ") ;
          form.setTopRelative( lab2, lab1, 4 );
          form.setLeftAlign( lab2, lab1 );
          namefld = new JTextField( 30 );
          form.setBottomAlign( namefld, lab2 );
          form.setLeftRelative( namefld, lab2, 4 );
          namefld.addCaretListener( new CaretListener()
             public void caretUpdate(CaretEvent e)
                 showMatches();
          quitbtn = new JButton( "Quit" );
          quitbtn.addActionListener( new ActionListener()
             public void actionPerformed(ActionEvent e)
                quitProcessing();
          form.setBottomAlign( quitbtn, namefld );
          form.setLeftRelative( quitbtn, namefld, 15 );
          results = new JTextArea( 10,50 );
          results.setEditable(false);
          JScrollPane jsp = new JScrollPane( results,
                                     JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                     JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
          form.setTopRelative( jsp, lab2, 6 );
          form.setLeftAlign( jsp, lab2 );
          form.setBottomAnchor( jsp, 5 );
          form.setRightAnchor( jsp, 5 );
          form.setRightAnchor( quitbtn, 5 );
          matches = new Chooser( this );
          //matches.setUndecorated(true);
          pack();
          setVisible(true);
          namefld.requestFocus();
          if (arg.length > 0) init(arg[0]);
          else init("triathlon.txt"); //<<<<<<<<<<<<<<<< Place the default filename here
          /** Called once only, at the end of the constructor, to read the data
            * from the membership file.
       public void init( String fname )
          members = new TreeSet();
           try {
               FileReader fr = new FileReader(new File (fname));
               Scanner scan = new Scanner(fr);
               trimember cmem;
               String cLine, eTag, memberNo, first, last, gender, yob, tel ,addr,
                       club;
               while(scan.hasNextLine())
                   cLine = scan.nextLine();
                   Scanner scan2 = new Scanner(cLine);
                   scan2.useDelimiter(";");
                   eTag = scan2.next().trim();
                   memberNo = scan2.next().trim();
                   first = scan2.next().trim();
                   last = scan2.next().trim();
                   gender = scan2.next().trim();
                   yob = scan2.next().trim();
                   tel = scan2.next().trim();
                   addr = scan2.next().trim();
                   club = scan2.next().trim();
                   cmem = new trimember(eTag, memberNo, first, last, gender, yob,
                           tel, addr, club);
                   members.add(cmem);
           catch (FileNotFoundException ex)
               results.append("Sorry can't find the input file\n");
               results.append("Please check file name and location and try again");
               ex.printStackTrace();
          /** Called every time there is a change in the contents of the text field
            * namefld.  It will first clear the text area.  It then needs to search
            * through the container of data to find all records where the surname
            * starts with the characters that have been typed.  The names and
            * addresses need to be set up as strings and placed in
            * an array of Strings.  This can be placed in the "matches" window and
            * displayed for the user, inviting one to be selected.
            * <p>
            * The performance of this is very important.  If necessary, it may be
            * necessary to run as a separate thread so that the user interface is
            * not delayed.  It is essential that the user be able to type letters at a
            * reasonable speed and not have the keystroke processing held up by
            * previous text.
       public void showMatches( )
           run();
                // First clear the text area
          //results.setText("");
                // Determine the leading characters of the surname that is wanted
                input = namefld.getText();
                // Locate the data for this name, and display each matching item
                //  in the JTextArea ...
                // Example of how to set the data in the popup dialog
          matches.list.setListData(found);
          matches.pack();   // resize the popup
                // set the location of the popup if it is not currently visible
          if ( ! matches.isVisible())
             Dimension sz = matches.getSize();
             Point mouse = getMousePosition();
             Point framepos = getLocation();
             int x=0, y=0;
             if (mouse == null)
                Point pt = results.getLocation();
                x = pt.x + 20 + framepos.x;
                y = pt.y + 20 + framepos.y;
             else
                x = mouse.x - 2 + framepos.x;
                y = mouse.y - 2 + framepos.y;
             matches.setLocation(x,y);
          matches.setVisible(true);
          namefld.requestFocus();
          /** Perform any final processing before closing down.
       public void quitProcessing( )
          // Any closing work.  Then
          System.exit(0);
        public void run()
            ArrayList<String> foundit = new ArrayList<String>();
            System.out.println(input);
            if(input != null)
            Iterator it = members.iterator();
            while(it.hasNext())
               trimember test = (trimember) it.next();
               if (test.last.startsWith(input))
                   foundit.add(test.last +", "+ test.first);
            found = new String[foundit.size()];
            for(int i=0; i<foundit.size();i++)
                found[i] = foundit.get(i);
         /** A window for displaying names and addresses from the data set which
          match the leading characters in namefld.
          <p>
          This will automatically pop down if the user moves the mouse out of the
          window.
          <p>
          It needs code added to it to respond to the user clicking on an item in
          the displayed list. */
       class Chooser extends JWindow
                /** To display a set of names and addresses that match the leading
                characters of the namefld text field. */
          public JList list = new JList();
          Chooser( JFrame parent )
             super( parent );
             Container cpane = getContentPane();
             cpane.addMouseListener( new MouseAdapter()
                public void mouseExited(MouseEvent e)
                   Chooser.this.setVisible(false);
             cpane.add("Center",list);
             list.addListSelectionListener( new ListSelectionListener()
                public void valueChanged(ListSelectionEvent e)
                   Chooser.this.setVisible(false);
                   System.out.println("ValueChanged");
                   // First clear the text area
                   results.setText("");
                   String in = (String) list.getSelectedValue();
                   System.out.println("Selected Value was : "+in);
                   String[] inlf = in.split(", ");
                   System.out.println("inlf[0]:"+inlf[0]+" inlf[1]:"+inlf[1]);
                   results.append("Surname \tFirst \teTag \tMemberNo \tSex \tYOB " +
                           "\tTel \tAddress \t\t\tClub\n");
                   Iterator it = members.iterator();
                   while(it.hasNext())
                       trimember test = (trimember) it.next();
                       if (test.last.equals(inlf[0])&&test.first.equals(inlf[1]))
                           results.append(test.toString()+"\n");
                   namefld.requestFocus();
          public class trimember implements Comparable
           String eTag;
           public String memberNo;
           public String first;
           public String last;
           String gender;
           String yob;
           String tel;
           String addr;
           String club;
           public trimember(String eT, String me, String fi, String la,
                   String ge, String yo, String te, String ad, String cl)
               eTag = eT;
               memberNo = me;
               first = fi;
               last = la;
               gender = ge;
               yob = yo;
               tel = te;
               addr = ad;
               club = cl;         
           //To String method to output string of details
           public String toString()
               return last + "\t" + first + "\t" + eTag + "\t" +
                       memberNo + "\t" + gender + "\t" + yob + "\t"+ tel + "\t" +
                       addr + "\t" + club;
           //Compare and sort on Last name
           public int compareTo(Object o)
               trimember com = (trimember) o;
               int lastCmp = last.compareTo(com.last);
               int firstCmp = first.compareTo(com.first);
               int memCmp = memberNo.compareTo(com.memberNo);
               if (lastCmp == 0 && firstCmp !=0)return firstCmp;
               else if (lastCmp==0&&firstCmp==0)return memCmp;
               else return lastCmp;
    }

    Please don't cross-post. It is considered very rude to do that here:
    http://forum.java.sun.com/thread.jspa?messageID=9953193

  • Help needed, Providing Dynamic User input

    Hello,
    I am attempting to create some dynamic user input by "predicting" what the user requires in a text box.
    For example if the user enters "Smi" I have a select list pop up which gives the user all options that begin with "Smi".
    I am able to achieve the popups but the interface is quite jerky and not terribly responsive I am trying to solve this by using a thread which starts and stops when new input is received but it is still not quite right.
    The program uses a Sorted TreeSet to hold the data (I thought this would give me a quick search time) and a simple interface at this stage.
    Any help would be fantastic
    Thanks in advance :P
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.text.*;
    import java.util.*;
       /** This program represents part of a larger user interface for allowing the
       user to select data from a file or database.
       <p>
       When the program starts up, it will read in data from a given file, and hold
       it in some type of container allowing rapid access.
       <p>
       The user may then type in the first few letters of the surname of a person,
       and this program should immediately present in a popup dialog the names which
       match.  The user will be able to click on one of the names in the popup and
       that will cause all data about that person to be displayed in the JTextArea
       at the bottom of the window.
       <p>
       This program requires the FormLayout.class, FormLayout$Placement.class, and
       FormLayout$Constraint.class files in the same directory
       (folder) or in its classpath.  These is provided separately.
    class PartMatch extends JFrame implements Runnable
                        /** Close down the program. */
       JButton quitbtn;
                        /** Field for the surname. */
       JTextField namefld;
                        /** Full details of the person(s). */
       JTextArea  results;
                        /** Popup dialog to display the names and addresses which
                        match the leading characters given in namefld. */
       Chooser matches;
                      /** Default background color for a window. */
       final static  Color            defBackground = new Color(0xD0C0C0);
                      /** Default foreground color for a window. */
       final static  Color            defForeground = new Color(0x000000);
                      /** Default background color for a field */
       final static  Color            fldBackground = new Color(0xFFFFFF);
                      /** Default background color for a button */
       final static  Color            btnBackground = new Color(0xF0E0E0);
       final static  Color            dkBackground = new Color(0xB0A0A0);
                      /** Larger font */
       final static  Font bold = new Font("Helvetica", Font.BOLD, 30);
       TreeSet members;
       String input;
       String[] found;
       public static void main(String arg[])
          UIManager.put("TextField.background",fldBackground);
          UIManager.put("TextField.foreground",defForeground);
          UIManager.put("TextField.selectionBackground",btnBackground);
          UIManager.put("TextArea.background",fldBackground);
          UIManager.put("TextArea.foreground",defForeground);
          UIManager.put("TextArea.selectionBackground",btnBackground);
          UIManager.put("Panel.background",defBackground);
          UIManager.put("Label.background",defBackground);
          UIManager.put("Label.foreground",defForeground);
          UIManager.put("Button.background",btnBackground);
          UIManager.put("Button.foreground",defForeground);
          UIManager.put("CheckBox.background",defBackground);
          UIManager.put("ScrollBar.background",defBackground);
          UIManager.put("ScrollBar.thumb",btnBackground);
          UIManager.put("ComboBox.background",btnBackground);
          UIManager.put("ComboBox.selectionBackground",dkBackground);
          PartMatch trial = new PartMatch(arg);
       public PartMatch( String [] arg )
          super("Part Match");
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          Container cpane = getContentPane();
          FormLayout form = new FormLayout(cpane);
          JLabel lab1 = new JLabel("Fetch details") ;
          lab1.setFont( bold );
          form.setTopAnchor( lab1, 4 );
          form.setLeftAnchor( lab1, 4 );
          JLabel lab2 = new JLabel("Surname: ") ;
          form.setTopRelative( lab2, lab1, 4 );
          form.setLeftAlign( lab2, lab1 );
          namefld = new JTextField( 30 );
          form.setBottomAlign( namefld, lab2 );
          form.setLeftRelative( namefld, lab2, 4 );
          namefld.addCaretListener( new CaretListener()
             public void caretUpdate(CaretEvent e)
                 showMatches();
          quitbtn = new JButton( "Quit" );
          quitbtn.addActionListener( new ActionListener()
             public void actionPerformed(ActionEvent e)
                quitProcessing();
          form.setBottomAlign( quitbtn, namefld );
          form.setLeftRelative( quitbtn, namefld, 15 );
          results = new JTextArea( 10,50 );
          results.setEditable(false);
          JScrollPane jsp = new JScrollPane( results,
                                     JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                     JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
          form.setTopRelative( jsp, lab2, 6 );
          form.setLeftAlign( jsp, lab2 );
          form.setBottomAnchor( jsp, 5 );
          form.setRightAnchor( jsp, 5 );
          form.setRightAnchor( quitbtn, 5 );
          matches = new Chooser( this );
          //matches.setUndecorated(true);
          pack();
          setVisible(true);
          namefld.requestFocus();
          if (arg.length > 0) init(arg[0]);
          else init("triathlon.txt"); //<<<<<<<<<<<<<<<< Place the default filename here
          /** Called once only, at the end of the constructor, to read the data
            * from the membership file.
       public void init( String fname )
          members = new TreeSet();
           try {
               FileReader fr = new FileReader(new File (fname));
               Scanner scan = new Scanner(fr);
               trimember cmem;
               String cLine, eTag, memberNo, first, last, gender, yob, tel ,addr,
                       club;
               while(scan.hasNextLine())
                   cLine = scan.nextLine();
                   Scanner scan2 = new Scanner(cLine);
                   scan2.useDelimiter(";");
                   eTag = scan2.next().trim();
                   memberNo = scan2.next().trim();
                   first = scan2.next().trim();
                   last = scan2.next().trim();
                   gender = scan2.next().trim();
                   yob = scan2.next().trim();
                   tel = scan2.next().trim();
                   addr = scan2.next().trim();
                   club = scan2.next().trim();
                   cmem = new trimember(eTag, memberNo, first, last, gender, yob,
                           tel, addr, club);
                   members.add(cmem);
           catch (FileNotFoundException ex)
               results.append("Sorry can't find the input file\n");
               results.append("Please check file name and location and try again");
               ex.printStackTrace();
          /** Called every time there is a change in the contents of the text field
            * namefld.  It will first clear the text area.  It then needs to search
            * through the container of data to find all records where the surname
            * starts with the characters that have been typed.  The names and
            * addresses need to be set up as strings and placed in
            * an array of Strings.  This can be placed in the "matches" window and
            * displayed for the user, inviting one to be selected.
            * <p>
            * The performance of this is very important.  If necessary, it may be
            * necessary to run as a separate thread so that the user interface is
            * not delayed.  It is essential that the user be able to type letters at a
            * reasonable speed and not have the keystroke processing held up by
            * previous text.
       public void showMatches( )
           run();
                // First clear the text area
          //results.setText("");
                // Determine the leading characters of the surname that is wanted
                input = namefld.getText();
                // Locate the data for this name, and display each matching item
                //  in the JTextArea ...
                // Example of how to set the data in the popup dialog
          matches.list.setListData(found);
          matches.pack();   // resize the popup
                // set the location of the popup if it is not currently visible
          if ( ! matches.isVisible())
             Dimension sz = matches.getSize();
             Point mouse = getMousePosition();
             Point framepos = getLocation();
             int x=0, y=0;
             if (mouse == null)
                Point pt = results.getLocation();
                x = pt.x + 20 + framepos.x;
                y = pt.y + 20 + framepos.y;
             else
                x = mouse.x - 2 + framepos.x;
                y = mouse.y - 2 + framepos.y;
             matches.setLocation(x,y);
          matches.setVisible(true);
          namefld.requestFocus();
          /** Perform any final processing before closing down.
       public void quitProcessing( )
          // Any closing work.  Then
          System.exit(0);
        public void run()
            ArrayList<String> foundit = new ArrayList<String>();
            System.out.println(input);
            if(input != null)
            Iterator it = members.iterator();
            while(it.hasNext())
               trimember test = (trimember) it.next();
               if (test.last.startsWith(input))
                   foundit.add(test.last +", "+ test.first);
            found = new String[foundit.size()];
            for(int i=0; i<foundit.size();i++)
                found[i] = foundit.get(i);
         /** A window for displaying names and addresses from the data set which
          match the leading characters in namefld.
          <p>
          This will automatically pop down if the user moves the mouse out of the
          window.
          <p>
          It needs code added to it to respond to the user clicking on an item in
          the displayed list. */
       class Chooser extends JWindow
                /** To display a set of names and addresses that match the leading
                characters of the namefld text field. */
          public JList list = new JList();
          Chooser( JFrame parent )
             super( parent );
             Container cpane = getContentPane();
             cpane.addMouseListener( new MouseAdapter()
                public void mouseExited(MouseEvent e)
                   Chooser.this.setVisible(false);
             cpane.add("Center",list);
             list.addListSelectionListener( new ListSelectionListener()
                public void valueChanged(ListSelectionEvent e)
                   Chooser.this.setVisible(false);
                   System.out.println("ValueChanged");
                   // First clear the text area
                   results.setText("");
                   String in = (String) list.getSelectedValue();
                   System.out.println("Selected Value was : "+in);
                   String[] inlf = in.split(", ");
                   System.out.println("inlf[0]:"+inlf[0]+" inlf[1]:"+inlf[1]);
                   results.append("Surname \tFirst \teTag \tMemberNo \tSex \tYOB " +
                           "\tTel \tAddress \t\t\tClub\n");
                   Iterator it = members.iterator();
                   while(it.hasNext())
                       trimember test = (trimember) it.next();
                       if (test.last.equals(inlf[0])&&test.first.equals(inlf[1]))
                           results.append(test.toString()+"\n");
                   namefld.requestFocus();
          public class trimember implements Comparable
           String eTag;
           public String memberNo;
           public String first;
           public String last;
           String gender;
           String yob;
           String tel;
           String addr;
           String club;
           public trimember(String eT, String me, String fi, String la,
                   String ge, String yo, String te, String ad, String cl)
               eTag = eT;
               memberNo = me;
               first = fi;
               last = la;
               gender = ge;
               yob = yo;
               tel = te;
               addr = ad;
               club = cl;         
           //To String method to output string of details
           public String toString()
               return last + "\t" + first + "\t" + eTag + "\t" +
                       memberNo + "\t" + gender + "\t" + yob + "\t"+ tel + "\t" +
                       addr + "\t" + club;
           //Compare and sort on Last name
           public int compareTo(Object o)
               trimember com = (trimember) o;
               int lastCmp = last.compareTo(com.last);
               int firstCmp = first.compareTo(com.first);
               int memCmp = memberNo.compareTo(com.memberNo);
               if (lastCmp == 0 && firstCmp !=0)return firstCmp;
               else if (lastCmp==0&&firstCmp==0)return memCmp;
               else return lastCmp;
    }Edited by: Roger on Nov 3, 2007 11:50 AM

    Please don't cross-post. It is considered very rude to do that here:
    http://forum.java.sun.com/thread.jspa?threadID=5233033&messageID=9953169#9953169

Maybe you are looking for

  • How to use a Itunes Library between multiple computers

    Hi all, I have never posted a question to this apple forum, so forgive me if this is the wrong place to ask. My situation is as follows: I have a Synology DS214play NAS, also attached to my network is a wired Imac (late 2013 model) running the latest

  • My I-Touch Wont Connect To The Internet ! But My Bro's Did ! Help Please

    I just bought this friggin thing a few hours ago, cause my idiot brother talked me into getting it. He successfully connected his to the internet. I just paid $230.00 for an 8gb Ipod-touch, and a warranty, and it wont connect to the internet. I put i

  • Display moving average in XY Chart

    Hello Everyone, Im trying to produce an XY Chart for Time vs Pressure. What I would like to do is also plot a moving average on the Chart. Can anyone suggest an example on how to do this? Thanks

  • J Developer

    Hi ! Am new in Java Development and using J Dev 10.1.2.0.0 Version , I am developing web pages based on Structs pages , in this i have created three JSP pages and those r working fine , My problem is that i want develop a JSP in whcih i can show head

  • Re: FI -Group Chart of Account

    Can I have ste-by-step instructions to configure Group Chart of Account in FI? Is this comes out of FI or ECCS? Thanks RJ