JTextField and Strings

I have a problem with using a JTextField in an IF statement. What im trying to achieve is that when the variable "TOLASuser" (JTextField) has a blank text (null) the IF statement then goes on to tell the user through a JTextArea that a null entry is not valid. The problem i'm having is that the IF statement does not read the TOLASuser.getText() as null when there is nothing entered into it, and goes straight on to the else clause.
Do I need to add anything additional to the code prior to using the IF statement. Below is my code.
This is only a small simple program if the entire source code is required I can provide it.
private void BtnValidateActionPerformed(java.awt.event.ActionEvent evt) {                                           
ConsoleView.append(TOLASuser.getText() + '\n');
String User = TOLASuser.getText();
if(User == null)
ConsoleView.setForeground(Color.red);
ConsoleView.append("You must enter your TOLAS username");
else
LblInputpath.setText("\\" + "\\adrsydtolastest\\TOL_USR_DIR\\" + TOLASuser.getText() + "\\RUN\\DTOPLAB.txt");
LblOutputpath.setText("\\" + "\\adrsydtolastest\\PAST_IN_RDY\\" + "TO891.CAF");
ConsoleView.setForeground(Color.red);
ConsoleView.append("PLEASE CHECK THE INPUT AND OUTPUT PATH BEFORE EXECUTING" + '\n');
BtnGo.setEnabled(true);
}

Thank you very much for you help. the use of a new string variable initialised as "" and the use of the equals() methods works perfectly.
below is my new code. not that you need to see it, i just want to make sure i used the CODE tags properly.
Thanks again.
private void BtnValidateActionPerformed(java.awt.event.ActionEvent evt) {
String Varify = "";
String User = TOLASuser.getText();
if(User.equals(Varify))
ConsoleView.setForeground(Color.red);
ConsoleView.append("You must enter your TOLAS username");
else
LblInputpath.setText("\\" "\\adrsydtolastest\\TOL_USR_DIR\\" TOLASuser.getText() "\\RUN\\DTOPLAB.txt");
LblOutputpath.setText("\\" "\\adrsydtolastest\\PAST_IN_RDY\\" "TO891.CAF");
ConsoleView.setForeground(Color.red);
ConsoleView.append("PLEASE CHECK THE INPUT AND OUTPUT PATH BEFORE EXECUTING" + '\n');
BtnGo.setEnabled(true);
}

Similar Messages

  • JTextField and String

    Hi,
    I have this few lines :
    JLabel LNSociete = new JLabel( "Nom ");
    LNSociete.setBounds(160,5,100,20);
    c.add(LNSociete);
    INSociete = new JTextField();
    INSociete.setBounds(210,5,150,20);
    c.add(INSociete);
    LNSociete.setLabelFor( INSociete);
    NICC = INSociete.getText();
    my NICC is define as : String NICC = new String();
    and INSociete as a JTextField
    When I'm looking in my frame I have a name in the INSociete fields.
    I WANT receive the text in my NICC I saw or I modified in my frame, but I have " " in my NICC string.
    regards
    Thierry

    As Kamran said, you will need a listener to get the text.
    You have written the code to set up the component but accessing the text must be event driven. As written, your code to get the text happens immediately after the textfield is setup so the user doesn't have time to enter the text before you try to get it out.
    When the user enters the text (and hits return, unless you are using a focuslost listener that hears when the component loses focus or a document listener that hears every keystroke) then an event is triggered that you can write a listener to handle. The listener code then can get the text into NICC.
    I suggest you have a look at the swing tutorial for text components, especially: http://java.sun.com/docs/books/tutorial/uiswing/components/simpletext.html#textfield
    has an example action listener (user has to hit return to triger an action event on a textfield).
    Hope that helps,
    Scott

  • 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 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 );

  • 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!

  • How to Plot number and string in one row (data logger counter) ?

    hi all i made data log quantity using Digital Counter via modbus to monitoring quantity and reject that has and Name Operator, Machine and Part Number.
    i have problem about plot the number & string in one row, as shown on the picture below :
    how to move that string on one row ? i attach my vi.
    Thanks~
    Attachments:
    MODBUS LIB Counter.vi ‏39 KB

    Duplicate and answered - http://forums.ni.com/t5/LabVIEW/How-to-Plot-number-and-string-in-one-row-data-logger-counter-via/m-p...

  • Difference between String=""; and String =null

    I want to know the difference especially the ADVANTAGE between the following-
    1. String s="";
    String s="ABC"
    and
    String s;
    String s="ABC";
    or String s=null;
    String s="ABC";
    2. Object anyObject;
    anyObject-new Object();
    and
    Object anyObject=null;
    anyObject=new Object();

    Tanvir007 wrote:
    I want to know the difference especially the ADVANTAGE between the following-
    1. String s="";s points to the empty string--the String object containing no characters.
    String s="ABC"s points to the String object containing the characters "ABC"
    String s; Declares String reference varialbe s. Doesn't not assign it any value. If it's a local variable, it won't have a value until you explicitly assign it. If it's a member variable, it will be given the value null when the enclosing object is created.
    String s="ABC";Already covered above.
    or String s=null;s does not point to any object.
    String s="ABC";???
    You've already asked this twice.
    Are you talking about doing
    String s = null;
    String s = "ABC";right after each other?
    You can't do that. You can only declare a variable once.
    If you mean
    String s = null;
    s = "ABC";It just does what I described above, one after the other.
    2. Object anyObject;
    anyObject-new Object();
    and
    Object anyObject=null;
    anyObject=new Object();As above: In the first case, its value is undefined until the new Object line if it's a local, or it's null if it's a member.
    As for which is better, it depends what you're doing.

  • How to Sort JTable data using Multiple fields (Date, time and string)

    I have to fill the JTable data with some date, time and string values. for example my table data looks like this:
    "1998/12/14","15:14:38","Unicorn1","row1"
    "1998/12/14","15:14:39","Unicorn2","row2"
    "1998/12/14","15:14:40","Unicorn4","row3"
    "1998/12/17","12:14:12","Unicorn4","row6"
    Now the Sorted Table should be in the following way:
    "1998/12/17","12:14:12","Unicorn4","row6"
    "1998/12/14","15:14:40","Unicorn4","row3"
    "1998/12/14","15:14:39","Unicorn2","row2"
    "1998/12/14","15:14:38","Unicorn1","row1"
    ie First Date field should be sorted, if 2 date fields are same then sort based on time. if date and time fields are same then need to be sorted on String field.
    So if any one worked on this please throw some light on how to proceed. I know how to sort based on single column.
    But now i need to sort on multiple columns.So what is code change in the Comparater class.
    Thanks in advance.. This is urgent....

    I think your Schedule objects should implement Comparable. Then you can sort your linked list using the Collections.sort() method without passing in a Comparator.class Schedule(Date date, String class) implements Comparable
      public void compareTo(Object obj)
        Schedule other = (Schedule)obj;
        return date.getTime() - other.getDate().getTime();
    }

  • In Applet  how to send an ' image' and 'string' as parameter

    Hi,
    In web application, how to use post method in applet to send an ' image' and 'string' as a parameter, I can able to send the image alone form applet to servlet.

    869665 wrote:
    Hi,
    In web application, how to use post method in applet to send an ' image' and 'string' as a parameter, I can able to send the image alone form applet to servlet.One way to do this is to convert your binary image data to base64 (convert it to plain text) and send it along with your other String parameter, delimited with a & of course.
    Edited by: maheshguruswamy on Aug 2, 2011 11:59 AM

  • 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.

Maybe you are looking for

  • Error while Transporting changes in Process chain

    Hi All, I have added a Hierarchy InfoPackage in Process chain and added this InfoObject in Save hierarchy and Attribute change Run Process types. My transport Request is showing only three entries each for save hierarchy , attribute change run and on

  • What is the use of item usage in the item category determination.

    Hi, What is the use of item usage in the item category determination. can any one please give me config setting where from actually the system will take the item usage and background functionality thanks Kuntla

  • Importing RFC from 4.5B problem

    Every one, I am trying import RFC from 4.5B, I have given all the correct details. It is giving an error "Problems to reach R/3 System" and connection to XI server is lost and I have to log-in again. Reg, -Naveen. Message was edited by: naveen chitlu

  • Safari is crashing immediately after launch

    Since the tribute to Steve's memory is integrated in the main frame, Safari crasches immediately after launch. - iMac 3.06 GHz Intel Core 2 Duo - OS X 10.7.5

  • A translation box disappeared - could it be related to Google chrome?

    Before i updated to the latesdt Firefox i had a "translation" box on my bar. Since then it has disappeared. Could it be related to Google Chrome? My operating system is Windows XP pro in Hebrew. Thank you shimsar