JTextField [] and MouseEntered

Hello
I know this type of question has been asked in the forums before, but might is kind of different...i think.
I have an array of JTextFields and i want each of there color to turn to GRAY when the mouse is on top of them.
So if mouse is on top of TextField1 then only TextField1 turns GRAY.
my Current mouseEntered() method is this
public void mouseEntered(MouseEvent me)
             for (int i=0; i < nasdaqTFs.length; i++){
            nasdaqTFs.setEditable(false);
          nasdaqTFs[i].setBackground(Color.GRAY);
This, obviously, turns ALL the TextFields to GRAY when the cursor is in the Panel. So cursor can be anywhere and they all turn GRAY.
So the question is...how do i find out when the Cursor is on the Specific TextField.

Learning from earlier today This time i did write a Short Example of what i want done.
Maybe this time i didnt do a bad job at it
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Listener extends JFrame implements MouseListener
     JTextField t;
     JTextField t1;
     public Listener ()
          super ("test");
          Container c = getContentPane();
          c.setLayout(new BorderLayout());
          t = new JTextField(4);
          c.add(t, BorderLayout.NORTH);
          t1 = new JTextField (4);
          c.add(t1, BorderLayout.SOUTH);
          addMouseListener(this);
          setVisible(true);
          setSize(300,300);
          MouseMotionListener don = new MouseMotionAdapter(){
          public void mouseEntered(MouseEvent me) {
               System.out.println("Enterd)");
             me.getComponent().setBackground(Color.GRAY);
          t.addMouseMotionListener(don);
          t1.addMouseMotionListener(don);
     public static void main (String args[])
          Listener l = new Listener ();
       public void mouseEntered(MouseEvent me)
         /*JTextField tf = (JTextField) me.getSource();
         tf.setBackground(Color.GREEN);*/
            me.getComponent().setBackground(Color.GREEN);
       public void mouseExited(MouseEvent me)
         /*JTextField tf = (JTextField) me.getSource();
         tf.setBackground(Color.white);*/
            me.getComponent().setBackground(Color.WHITE);
       public void mousePressed(MouseEvent me){}
       public void mouseReleased(MouseEvent me){}
       public void mouseClicked(MouseEvent me){}
}This GUI wont change colors of TF's either. However when i move around the GUI i see somethin Green flickering!

Similar Messages

  • Reading values from JTextField and using them?

    Hello,
    I am trying to make a login screen to connect to an oracle database. Im pretty new to creaing GUI. I need help with reading the values from the JTextField and to be able to use them for my connection. So do I need to apply a listener? How do I go about doing that in this project. Thanks for any code or advice.
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.sql.*;
    public class UserDialog
        String databaseURL;
        String driver;
        String database;
        String username;
        String password;
        String hostname;
        String port;
        UserDialog() {
            getInfo();
        static String[] ConnectOptionNames = { "Login", "Cancel" };
        static String   ConnectTitle = "Login screen";
        public void getInfo() {
            JPanel      connectionPanel;
            JLabel     databaseURLLabel = new JLabel("Database URL:   ", JLabel.LEFT);
         JTextField databaseURLField = new JTextField("");
         JLabel     driverLabel = new JLabel("Driver:   ", JLabel.LEFT);
         JTextField driverField = new JTextField("");
            JLabel     databaseLabel = new JLabel("Database:   ", JLabel.LEFT);
         JTextField databaseField = new JTextField("");
            JLabel     usernameLabel = new JLabel("User Name:   ", JLabel.LEFT);
         JTextField usernameField = new JTextField("");
            JLabel     passwordLabel = new JLabel("Password:   ", JLabel.LEFT);
         JTextField passwordField = new JPasswordField("");
            JLabel     hostnameLabel = new JLabel("Host Name:   ", JLabel.LEFT);
         JTextField hostnameField = new JTextField("");
            JLabel     portLabel = new JLabel("Port:   ", JLabel.LEFT);
         JTextField portField = new JTextField("");
         connectionPanel = new JPanel(false);
         connectionPanel.setLayout(new BoxLayout(connectionPanel,
                                  BoxLayout.X_AXIS));
         JPanel namePanel = new JPanel(false);
         namePanel.setLayout(new GridLayout(0, 1));
         namePanel.add(databaseURLLabel);
         namePanel.add(driverLabel);
            namePanel.add(databaseLabel);
            namePanel.add(usernameLabel);
            namePanel.add(passwordLabel);
            namePanel.add(hostnameLabel);
            namePanel.add(portLabel);
         JPanel fieldPanel = new JPanel(false);
         fieldPanel.setLayout(new GridLayout(0, 1));
         fieldPanel.add(databaseURLField);
            fieldPanel.add(driverField);
            fieldPanel.add(databaseField);
            fieldPanel.add(usernameField);
         fieldPanel.add(passwordField);
            fieldPanel.add(hostnameField);
            fieldPanel.add(portField);
         connectionPanel.add(namePanel);
         connectionPanel.add(fieldPanel);
            // Connect or quit
            databaseURL = databaseURLField.getText();
            driver = driverField.getText();
            database = databaseField.getText();
            username = usernameField.getText();
            password = passwordField.getText();
            hostname = hostnameField.getText();
            port = portField.getText();
            int n = JOptionPane.showOptionDialog(null, connectionPanel,
                                            ConnectTitle,
                                            JOptionPane.OK_CANCEL_OPTION,
                                            JOptionPane.PLAIN_MESSAGE,
                                            null, ConnectOptionNames,
                                            ConnectOptionNames[0]);
            if (n == 0) {
                System.out.println("Attempting login: " + username);
                String url = databaseURL+hostname+":"+port+":"+database;
             // load the JDBC driver for Oracle
             try{
                   DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                   Connection con =  DriverManager.getConnection (url, username, password);
                System.out.println("Congratulations! You are connected successfully.");
                con.close();
                System.out.println("Connection is closed successfully.");
             catch(SQLException e){
                System.out.println("Error: "+e);
            else if (n == 1)
                    System.exit(0);
        public static void main (String args []) {
             UserDialog ud = new UserDialog();
    }thanks again,
    James

    the reason why you can't get the text is because you are reading the value before some actually inserts anything in any fields.
    Here is what you need to do:
    Create a JDialog/JFrame. Create a JPanel and set that panel as contentPane (dialog.setContentPane(panel)). Insert all the components, ie JLabels and JTextFields. Add two buttons, Login and Cancel to the panel as well. Now get the username and password field values using getText() inside the ActionListener of the Login.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class LoginDialog extends JDialog
    String username, password;
      public LoginDialog( ){
        setTitle( "Login" );
        JPanel content = new JPanel(new GridLayout(0, 2) ); // as many rows, but only 2 columns.
        content.add( new JLabel( "User Name" ) );
        final JTextField nameField = new JTextField( "" );
        content.add( nameField );
        content.add( new JLabel( "Password" ) );
        final JTextField passField = new JTextField( "" );
        content.add( passField );
        JButton login = new JButton( "Login" );
        login.addActionListener( new ActionListener(){
          public void actionPerformed( ActionEvent ae ){
            username = nameField.getText();
            password = passField.getText();
            // call a method or write the code to verify the username and login here...
        content.add( login );
        JButton cancel = new JButton( "Cancel" );
        cancel.addActionListener( new ActionListener( ){
          public void actionPerformed( ActionEvent ae ){
            dispose(); // close the window or write any code that you want here.
        content.add( cancel );
        pack( ); // pack everything in the dialog for display.
        show(); // show the dialog.

  • JTextfield and JButton

    Hi all
    My problem is that i have a JTextfield that is connected to a Oracle database that allow the user to enter data in the database. I want to have a button that will allow the user to test to see whether the data entered in the textfield is valid.
    I'm not sure if i need to use sqlj or not. Any help would be gladly received.
    Thanks
    null

    Hmmm... lots and lots of ways to handle this, depending on your particular need for the particular type of 'validation'. ( More info? )
    "JTextField" is not connected to a database in the same way that the infoswing "TextFieldControl" is.. .therefore one could trap the event ActionPerformed off the JTextField and do the checks ( or use the jbutton like you suggest..but it would seem like you'd always want it checked and corrected before continuing towards the inevitable commit attempt??? ).
    You can use sqlj, or you can not use it... depends upon the way you've architected your application/environment and your needs and desires.
    Note (if you haven't already ) that you can also do a heck of a lot of validation at the entity/view object level.
    In my case ( an application ) I have a jdbc connection up at the front end for all my miscellaneous stuff, and a validate PL/SQL stored function. The nice things about using stored procedures/functions are that the validate routines can be nested for quick and easy use by triggers and stored procedures. If you put it outside the database it gets more fun should you want to get at the common validation routines from all approaches.
    Curious as to how other folk are architecting their validations....

  • JTextField and JButtons not appearing until clicked.

    I'm writing a program to refresh my CS1 java skills. For some reason when I try to add a JTextField and two JButtons to my container they don't appear until Ive clicked them.
    Actually more specifically, this only happens after a 100ms wait after setting the frame visible. Any less and the components wind up visible, but scrunched up in the top middle of my frame.
    Ive found that if I add the components before and after the wait they are visible and in the correct place, but this makes a noticeable flicker.
    I'm running windows vista if that matters.
    If someone could help me I would appreciate it.
    snippet of code:
    public scrollText()
         drawingThread.start();
         mainFrame.setSize(640,160);
         mainFrame.setContentPane(draw);
         mainPane = mainFrame.getContentPane();
         mainPane.setBackground(Color.white);
         mainFrame.setResizable(false);
         mainFrame.setVisible(true);
         try
              Thread.sleep(100);
              addInterface();
         catch(InterruptedException e){}
    public void addInterface()
         textInput.setBounds(1,103,501,31);
         play.setBounds(502,103,65,30);
         play.addActionListener(this);
         stop.setBounds(568,103,65,30);
         stop.addActionListener(this);
         mainPane.add(textInput);
         mainPane.add(play);
         mainPane.add(stop);
    }

    Postings can't be moved between forums. Now you know for the next time.
    The general form for building a GUI is
    frame.getContentPane().add( yourComponentsHere );
    frame.pack();
    frame.setVisible( true );Then all the compnoent will show up according to the rules of the layout managers used.
    However is you add components to the GUI "after" the GUI is visible then the components are not automatically painted. You need to tell the GUI to invoke the layout manager again so your code would be:
    frame.getContentPane().add( componentsToVisibleGUI );
    frame.getContentPane().validate();

  • JtextField and list of data

    Hi everyone (and sorry for my english language....).
    I've this problem:
    I've a Frame with a JtextField and a button. When I click on this button, I want to show a list of data from a database and then I must choose a value that must go to the JtextField.
    Have you an idea how I can implement this? Sorry for this generic question, but I don't know how to do..
    Thank you!

    >
    As to your question.
    I've a Frame with a JtextField and a button. When I click on this button, I want to show a list of data from a database and then I must choose a value that must go to the JtextField.
    Have you an idea how I can implement this? ..Sure, plenty of people. But they will want to know exactly what you are having trouble with. E.G.
    - Getting data from a DB.
    - Putting data into a JList.
    - Adding listeners to that JList so that choices are acted on, rather than simply high-lighted as the selection.
    - Using the event provided to the listener, to update the JTextField.
    - Adding a JTextField and JList to a JFrame using layout managers.
    If your answer is 'all of that', then I suspect they would be tempted to:
    a) Advise you to put this project aside until you have considerably more experience.
    b) Refer you to the [Java Tutorial|http://java.sun.com/docs/books/tutorial/].

  • JTextField and JTextArea don't get focus occuasionally

    I am developing a Java Swing Applet. At edit mode, JComboBox, JCheckBox, JRadioBox, and JButton work fine, but JTextField and JTextArea can't get focus occuasionally while I click them.
    Anyone has idea?
    Thanks

    Thank you Himanshu,
    but that's not exactly what my issue is. This link describes the undesired effect of ending up outisde of the player window and in the browser.
    My problem is kind of the opposite. When I launch the page in the html file I cannot use the tab key to get to any of the controls in the captivate window. I'm stuck in the browser unless I click on the captivate window. That is not acceptable if we want it accessible without using a mouse. I found a way to make it work for chrome like I stated above, but not in FF. Do you have any ideas for this?
    Thanks!
    Monique

  • JTextField and JPasswordField

    Hi!
    How do I limit the character number that can be inserted into a JtextField and JPasswordField.
    For examen is the Password can be mam 6 characters, how do I do from limit the input?
    Thanks

    The most common way to limit what is entered in a JTextField is to create your own document. See the following thread:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=414464
    Graeme

  • JTextField and TextListener

    I am using an JTextField and I want to be notified when the text there have been changed. But there is no TextListener accessible in JTextField. Do I have to modify a CaretListener ?
    many Thanks/ Sam

    I am using an JTextField and I want to be notified
    when the text there have been changed. But there is no
    TextListener accessible in JTextField. Do I have to
    modify a CaretListener ?DocumentListener.

  • JTextField and transparency

    I have a JTextField and I am trying to set it up so it is somewhat transparent.
    mTextField.setBackground(new Color(255,255,255,50));
    But what happens when i do that is this: the textfield as a text value gets the text that i have set up for one of the neighbouring components.
    I am not sure why this happens.
    Has anyone experienced this problem before? Is there a fix to it?
    I tried setting up the text using setText to an empty string but it happens agian. I dont have this problem when the transparency is Not set.
    Cheers
    Dan

    I am not sure why this happens. An opaque component is responsible for painting the entire area of the component, which basically means that the RepaintManager doesnt' have to worry about the garbage that may exist where the component is about to be repainted.
    Since you background is somewhat transparent, you can see the garbage left behind. (Don't ask me what its left behind from, thats in the details of the Swing repaint manager which I know nothing about).
    Michaels suggestion makes the component transparent which means Swing will paint the background of the components parent. However when you do this, the background of your component isn't painted.
    So heres a solution that paints the background of the parent and the child:
    JTextField textField = new JTextField("Some Text")
         protected void paintComponent(Graphics g)
              g.setColor( getBackground() );
              g.fillRect(0, 0, getSize().width, getSize().height);
              super.paintComponent( g );
    textField.setBackground(new Color(0, 255, 255, 50));
    textField.setOpaque( false );

  • Accelerators, JTextField, and focus

    I created a JMenuItem for Save. I also created an accelerator for the Save menu item.
    JMenuItem saveItem;
    JMenu fileMenu = new JMenu ("File");
    fileMenu.add (saveItem = new JMenuItem ("Save"));
    saveItem.setMnemonic ('S');
    KeyStroke cntrlS = KeyStroke.getKeyStroke(KeyEvent.VK_S,
    Event.CTRL_MASK);
    saveItem.setAccelerator (cntrlS);
    saveItem.addActionListener (new ActionListener() {
    public void actionPerformed (ActionEvent e) {
    doSaveNote();
    When the user is finished entering data into the JTextField(s), the user then either presses ctrl-S or clicks on the Save button on the menu. My code (not shown) validates data in JTextFields when the Save accelerator or button is pressed (blank field is considered invalid as well as wrong flight number). If data is invalid, then the first field with invalid data gets focus.
    If the JTextField has focus and invalid data is there, then when the user clicks the Save button the JTextField still has focus with a message letting the user know the data is invalid. However, if the user puts invalid data in the JTextField and uses the accelerator ctrl-S without tabbing out of the field first, the invalid JTextField does not get focus and no error message is presented. When using the accelerator the invalid JTextField only gets focus and prints an error message if the user tabs out of the JTextField befor pressing ctrl-S.
    I don't want to tab out of the field. Why is the behavior different between the accelerator and clicking the Save button? Any help is appreciated.

    You can request focus for another component.
    Or you could do: myTextField.setFocusable(false). But in this case you would have to make it fosucable later on if you want to use it.

  • How to for JTextField and JButton..

    How can i set the size of the JTextField and getting the words alignment to be in Center format?? Can i use JButton, click on it and key in value to be displayed in text form?

    Hi,
    you can change the alignment really simple:
    JTextField textField = new JTextField("Your Text");
    textField.setHorizontalAlignment(JTextField.LEFT);
    textField.setHorizontalAlignment(JTextField.CENTER);
    textField.setHorizontalAlignment(JTextField.RIGHT);The size can be set by
    setPrefferedSize(int w, int h)or try
    setColumns(int columns)L.P.

  • How to use the MouseAdapter and mouseEntered

    I've made panel(Jpanel) with a Label(Jlabel) wich contains an Image).
    but i want the image changes in another Image when the mouse passesover the image, without click the mouse?
    how can i get this, if i can?
    some told use the MouseAdapter anf the mouseEntered, but how
    here is the program
    public class Panel1 extends JPanel
    JLabel ImageLabel,ImageLabel3;
    ImageIcon imatge1,imatge2,imatge;
    boolean asig;
    int Ymove,Xmove;
    public Panel1()
                   imatge1 = new ImageIcon("c:/Applet/imatges/lupa.gif");
         imatge2 = new ImageIcon("c:/Applet/imatges/not.gif");
              ImageLabel = new JLabel (imatge1);
              ImageLabel.setBackground(new Color(255,219,183));
    ImageLabel.setForeground(new Color(255,219,183));
    ImageLabel.setOpaque(true);
    add(ImageLabel);
    //Add a MouseAdapter to the Jlabel and change the image in the mouseEntered method of the adapter.

    Here a simple example:
    import java.awt.*;
    import java.awt.event.*;
    class MAdapter extends Frame
         private Button b1, b2, b3;
         public MAdapter()
              addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent e)
                        dispose();
                        System.exit(0);
              setLayout(new GridLayout(3, 1, 10, 10));
              b1 = new Button("Button 1");
              b2 = new Button("Button 2");
              b3 = new Button("Button 3");
              MouseListener mListener = new MMListener();
              b1.addMouseListener(mListener);
              b2.addMouseListener(mListener);
              b3.addMouseListener(mListener);
              add(b1); add(b2); add(b3);
         class MMListener extends MouseAdapter
              public void mouseEntered(MouseEvent e)
                   Object o = e.getSource();
                   if (o == b1)
                        b1.setBackground(Color.yellow);
                   else if (o == b2)
                        b2.setBackground(Color.yellow);
                   else
                        b3.setBackground(Color.yellow);
              public void mouseExited(MouseEvent e)
                   Object o = e.getSource();
                   if (o == b1)
                        b1.setBackground(Color.LIGHT_GRAY);
                   else if (o == b2)
                        b2.setBackground(Color.LIGHT_GRAY);
                   else
                        b3.setBackground(Color.LIGHT_GRAY);
         public static void main(String args[])
              MAdapter mainFrame = new MAdapter();
              mainFrame.setSize(400, 200);
              mainFrame.setTitle("MAdapter");
              mainFrame.setBackground(Color.LIGHT_GRAY);
              mainFrame.setVisible(true);

  • JTextField and Farsi or Arabic fonts.

    Hi,
    I am trying to use Arabic or Farsi fonts for JTextField but it displays unreadable character or boxes. The program is using Ms Access is working with English fonts perfectley (The Farsi fonts like B Homa or...does not work even without using Ms Access). Here is the code, please help; thanks in advance.
    Font font1 = new Font("Lucida Sans", Font.PLAIN, 12);
    fnametxt.setFont(font1);
    fnametxt.setText(text1);

    I don't know where is the problem, when you are typing or when you whant to display and retrive it from file or db.
    Anyway, as I know for multilanguage application you should use fonts that supports all language scripts that is applied in the app.
    One way to find out what scripts is supported by fonts is goto Format in Notepad and select a font, on the dialog box there is a combo that displays all sopprted language script by the font.
    For farsi language you shuld be sure that the font supports Arabic scripts like Tahoma and Arial.

  • JTextField and EventListener

    Hi guys,
    I want to parse a string from a JTextField as soon as the user writes something. But I don't know which EventListener I have to use...
    About a fast answer I would be very happy...

    About a fast answer I would be very happy... You got a fast answer!
    Now a fast reply to thank the person for their time and effort would be appropriate.

  • JTextField and append

    hi,
    i've got a question: I'm looking a method in JTextField class similar to the append() in JTextArea.
    I need to add a new chars to the end of my text in TextField. The method setText() doesn't work - it always clear the field and set the text at the beginning of my TextField
    thanks a lot in advance
    thud
    Message was edited by:
    thud_Mike

    In the future, you can always look at the source code to see what the JTextArea append() method does and then use the same concept on JTextField.
    Document doc = textComponent.getDocument();
    doc.insertString( doc.getLength(), "whatever", null );

Maybe you are looking for

  • No SAP Datasources or SAP Toolbar in Crystal Reports 2008

    I cannot see the SAP toolbar or SAP datasources under "Create New Connection" in Crystal Reports 2008 SP1. After reading many threads on SDN and reistalling Crystal Reports 2008 SP1 and the BOBJ SAP Integration Kit many times I have not been able to

  • I need to add a skin to my .fla or .swf, how can I do this without converting?

    I have created a project using motion and sound.  I need to add a skin to it which you use to be able to do when you published it.  Now it seems the only way to do it is by exporting my file into Media encoder then convert it to a MP4 ( there is no F

  • Editing a PDF file converted to Word- please tell me how

    I converted a PDF file to Word, but I can't edit it. How do I do this?

  • Database Authenticaton

    Hi all, I got the concept of external table authentication in OBIEE but what is the use of database authentication?Is that use for identify the database ?

  • Flash player refuses to open

    I am unable to view anything that requires usage of flash player. I have checked and it is installed on my Windows 8.1 and it is enabled. But am unable to view anything that requires assistance of flash player. When attempting to use, a black screen