JTextField to String?

Hi
Can anyone tell me how i can extract the text i entered in a JTextField to a String?
I have two programs that are connected, one the driver of the other
I tried String string = jTextField.getString();
all seem fine when i print it, but when i try to access the string from the other program it gives the string a null value, can anyone help me?
Regard
Eben

Program one:
* RaceScreen.java
* Created on September 7, 2008, 11:18 AM
package cargame;
import java.awt.event.ActionListener;
* @author  DieBlouBaba
public class RaceScreen extends javax.swing.JFrame implements ActionListener {
String pa2,un2;
    /** Creates new form RaceScreen */
    public RaceScreen() {
        initComponents();
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {
        Login = new javax.swing.JButton();
        Newuser = new javax.swing.JButton();
        UserScreenHelp = new javax.swing.JButton();
        UserScreenExit = new javax.swing.JButton();
        Heading = new javax.swing.JLabel();
        setTitle("Start Page");
        setBackground(new java.awt.Color(1, 1, 1));
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        Login.setText("Log In");
        Login.addActionListener(this);
        Newuser.setText("Create New User");
        Newuser.addActionListener(this);
        UserScreenHelp.setText("Help");
        UserScreenExit.setText("Exit");
        UserScreenExit.addActionListener(this);
        Heading.setFont(new java.awt.Font("Bauhaus 93", 1, 24)); // NOI18N
        Heading.setText("Race Game");
        Heading.setDebugGraphicsOptions(javax.swing.DebugGraphics.BUFFERED_OPTION);
        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(UserScreenHelp)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 269, Short.MAX_VALUE)
                .add(UserScreenExit))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(135, 135, 135)
                .add(Heading, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(108, 108, 108))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap(76, Short.MAX_VALUE)
                .add(Login, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 111, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(Newuser)
                .add(61, 61, 61))
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(Heading, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 34, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 50, Short.MAX_VALUE)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(Newuser)
                    .add(Login))
                .add(84, 84, 84))
            .add(layout.createSequentialGroup()
                .add(168, 168, 168)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(UserScreenExit)
                    .add(UserScreenHelp)))
        pack();
    // Code for dispatching events from components to event handlers.
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        if (evt.getSource() == Login) {
            RaceScreen.this.LoginActionPerformed(evt);
        else if (evt.getSource() == Newuser) {
            RaceScreen.this.NewuserActionPerformed(evt);
        else if (evt.getSource() == UserScreenExit) {
            RaceScreen.this.UserScreenExitActionPerformed(evt);
    }// </editor-fold>                       
private void UserScreenExitActionPerformed(java.awt.event.ActionEvent evt) {                                              
System.exit(0);
private void LoginActionPerformed(java.awt.event.ActionEvent evt) {                                     
new Login().setVisible(true);
Login login = new Login();
private void NewuserActionPerformed(java.awt.event.ActionEvent evt) {                                       
new NewUser().setVisible(true);
NewUser newuser = new NewUser();// TODO add your handling code here:
    * @param args the command line arguments
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new RaceScreen().setVisible(true);
    // Variables declaration - do not modify                    
    private javax.swing.JLabel Heading;
    private javax.swing.JButton Login;
    private javax.swing.JButton Newuser;
    private javax.swing.JButton UserScreenExit;
    private javax.swing.JButton UserScreenHelp;
    // End of variables declaration                  
// Program 2
* Login.java
* Created on September 7, 2008, 11:35 AM
package cargame;
import java.awt.event.ActionListener;
import javax.swing.*;
* @author  DieBlouBaba
public class Login extends javax.swing.JFrame implements ActionListener {
    String pass2, name2;
   String un;
String pa;
      RaceScreen racesreen = new RaceScreen();
    /** Creates new form Login */  
    public Login() {
        initComponents();
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {
        Username = new javax.swing.JLabel();
        Password = new javax.swing.JLabel();
        LoginOK = new javax.swing.JButton();
        LoginCancel = new javax.swing.JButton();
        Usernamel = new javax.swing.JTextField();
        Passwordl = new javax.swing.JTextField();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Log In");
        Username.setText("Username:");
        Username.setAutoscrolls(true);
        Username.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        Password.setText("Password:");
        Password.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        LoginOK.setText("OK");
        LoginOK.addActionListener(this);
        LoginCancel.setText("Cancel");
        Usernamel.setNextFocusableComponent(Usernamel);
        Usernamel.setSelectionEnd(1);
        Usernamel.setSelectionStart(10);
        Passwordl.setSelectionEnd(1);
        Passwordl.setSelectionStart(10);
        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(Password, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE)
                    .add(Username, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(LoginOK, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 89, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(LoginCancel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)
                        .add(39, 39, 39))
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, Passwordl)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, Usernamel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 189, Short.MAX_VALUE))
                        .addContainerGap())))
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(Usernamel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(Username, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 19, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(Password, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 19, Short.MAX_VALUE)
                    .add(Passwordl, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(LoginCancel)
                    .add(LoginOK))
                .addContainerGap(20, Short.MAX_VALUE))
        pack();
    // Code for dispatching events from components to event handlers.
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        if (evt.getSource() == LoginOK) {
            Login.this.LoginOKActionPerformed(evt);
    }// </editor-fold>                       
private void LoginOKActionPerformed(java.awt.event.ActionEvent evt) {                                       
runner();
JOptionPane.showMessageDialog (null, racesreen.un2, "Database Error", JOptionPane.ERROR_MESSAGE);
     JOptionPane.showMessageDialog (null,  racesreen.pa2, "Database Error", JOptionPane.ERROR_MESSAGE);LoginCheck checking = new LoginCheck();      
LoginCheck logincheck = new LoginCheck();
logincheck.Users();
     public void runner ()
     Usernamel.select(0, 10);
    String un = new String();
    un = Usernamel.getText(); 
     Passwordl.select(0,10);
      String pa = new String();
     pa = Passwordl.getText();
public void Userlogin ()
    runner();
    // Variables declaration - do not modify                    
    private javax.swing.JButton LoginCancel;
    private javax.swing.JButton LoginOK;
    private javax.swing.JLabel Password;
    private javax.swing.JTextField Passwordl;
    private javax.swing.JLabel Username;
    private javax.swing.JTextField Usernamel;
    // End of variables declaration                  
//Program 3
package cargame;
import java.awt.Toolkit;
import java.sql.*;
import javax.swing.*;
public class LoginCheck
    int repeat = 1;
    public static int i = 1;
    public static Statement stm;
    public static ResultSet rst;
    public static Connection cnt;
    public static final String driver =
        "sun.jdbc.odbc.JdbcOdbcDriver";
    public static final String url =
        "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=";
    String path = System.getProperty ("user.dir", "") + "\\Cars.mdb";
    String tempname[] = new String [2];
    String temppass[] = new String [2];
    String usernamefromdb, passwordfromdb, namel, passl;
    // Login login = new Login();
    Login login = new Login ();
    RaceScreen racesreen = new RaceScreen ();
    int y = 0;
    int t = 0;
    public LoginCheck ()
        super ();
    //Making the connection
    @ SuppressWarnings ("static-access")
        public void makeConnection ()
        try
            Class.forName (driver);
            cnt = DriverManager.getConnection (url + path);
        catch (Exception ex)
            Toolkit q = Toolkit.getDefaultToolkit ();
            q.beep ();
            JOptionPane jop = new JOptionPane ();
            jop.showMessageDialog (null, " Cannot Connect\n", "Database Error"
                    , JOptionPane.ERROR_MESSAGE);
    //Closing the Connection
    @ SuppressWarnings ("static-access")
        public void closeConnection ()
        try
            cnt.close ();
        catch (Exception ex)
            Toolkit q = Toolkit.getDefaultToolkit ();
            q.beep ();
            JOptionPane jop = new JOptionPane ();
            jop.showMessageDialog (null, " Cannot Close\n", "Database Error"
                    , JOptionPane.ERROR_MESSAGE);
    public void Userdetails ()
        try
            stm = cnt.createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE
                    , ResultSet.CONCUR_READ_ONLY);
            rst = stm.executeQuery ("Select * FROM Users");
            while (rst.next ())
                usernamefromdb = rst.getString ("Username");
                passwordfromdb = rst.getString ("Password");
                JOptionPane.showMessageDialog (null
                        , usernamefromdb + passwordfromdb
                        , "User Logged in"
                        , JOptionPane.WARNING_MESSAGE);
            tempname [t] = usernamefromdb;
            temppass [t] = passwordfromdb;
            t = t + 1;
            for (t = 0 ; t < 2 ; t++)
                System.out.println (tempname [t] + "\n" + temppass [t]);
            System.out.print (tempname + "    " + temppass);
        catch (Exception ex)
            System.out.println (ex);
    public void Users ()
        login.Userlogin ();
        Userdetails ();
        JOptionPane.showMessageDialog (null
                , login.un + " g "
                , "User Logged in"
                , JOptionPane.WARNING_MESSAGE);
        JOptionPane.showMessageDialog (null
                , login.pa
                , "User Logged in"
                , JOptionPane.WARNING_MESSAGE);
        if ("Eben".equalsIgnoreCase ("Eben"))
            if ("Eben".equalsIgnoreCase ("Eben"))
                JOptionPane.showMessageDialog (null
                        , login.un + " has logged in"
                        , "User Logged in"
                        , JOptionPane.WARNING_MESSAGE);
            else
                JOptionPane.showMessageDialog (null
                        , "Sorry, wrong password.", "Password"
                        , JOptionPane.ERROR_MESSAGE);
                Runtime.getRuntime ().exit (0);
        else
            JOptionPane.showMessageDialog (null
                    , "Sorry, User does not exist", "User"
                    , JOptionPane.ERROR_MESSAGE);
    public static void main (String[] args)
}It's done on Netbeans 6.1, so wont work in Ready

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

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

  • JTextField(Document, string, int)

    Dear friends,
    Could you just tell me how can I fix the size of the JTextField,
    such as just accept the maximum number of digits or characters in JTextField...
    I cant create the Document....
    Could anyone give me a tips?

    I found the best way to do this is to subclass PlainDocument as follows:
    public class MyTextDoc extends PlainDocument
        int maxCharacters;
        public MyTextDoc(int maxChars) {
            maxCharacters = maxChars;
        public void insertString( int offs, String str,  AttributeSet a )
                    throws BadLocationException {
            if( (getLength() + str.length()) <= maxCharacters)
                super.insertString(offs, str, a);
            else
                Toolkit.getDefaultToolkit().beep();
    }I then use this document in the constructor for all my JTextFields.
    I'm not sure what you mean by "I cant create the Document...."
    Cheers
    Gary

  • From JTextField into string array

    hello,
    Me and my friend are currently doing a cryptography project for UNI. We are required to read in a word from the JTextField into an array. the problem is the whole word seems to be going into the array as one element. Is there any way to read in each letter in the word into a seperate element of the array??

    Well you can always read the value in the textfield, convert it to a character array and then as you transfer each character to your string array you add a blank string to it, so then it becomes a string.
    Example:
    String sentence = "hello, I am a really loooooooooong string";
    String[] stringArray = new String[sentence.length()];
    char[] charArray = sentence.toCharArray();
    for (int count = 0; count < sentence.length(); count++)
         stringArray[count] = charArray[count] + "";I hope this helps.

  • How can I set a gap in a JTextField, before the active Textfield starts?

    Hi,
    how can I set a gap in a JTextField, before the active Textfield starts?
    I'll avoid, that the input text starts immediately after the border of the JTextField.
    Btw, how can I set the height of the JTextField in a BoxLayout?
    Thx.
    Hans

    Yes, that was also my thinking, but nothing happens.
    Maybe You have an idea :-)
    Thx, Hans
    Here a part of my code:
      private JPanel createEntry(String label, JTextField jtf, String initJtf, boolean editable) {
        jtf.setColumns(15);
        if (editable) {
          jtf.setEditable(true);
          jtf.setBackground(new Color(191, 191, 255));
        else {
          jtf.setEditable(false);
          jtf.setBackground(SystemColor.control);
        jtf.setText(initJtf);
        jtf.setForeground(Color.black);
        jtf.setBorder(BorderFactory.createLoweredBevelBorder());
        jtf.setMargin(new Insets(50, 20, 50, 40));   // <-  The PROBLEM
        JPanel panel = new JPanel();
        GridLayout gl = new GridLayout(1, 2);
        gl.setHgap(1);
        panel.setLayout(gl);
        panel.add(BxpCdmUtils.Utils.createLabel(label, Color.darkGray, Font.BOLD, 11));
        panel.add(jtf);
        JPanel superpanel = new JPanel();
        superpanel.setLayout(new BoxLayout(superpanel, BoxLayout.X_AXIS));
        superpanel.add(panel);
        superpanel.add(new JLabel(" "));
        return superpanel;
      }

  • JTextField update problem when called from PropertyChangeEvent

    Hi,
    I'm trying to create forms that can be dynamically loaded with Class.forname(formName).
    Those forms should always inherit some methods that make it easy to pass data to
    them and receive data from them. The idea is that the data comes from a table which
    sends a hashmap (String column/JTextField-name + String Value pairs) with firePropertyChanged
    as soon as a new row is seleceted. The JTextFields in the form are marked with setName("FieldName") that has to correspond to the name of the columns of the table.
    My problem is that I can't update the fields in my form when I'm calling getRow(HashMap)
    from within propertyChangeEvent but that's necessary to keep the forms flexible.
    JTextFieldName.setText(newText) just won't work. But it works when I call getRow(HashMap)
    from the constructor. SwingWorker and threads to update the form didn't help.
    I don't need to call pack() / update() / repaint() on the JFrame, do I ??
    update() / validate() / repaint() etc. didn't work on the JTextField themselves.
    Below is the code for one of the test-forms (just a JPanel that is inserted in a frame)
    with all of it's methods. Does anybody have a solution to this problem ??
    Thanks for taking time for that !!
    Benjamin
    * testTable.java
    * Created on 15. April 2004, 16:12
    package viewcontrol.GUI;
    * @author gerbarmb
    import javax.swing.*;
    import java.awt.*;
    import java.beans.*;
    import java.util.*;
    public class testTable extends javax.swing.JPanel
              implements
                   java.awt.event.KeyListener,
                   java.beans.PropertyChangeListener {
          * public static void main(String[] argv) { testTable tt = new testTable();
          * JFrame jf = new JFrame(); jf.setContentPane(tt); jf.setVisible(true); }
         /** Creates new customizer testTable */
         public testTable() {
              initComponents();
              HashMap hm = new HashMap();
               * Only for debugging, to see that the method getRow() works when
               * called from the constructor.
               hm.put("ttext", "TEst");
               this.getRow(hm);
          * This method is called from within the constructor to initialize the form.
          * WARNING: Do NOT modify this code. The content of this method is always
          * regenerated by the FormEditor.
         private void initComponents() {//GEN-BEGIN:initComponents
              java.awt.GridBagConstraints gridBagConstraints;
              jLabel1 = new javax.swing.JLabel();
              textIn = new javax.swing.JTextField();
              jLabel2 = new javax.swing.JLabel();
              intIn = new javax.swing.JTextField();
              jLabel3 = new javax.swing.JLabel();
              numIn = new javax.swing.JTextField();
              jLabel4 = new javax.swing.JLabel();
              dateIn = new javax.swing.JTextField();
              jLabel5 = new javax.swing.JLabel();
              dateTimeIn = new javax.swing.JTextField();
              jLabel6 = new javax.swing.JLabel();
              jCheckBox1 = new javax.swing.JCheckBox();
              keepValues = new javax.swing.JCheckBox();
              jButton1 = new javax.swing.JButton();
              setLayout(new java.awt.GridBagLayout());
              jLabel1.setText("Text");
              add(jLabel1, new java.awt.GridBagConstraints());
              textIn.setName("ttext");
              textIn.setPreferredSize(new java.awt.Dimension(100, 21));
              textIn.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent evt) {
                        textInActionPerformed(evt);
              gridBagConstraints = new java.awt.GridBagConstraints();
              gridBagConstraints.gridwidth = 2;
              add(textIn, gridBagConstraints);
              jLabel2.setText("Integer");
              add(jLabel2, new java.awt.GridBagConstraints());
              intIn.setName("tint");
              intIn.setPreferredSize(new java.awt.Dimension(50, 21));
              add(intIn, new java.awt.GridBagConstraints());
              jLabel3.setText("Number");
              add(jLabel3, new java.awt.GridBagConstraints());
              numIn.setName("tnum");
              numIn.setPreferredSize(new java.awt.Dimension(50, 21));
              add(numIn, new java.awt.GridBagConstraints());
              jLabel4.setText("Date");
              gridBagConstraints = new java.awt.GridBagConstraints();
              gridBagConstraints.gridx = 0;
              gridBagConstraints.gridy = 1;
              add(jLabel4, gridBagConstraints);
              dateIn.setName("tdate");
              dateIn.setPreferredSize(new java.awt.Dimension(50, 21));
              gridBagConstraints = new java.awt.GridBagConstraints();
              gridBagConstraints.gridx = 1;
              gridBagConstraints.gridy = 1;
              add(dateIn, gridBagConstraints);
              jLabel5.setText("DateTime");
              gridBagConstraints = new java.awt.GridBagConstraints();
              gridBagConstraints.gridx = 2;
              gridBagConstraints.gridy = 1;
              add(jLabel5, gridBagConstraints);
              dateTimeIn.setName("tidate");
              dateTimeIn.setPreferredSize(new java.awt.Dimension(80, 21));
              gridBagConstraints = new java.awt.GridBagConstraints();
              gridBagConstraints.gridy = 1;
              add(dateTimeIn, gridBagConstraints);
              jLabel6.setText("Bit");
              gridBagConstraints = new java.awt.GridBagConstraints();
              gridBagConstraints.gridy = 1;
              add(jLabel6, gridBagConstraints);
              jCheckBox1.setName("tbit");
              gridBagConstraints = new java.awt.GridBagConstraints();
              gridBagConstraints.gridy = 1;
              add(jCheckBox1, gridBagConstraints);
              keepValues.setText("keep values");
              gridBagConstraints = new java.awt.GridBagConstraints();
              gridBagConstraints.gridx = 7;
              gridBagConstraints.gridy = 3;
              add(keepValues, gridBagConstraints);
              jButton1.setText("Send");
              jButton1.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent evt) {
                        jButton1ActionPerformed(evt);
              gridBagConstraints = new java.awt.GridBagConstraints();
              gridBagConstraints.gridx = 7;
              gridBagConstraints.gridy = 2;
              add(jButton1, gridBagConstraints);
         }//GEN-END:initComponents
         private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
              sendRow();
         }//GEN-LAST:event_jButton1ActionPerformed
         private boolean sendRow() {
              java.util.HashMap hm = new java.util.HashMap();
              Component[] cs = this.getComponents();
              for (int i = 0; i < cs.length; i++) {
                   if (((Component) cs).getName() != null) {
                        if (cs[i] instanceof JCheckBox) {
                             String value = ((JCheckBox) cs[i]).isSelected() ? "1" : "0";
                             hm.put(cs[i].getName(), value);
                        } else if (cs[i] instanceof JCheckBox) {
                             hm.put(cs[i].getName(), ((JTextField) cs[i]).getText());
              } // end for
              firePropertyChange("rowChanged", null, hm);
              return true;
         private void getRow(java.util.HashMap hm) {
              //if (! this.keepValues.isSelected()) {
              Component[] cs = this.getComponents();
              for (int i = 0; i < cs.length; i++) {
                   if (cs[i].getName() != null && hm.containsKey(cs[i].getName())) {
                        Component component = cs[i];
                        String componentName = cs[i].getName();
                        String componentValue = (String) hm.get(component.getName());
                        if (cs[i] instanceof JTextField) {
                             // output for debugging
                             System.out.println("Setting " + cs[i].getName() + " = "
                                       + componentValue);
                             ((JTextField) component).setText(componentValue);
                        } else if (cs[i] instanceof JCheckBox) {
                             // output for debugging
                             System.out.println("JCheckBox found");
                             JCheckBox cb = (JCheckBox) component;
                             boolean selected = (componentValue == null ? false : (componentValue.equals("1")
                                       ? true
                                       : false));
                             ((JCheckBox) component).setSelected(selected);
              } // end for
              /* Uncomment this code snippet to retrieve the text that has been set
              for the components (that means JTextFields)
              This is just for debugging !
              Component[] cs = this.getComponents(); for (int i = 0; i < cs.length;
              i++) { if (cs[i].getName() != null) { if (cs[i] instanceof
              JTextField) { System.out.println("Value of " +cs[i].getName() + " = " +
              ((JTextField) cs[i]).getText()); } } } // end for
         private void textInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textInActionPerformed
         }//GEN-LAST:event_textInActionPerformed
         public void keyPressed(java.awt.event.KeyEvent e) {
              if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
                   sendRow();
         public void keyReleased(java.awt.event.KeyEvent e) {
         public void keyTyped(java.awt.event.KeyEvent e) {
         public void propertyChange(java.beans.PropertyChangeEvent evt) {
              if (evt.getPropertyName().equals("newRow")) {
                   final PropertyChangeEvent finalEvt = evt;
                   Runnable makeChanges = new Runnable () {
                        public void run() {
                             getRow((java.util.HashMap) finalEvt.getNewValue());
         // Variables declaration - do not modify//GEN-BEGIN:variables
         private javax.swing.JTextField dateIn;
         private javax.swing.JTextField dateTimeIn;
         private javax.swing.JTextField intIn;
         private javax.swing.JButton jButton1;
         private javax.swing.JCheckBox jCheckBox1;
         private javax.swing.JLabel jLabel1;
         private javax.swing.JLabel jLabel2;
         private javax.swing.JLabel jLabel3;
         private javax.swing.JLabel jLabel4;
         private javax.swing.JLabel jLabel5;
         private javax.swing.JLabel jLabel6;
         private javax.swing.JCheckBox keepValues;
         private javax.swing.JTextField numIn;
         private javax.swing.JTextField textIn;
         // End of variables declaration//GEN-END:variables

    The problem of the change in the form not being comitted is that
    I forgot SwingUtilities.invokeLater(makeChanges); in the bottom
    part in public void propertyChange(java.beans.PropertyChangeEvent evt)
    after having created a new Runnable.
    Changes to the UI often have to be comitted by SwingUtitlities.invokeLater()
    though I don't know that much about Swing yet.
    Thanks to everybody who tried to solve that problem.
    Benjamin

  • Size of the JtextField

    Hi All
    I rendered a jpanel for one column of jtable. In that Jpanel i placed a JtextField . The problem is when I click that JtextField the size of the Jtextfield incress up to the size of the jtable cell.
    Please help me

    This is the Editor class
    public class PanelEditor extends AbstractCellEditor
    implements TableCellEditor {
    /** Creates a new instance of PanelEditor */
    private JPanel panel;
    protected JTextField tf;
    String txt;
    private double total;
    private com.clx.client.gui.order.CatalogView catalogView;
    public PanelEditor() {
    public Object getCellEditorValue() {
    return tf.getText();
    //Implement the one method defined by TableCellEditor.
    public Component getTableCellEditorComponent(javax.swing.JTable table, Object value,
    boolean isSelected, int row, int column) {
    tf.setBounds(10, 10, 20, 20);
    // tf.setSize(33,33);
    System.out.println(tf.getWidth());
    tf.setSize(33,33);
    txt = value.toString();
    tf.setText(txt);
    return tf;
    }

  • JtextField.setText()

    im having problem with JTextField.setText()... let say i have a vector containing multiple strings and i wanna set the text of a jtextfield with one of my vector's element i do:
    JTextField.setText((String)Vector.firstElement());
    but how come in my jtextfield the new string isnt showing... do i need to repaint my whole frame????
    thx

    You don't supply enough info to know the problem. You shouldn't have to repaint. Where is your JTextField Defined. If you defined inside a constructor or method, you can get the results you are having.

  • JTextField - inidicating already inputted spaces

    I am using a JTextField for users to input strings.
    Once captured from the JTextField, these strings will be used for find and replace operations and may contain whitespace (which is part of the string).
    During input I need the JTextField to distinguish between the blank spaces within the string and mere white space at the JTextField where no text has been entered yet.
    For example the background for the text already inputted (the string) is shaded differently to the blank space at the end of the field.
    Does anyone have any ideas how to do this?
    thanks,
    Paul Harrington

    Here's what I use, Paul. Instead of using shading, it replaces the space character with a centered dot for display purposes, and changes it back when you get the text out. It also converts TAB and LF characters, according to the policy you choose. That way, you can paste text into the field without having to worry about whether it contains those characters. Similarly, if you want to insert a TAB or LF, you can just type in the escape for it (assuming you used the ESCAPE_AND_RESTORE policy). In my search/replace dialog, I use a policy of USE_ESCAPES for the search field, and ESCAPE_AND_RESTORE for the replace field. I also have a preview field, which uses the USE_SYMBOLS policy.
    To use it, just create a new FriedlDocument with the desired policy and pass to the JTextField's constructor or its setDocument() method.
    import javax.swing.*;
    import javax.swing.text.*;
    * FriedlDocument converts SPACE, TAB and LF characters to
    * visible symbols so the contents can be edited or displayed
    * in a JTextField. If the textfield is being used for display
    * only, LFs and TABs can be converted to graphical symbols,
    * for greater readability, and those symbols will always be
    * converted back to the characters they represent on retrieval.
    * For editing, LF and TAB can be converted to their escapes
    * ("\n" and "\t") on insertion, and the user can choose whether
    * to reconvert the escapes or not.  The SPACE character will
    * always be converted to a visible symbol on insertion and
    * re-converted on retrieval.<p>
    * FriedlDocument is named after Jeffrey Friedl, author of
    * <i>Mastering Regular Expressions</i>, because it was inspired
    * by the typeface he invented for the examples in his book.
    * @author Alan Moore
    public class FriedlDocument extends PlainDocument
       * TAB and LF are converted on insertion to right-pointing
       * and down-pointing arrows, respectively, which will be
       * reconverted on retrieval.
      public static final int USE_SYMBOLS   = 0;
       * TAB and LF are converted on insertion to "\t" an "\n",
       * respectively, and are NOT reconverted on retrieval.
      public static final int USE_ESCAPES    = 1;
       * TAB and LF are converted on insertion to "\t" an "\n",
       * respectively, and reconverted on retrieval.
      public static final int ESCAPE_AND_RESTORE = 2;
      private int policy;
       * Creates a new FriedlDocument, which will use the given
       * <tt>policy</tt> when converting whitespace.
       * @param policy the converion policy; one of USE_SYMBOLS,
       *     USE_ESCAPES, or ESCAPE_AND_RESTORE
      public FriedlDocument(int policy)
        super(new StringContent());
        if (policy < 0 || policy > 2)
          throw new IllegalArgumentException(
              "Invalid conversion policy: " + policy);
        this.policy = policy;
       * Inserts some content into the document, converting
       * whitespace to visible characters according to the
       * selected policy.
      public void insertString(int offs, String str, AttributeSet a)
          throws BadLocationException
        if (str == null || str.length() == 0)
          return;
        if (policy == USE_SYMBOLS)
          str = displayWhitespace(str);
        else
          str = escapeWhitespace(str);
        super.insertString(offs, str, a);
       * Gets a sequence of text from the document, converting
       * escapes and graphical symbols to whitespace characters
       * according to the selected policy.
      public String getText(int offset, int length)
          throws BadLocationException
        /* It's possible for the returned text to be shorter than
         * the actual, displayed content. That isn't a problem,
         * though, because none of the view-related classes call
         * this method--they all use getText(int, int, Segment)
         * instead. The only exception is the insertUpdate()
         * method in PlainDocument, which we don't need anyway.
        String str = super.getText(offset, length);
        boolean restore = (policy == ESCAPE_AND_RESTORE);
        return restoreWhitespace(str, restore);
       * Updates document structure as a result of text insertion.
       * Since no such updates are needed in a textfield's model,
       * this method is overridden to do nothing.
      protected final void insertUpdate(DefaultDocumentEvent chng,
                                        AttributeSet attr)
        // no-op
       * Updates document structure as a result of text removal.
       * Since no such updates are needed in a textfield's model,
       * this method is overridden to do nothing.
      protected final void removeUpdate(DefaultDocumentEvent chng)
        // no-op
       * Replaces whitespace characters in the given string to more
       * visible, easily-editable characters.  The control characters
       * (TAB, LF) are replaced with their escapes (\t, \n), and the
       * SPACE character is replaced with a dot (U+00B7), making it
       * easy to see exactly how many there are.
       * @param str The string to convert
       * @return the converted string
      private String escapeWhitespace(String str)
        if (str == null)
          throw new IllegalArgumentException("String cannot be null");
        char[] working = str.toCharArray();
        StringBuffer sbuf = new StringBuffer(working.length + 10);
        for (int i = 0; i < working.length; i++)
          switch (working)
    case ' ':
    sbuf.append('\u00B7');
    break;
    case '\n':
    sbuf.append('\\').append('n');
    break;
    case '\t':
    sbuf.append('\\').append('t');
    break;
    default:
    sbuf.append(working[i]);
    return sbuf.toString();
    * Replaces common whitespace characters with visible symbols
    * to make it easier to see exactly what characters the string
    * contains. The control characters, TAB and LF, are replaced
    * with right- and down-pointing arrows, repectively (U+2192
    * and U+2193), and the space character is replaced with a
    * dot (U+00B7). The resulting string is for display only;
    * the {@link #escapeWhitespace} method creates a string that
    * is suitable for editing.
    * @param str The string to convert
    * @return the converted string
    private String displayWhitespace(String str)
    if (str == null)
    throw new IllegalArgumentException("String cannot be null");
    char[] working = str.toCharArray();
    StringBuffer sbuf = new StringBuffer(working.length);
    for (int i = 0; i < working.length; i++)
    switch (working[i])
    case ' ':
    sbuf.append('\u00B7');
    break;
    case '\t':
    sbuf.append('\u2192');
    break;
    case '\n':
    sbuf.append('\u2193');
    break;
    default:
    sbuf.append(working[i]);
    return sbuf.toString();
    * Converts the graphical whitespace symbols (the dot and the
    * arrows), to the characters they represent. The control
    * character escapes (\t and \n) will be left as they are.
    * @param str The string to restore
    * @return the converted string
    private String restoreWhitespace(String str)
    return restoreWhitespace(str, false);
    * Converts the graphical whitespace symbols (the dot and
    * the arrows), to the characters they represent. If
    * <tt>escapes</tt> is true, the control character escapes
    * (\t, \n) will also be replaced with the characters they
    * represent (TAB, LF).
    * @param str The string to restore
    * @param escapes Whether control escapes should be converted
    * @return the converted string
    private String restoreWhitespace(String str, boolean escapes)
    if (str == null)
    throw new IllegalArgumentException("String cannot be null");
    char[] working = str.toCharArray();
    StringBuffer sbuf = new StringBuffer(working.length);
    for (int i = 0; i < working.length; i++)
    if (working[i] > '\u007F')
    switch (working[i])
    case '\u00B7':
    sbuf.append(' ');
    break;
    case '\u2192':
    sbuf.append('\t');
    break;
    case '\u2193':
    sbuf.append('\n');
    break;
    default:
    sbuf.append(working[i]);
    else if (escapes && working[i] == '\\' &&
    i < working.length - 1)
    switch (working[++i])
    case 'n':
    sbuf.append('\n');
    break;
    case 't':
    sbuf.append('\t');
    break;
    default:
    sbuf.append('\\').append(working[i]);
    else
    sbuf.append(working[i]);
    return sbuf.toString();

  • Error with JTextField

    Hi,
    can anybody tell me why this doesn't work?:
    public class File1 {
    public static void main(String[] args) {
    String Pfad = new String();
    // create Window
    Window1 Dia = new Window1();
    // own Window Class
    class Window1 extends JFrame {
    // constructor
    public Window1 (){ 
    super("Search");
    setLocation(200,200);
    setSize(300,200);
    addWindowListener(new MyWindowListener());
    //Container
    Container conny = getContentPane();
    //Panel
    JPanel Inhalt = new JPanel();
    // Textfeld
    JTextField Getit = new JTextField(30);
    Getit.setToolTipText("Pfadname:");
    Inhalt.add(Getit);
    //Button
    JButton Knopf = new JButton("OK");
    Knopf.addActionListener(new MyActionListener());
    Inhalt.add(Knopf);
    // ContentPane
    conny.add(Inhalt, BorderLayout.NORTH);
    pack();
    show();
    // get content of JTextField
    public String getTextline(){
    return Getit.getText();
    When I try to compile this, I get the error message:
    Undefined variable or class name:Getit
    return Getit.getText();
    ^
    Undefine variable or class name:Dia
    System.out.println(Dia.getTextLine());
    ^
    The second command is used in an ActionListener which I added to
    the button.
    Please help. Whatever I tried, did not work.
    Thank you.
    Ralf

    Sorry for posting this twice.

  • Can´t get a value from a JTextField

    I don´t succeed in getting the text from a texfield from an actionListener.
    I have a class which is a JPanel containing a textfield.
    class MyPanel extends JPanel {
        private JTextField textfield = new JTextField();
        public String getInutValue() { return textfield.getText(); }
    }From another class that is a JFrame I have a button with an actionListener:
    class MainFrame extends JFrame {
        public void actionPerformed(ActionEvent e) {
             MyPanel panel = new MyPanel ();
             System.out.println(panel.getInutValue());  // Prints an emptry string ( "" )
    }Why can´t I get the value from the textfield on the JPanel from my other class?

    Roxxor wrote:
    I don´t succeed in getting the text from a texfield from an actionListener.
    I have a class which is a JPanel containing a textfield.
    class MyPanel extends JPanel {
    private JTextField textfield = new JTextField();
    public String getInutValue() { return textfield.getText(); }
    }From another class that is a JFrame I have a button with an actionListener:
    class MainFrame extends JFrame {
    public void actionPerformed(ActionEvent e) {
    MyPanel panel = new MyPanel ();
    System.out.println(panel.getInutValue());  // Prints an emptry string ( "" )
    }Why can´t I get the value from the textfield on the JPanel from my other class?You are creating a new instance of MyPanel in the actionPerformed method.

  • Validating a JTextField having a float or double value.

    Hello,
    I need help in validating a JTextfield which will accept a float or double value because it the deposit field and it shouldn't be of length more than 7 before the decimal and 2 after the decimal.That is it should be of length 10.I have written the following code for the validation.
    txtDeposit.addKeyListener(new KeyAdapter(){
    //Accept only integer value
              public void keyTyped(KeyEvent e){
              char c = e.getKeyChar();
    if((txtDeposit.getText()).length() == 10)
              if (!(Character.isDigit(c)))
              if(!Character.isISOControl(c))
              getToolkit().beep();
              e.consume();
              });//end of txtDeposit*/
    Please help.

    use javax.swing.InputVerifier
    import java.awt.BorderLayout;
    import java.awt.Toolkit;
    import javax.swing.InputVerifier;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    public class VerifyInput extends JFrame {
        public VerifyInput(){
            super("Input Verifier");
            this.setSize(200, 200);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JTextField txt = new JTextField();
            txt.setInputVerifier(new CheckInput());
            this.getContentPane().add(txt, BorderLayout.NORTH);
            JButton btnMoveFocus = new JButton("CLick");
            this.getContentPane().add(btnMoveFocus, BorderLayout.SOUTH);
        public static void main(String[] args) {
            VerifyInput f = new VerifyInput();
            f.setVisible(true);
        class CheckInput extends InputVerifier{
            private int lengthBeforeDot = 7;
            private int lengthAfterDot = 2;
            public CheckInput(){
            public CheckInput(int lengthBeforeDot, int lengthAfterDot){
                this.lengthAfterDot = lengthAfterDot;
                this.lengthBeforeDot = lengthBeforeDot;
            public boolean verify(JComponent input) {
                boolean correct = true;
                try {
                    JTextField tField = (JTextField) input;
                    String text = tField.getText();
                    if(text.length() == 0){
                        return true;
                    if ((correct = isDoubleOrFloat(text))) {
                        correct = isFormatCorrect(text);
                } finally {               
                    if(!correct){
                        Toolkit.getDefaultToolkit().beep();
                        System.out.println("Not Correct");
                    }else{
                        System.out.println("Correct");
                return correct;
            private boolean isDoubleOrFloat(String text){
                try{
                    Double.parseDouble(text);
                }catch(NumberFormatException nfe){
                    return false;
                return true;
            private boolean isFormatCorrect(String text){
                int dotIndex = text.indexOf('.');
                if(dotIndex < 0){
                    return text.length() <= lengthBeforeDot;
                String beforeDecimal = text.substring(0, dotIndex - 1);
                if(beforeDecimal.length() >= lengthBeforeDot){
                    return false;
                String afterDecimal = text.substring(dotIndex + 1);
                if(afterDecimal.length() > lengthAfterDot){
                    return false;
                return true;
    }

  • How can I change my JApplet into a JApplication?

    I am working with a JApplet and am finding that some of my code only works in applications.
    So being new to this, I am clueless as to how to change my Applet into an Application. I understand the difference in definition between the two, but when it comes to looking at Applet Code and Application Code, I am not able to see a difference. (Other than an Applet stating "Applet")
    So, that being said how can I change my code so that it runs as an application and not an applet? Here is my current layout code
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import java.text.NumberFormat;
    import java.text.DecimalFormat;
    // Creating the main class
    public class test extends JApplet implements ActionListener
         // Defining of format information
         JLabel heading = new JLabel("McBride Financial Services Mortgage Calculator");
         Font newFontOne = new Font("TimesRoman", Font.BOLD, 20);
         Font newFontTwo = new Font("TimesRoman", Font.ITALIC, 16);
         Font newFontThree = new Font("TimesRoman", Font.BOLD, 16);
         Font newFontFour = new Font("TimesRoman", Font.BOLD, 14);
         JButton calculate = new JButton("Calculate");
         JButton exitButton = new JButton("Quit");
         JButton clearButton = new JButton("Clear");
         JLabel instructions = new JLabel("Please Enter the Principal Amount Below");
         JLabel instructions2 = new JLabel("and Select a Loan Type from the Menu");
         // Declaration of variables
         private double principalAmount;
         private JLabel principalLabel = new JLabel("Principal Amount");
         private NumberFormat principalFormat;
         private JTextField enterPrincipal = new JTextField(10);
         private double finalPayment;
         private JLabel monthlyPaymentLabel = new JLabel("  Monthly Payment    \t         Interest Paid    \t \t            Loan Balance");
         private NumberFormat finalPaymentFormat;
         private JTextField displayMonthlyPayment = new JTextField(10);
         private JTextField displayInterestPaid = new JTextField(10);
         private JTextField displayBalance = new JTextField(10);
         // Creation of the String of arrays for the ComboBox
         String [] list = {"7 Years @ 5.35%", "15 Years @ 5.50%", "30 Years @ 5.75%"};
         JComboBox selections = new JComboBox(list);
         // Creation of the textArea that will display the output
         private TextArea txtArea = new TextArea(5, 10);
         StringBuffer buff = null;
         // Initializing the interface
         public void init()
              // Creation of the panel design and fonts
              JPanel upper = new JPanel(new BorderLayout());
              JPanel middle = new JPanel(new BorderLayout());
              JPanel lower = new JPanel(new BorderLayout());
              JPanel areaOne = new JPanel(new BorderLayout());
              JPanel areaTwo = new JPanel(new BorderLayout());
              JPanel areaThree = new JPanel(new BorderLayout());
              JPanel areaFour = new JPanel(new BorderLayout());
              JPanel areaFive = new JPanel(new BorderLayout());
              JPanel areaSix = new JPanel(new BorderLayout());
              Container con = getContentPane();
              getContentPane().add(upper, BorderLayout.NORTH);
              getContentPane().add(middle, BorderLayout.CENTER);
              getContentPane().add(lower, BorderLayout.SOUTH);
              upper.add(areaOne, BorderLayout.NORTH);
              middle.add(areaTwo, BorderLayout.NORTH);
              middle.add(areaThree, BorderLayout.CENTER);
              middle.add(areaFour, BorderLayout.SOUTH);
              lower.add(areaFive, BorderLayout.NORTH);
              lower.add(areaSix, BorderLayout.SOUTH);
              heading.setFont(newFontOne);
              instructions.setFont(newFontTwo);
              instructions2.setFont(newFontTwo);
              principalLabel.setFont(newFontThree);
              monthlyPaymentLabel.setFont(newFontFour);
              displayInterestPaid.setFont(newFontFour);
              displayBalance.setFont(newFontFour);
              areaOne.add(heading, BorderLayout.NORTH);
              areaOne.add(instructions, BorderLayout.CENTER);
              areaOne.add(instructions2, BorderLayout.SOUTH);
              areaTwo.add(principalLabel, BorderLayout.WEST);
              areaTwo.add(enterPrincipal, BorderLayout.EAST);
              areaThree.add(selections, BorderLayout.NORTH);
              areaFour.add(calculate, BorderLayout.CENTER);
              areaFour.add(exitButton, BorderLayout.EAST);
              areaFour.add(clearButton, BorderLayout.WEST);
              areaFive.add(monthlyPaymentLabel, BorderLayout.CENTER);
              areaSix.add(txtArea, BorderLayout.CENTER);
              // Using the ActionListener to determine when each button is clicked
              calculate.addActionListener(this);
              exitButton.addActionListener(this);
              clearButton.addActionListener(this);
              enterPrincipal.requestFocus();
              selections.addActionListener(this);
         }

    baftos wrote:
    Here is one of the sites that explains the procedure:
    [http://leepoint.net/notes-java/deployment/applications_and_applets/70applets.html].
    But maybe you should try to fix the code that does not work as applet?
    Which one is it?
    >Here is one of the sites that explains the procedure:
    [http://leepoint.net/notes-java/deployment/applications_and_applets/70applets.html].
    But maybe you should try to fix the code that does not work as applet?
    Which one is it?
    The code that doesn't work in my applet is the exit button code
    else if (source == exitButton)
                        System.exit(1);
                   }I also can't get my program to properly validate input. When invalid input is entered and the user presses calculate, an error window should pop up. Unfortunately it isn't. I compile and run my applications/applets through TextPad. So when I try to test the error window by entering in invalid info, the applet itself shows nothing but the command prompt window pops up and lists errors from Java. Anyhow, here is the method I was told to use to fix it.
    private static boolean validate(JTextField in)
              String inText = in.getText();
              char[] charInput = inText.toCharArray();
              for(int i = 0; i < charInput.length; i++)
                   int asciiVal = (int)charInput;
              if((asciiVal >= 48 && asciiVal <= 57) || asciiVal == 46)
              else
                   JOptionPane.showMessageDialog(null, "Invalid Character, Please Use Numeric Values Only");
                   return false;
                   return true;
         }My Instructor told me to try the following, but I still can't get it to work.String content = textField.getText();
    if (content.length() != 0) {       
    try {          Integer.parseInt(content);  
    } catch (NumberFormatException nfe) {}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Problem with Listeners/ requestFocus()

    Hello,
    I am new to Java (started learning two months back), There is a problem with the requestFocus() in the focusListener. The program does not return the focus to the object indicated in the requestFocus but it shows multiple cusors!!
    The faculity at the institute where I am learning could not rectify the error.
    Is the error because of the myMethod() which I am using. I had made this method to prove to my professor that we can reduce the code drastically while using the gridbaglayout.
    The code which I had written is as under:
    // file name ShopperApplet.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ShopperApplet extends JApplet implements ActionListener, FocusListener,Runnable
         //static JPanel sP;
         //static JPanel oP;
         JTabbedPane tabbedPane = new JTabbedPane();
         JPanel sP;
         JPanel oP;
         JPanel pwd = new JPanel();
         // Layout Decleration of oP
         GridBagLayout ordL = new GridBagLayout();
         GridBagConstraints ordC = new GridBagConstraints();
         // Layout Decleration of sP
         FlowLayout flow = new FlowLayout();
         // Variables of sP
              JTextField textShopperId;
              JPasswordField textPassword;
              JTextField textFirstName ;
              JTextField textLastName ;
              JTextField textEmailId ;
              JTextField textAddress ;
              JComboBox comboCity ;
              JTextField textState ;
              JTextField textCountryId ;
              JTextField textZipCode ;
              JTextField textPhone ;
              JTextField textCreditCardNo ;
              JRadioButton rbVisa;
              JRadioButton rbMaster;
              JRadioButton rbAmEx;
              ButtonGroup BGccType;
              //JComboBox comboCreditCardType;
              //JTextField textExperyDate;
              JComboBox cmbDt;
              JComboBox cmbMth;
              JComboBox cmbYear;
              JButton btnSubmit;
              JButton btnReset;          
         // Variables of oP
              // Variable Decleration od oP
              JTextField txtOrderNo;
              JTextField txtToyId;
              JTextField txtQty;
              JRadioButton rbYes;     
              JRadioButton rbNo;
              ButtonGroup bgGiftWrap;
              JComboBox cmbWrapperId;
              JTextField txtMsg;
              JTextField txtToyCost;
              JButton btnOSubmit;
              JButton btnOReset;     
         // Variables of pwd
              JTextField txtShopperId;
              JPasswordField txtPassword;
              JButton btnPSubmit;
              JButton btnPReset;     
              JButton btnPNew;
              JButton btnPLogoff;
              JLabel lblN, lblN1;     
              Thread t,t1;
         Font TNR = new Font("Times New Roman",1,15);
         Font arial = new Font("Arial",2,15);
         public void sPDet()
              //Variable Decleration of sP
              textShopperId = new JTextField(6);
              textPassword = new JPasswordField(4);
              textPassword.addFocusListener(this);
              //textPassword = new JTextField(4);
              textPassword.setEchoChar('*');
              textFirstName = new JTextField(20);
              textLastName = new JTextField(20);
              textEmailId = new JTextField(25);
              textAddress = new JTextField(20);
              String cityList[] = {"New Delhi", "Mumbai", "Calcutta", "Hyderabad"};
              comboCity = new JComboBox(cityList);
              comboCity.setEditable(true);
              textState = new JTextField(30);
              textCountryId = new JTextField(25);
              textZipCode = new JTextField(6);
              textPhone = new JTextField(25);
              textCreditCardNo = new JTextField(25);
              String cardTypes[] = {"Visa", "Master Card", "American Express"};
              //comboCreditCardType = new JComboBox(cardTypes);
              rbVisa = new JRadioButton("Visa");
              rbMaster = new JRadioButton("Master Card");
              rbAmEx = new JRadioButton("American Express");
              BGccType = new ButtonGroup();
              BGccType.add(rbVisa);
              BGccType.add(rbMaster);
              BGccType.add(rbAmEx);
              String stDt[] = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31"};
              String stMth[] = {"January","February","March","April","May","June","July","August","September","October","November","December"};
              String stYear[] = {"2001","2002","2003","2004","2005","2006","2007","2008","2009","2010"};
              cmbDt = new JComboBox(stDt);
              cmbMth = new JComboBox(stMth);
              cmbYear = new JComboBox(stYear);
              //textExperyDate = new JTextField(10);
              btnSubmit = new JButton("Submit");
              btnReset = new JButton("Reset");
              // Adding Layout Controls
              sP.setLayout(ordL);
              sP.setBackground(Color.green);
              myLayout(textShopperId,3,1,sP,"FM","Shopper Id");
              myLayout(textPassword,3,2,sP,"FM","Password");
              myLayout(textFirstName,3,3,sP,"FM","First Name") ;
              myLayout(textLastName,3,4,sP,"FM","Last Name") ;
              myLayout(textEmailId,3,5,sP,"FM","E-Mail Id") ;
              myLayout(textAddress,3,6,sP,"FM", "Address") ;
              myLayout(comboCity,3,7,sP,"FM","City") ;
              myLayout(textState,3,8,sP,"FM","State") ;
              myLayout(textCountryId,3,9,sP,"FM","Country") ;
              myLayout(textZipCode,3,10,sP,"FM","Zip Code") ;
              myLayout(textPhone,3,11,sP,"FM","Phone") ;
              myLayout(textCreditCardNo,3,12,sP,"FM","Credit Card No.") ;
              //myLayout(rbVisa,3,13,sP);
              JPanel newPanel = new JPanel();
              newPanel.add(rbVisa);
              newPanel.add(rbMaster);
              newPanel.add(rbAmEx);
              myLayout(newPanel,3,13,sP,"FM","Credit Card Type");
              //myLayout(rbMaster,4,13);
              //myLayout(rbAmEx,5,13);
              JPanel newPanel1 = new JPanel();
              newPanel1.add(cmbDt);
              newPanel1.add(cmbMth);
              newPanel1.add(cmbYear);
              myLayout(newPanel1,3,14,sP,"FM","Expiry Date");
              //myLayout(textExperyDate,3,14,sP,"FM");
              myLayout(btnSubmit,1,17,sP,"AL","Submit");
              myLayout(btnReset,3,17,sP,"AL","Reset");          
         public void oPDet()
              txtOrderNo = new JTextField(10);
              txtToyId = new JTextField(10);
              txtQty = new JTextField(10);
              rbYes = new JRadioButton("Yes");
              rbNo = new JRadioButton("No");
              bgGiftWrap = new ButtonGroup();
              bgGiftWrap.add(rbYes);
              bgGiftWrap.add(rbNo);
              String wrapperTypes[] = {"Blue Stripes", "Red Checks", "Green Crosses","Yellow Circles", "Red & Purple Stripes"};
              cmbWrapperId = new JComboBox(wrapperTypes);
              txtMsg = new JTextField(10);
              txtToyCost = new JTextField(10);
              btnOSubmit = new JButton("Submit");
              btnOReset = new JButton("Reset");
              // Adding Controls to oP
              oP.setLayout(ordL);
              oP.setBackground(Color.yellow);
              myLayout(txtOrderNo,3,1,oP,"FM","Order No.");
              myLayout(txtToyId,3,2,oP,"FM","Toy Id");
              myLayout(txtQty,3,3,oP,"FM","Quantity");
              myLayout(rbYes,3,4,oP,"M");
              myLayout(rbNo,4,4,oP,"M");
              myLayout(cmbWrapperId,3,5,oP,"M","Wrapper Id");
              myLayout(txtMsg,3,6,oP,"FM","Message");
              myLayout(txtToyCost,3,7,oP,"FM","Toy Cost");
              myLayout(btnOSubmit,1,8,oP,"AL","Submit");
              myLayout(btnOReset,3,8,oP,"AL","Reset");          
         public void pwdDet()
              pwd.setLayout(ordL);
              pwd.setBackground(Color.green);
              t = new Thread(this);
              t.start();
              t1 = new Thread(this);
              t1.start();
              lblN = new JLabel("");
              lblN1 = new JLabel("");
              txtShopperId = new JTextField(10);
              txtPassword = new JPasswordField(10);
              btnPSubmit = new JButton("Submit") ;
              btnPReset = new JButton("Reset");     
              btnPNew = new JButton("New Member");
              btnPLogoff = new JButton("Log Off");
              pwd.setLayout(ordL);
              pwd.setBackground(Color.yellow);
              myLayout(lblN,3,7,pwd);
              myLayout(lblN1,3,8,pwd);
              myLayout(txtShopperId,3,1,pwd,"FM","Shopper Id.");
              myLayout(txtPassword,3,2,pwd,"FM","Password");
              myLayout(btnPSubmit,2,4,pwd,"AL","Submit");
              myLayout(btnPReset,3,4,pwd,"AL","Reset");          
              myLayout(btnPNew,2,5,pwd,"AL","New");
              myLayout(btnPLogoff,3,5,pwd,"AL","Log Off");
         public void run()
              int ctr =0;
              String ili[] = {"India","is","a","Great","Country"};
              int ctr1 = 0;
              String iib[] = {"India","is","the","Best"};
              Thread myThread = Thread.currentThread();
              if (myThread == t)
                   while (t != null)
                        lblN.setText(ili[ctr]);
                        ctr++;
                        if (ctr >=5) ctr=0;
                        try
                             t.sleep(500);
                        catch(InterruptedException e)
                             showStatus("India is a great Country has been interrupter");
              else
                   while (t1 != null)
                        lblN1.setText(iib[ctr1]);
                        ctr1++;
                        if (ctr1 >=4) ctr1=0;
                        try
                             t1.sleep(1000);
                        catch(InterruptedException e)
                             showStatus("India is the best has been interrupter");
         public void myLayout(JComponent aObj, int x, int y, JPanel aPanel,String aListener,String toolTip)
              ordC.anchor=GridBagConstraints.NORTHWEST;
              JLabel aLabel = new JLabel(toolTip);
              ordC.gridx = x-1;
              ordC.gridy = y;
              ordL.setConstraints(aLabel,ordC);
              aPanel.add(aLabel);
              aObj.setToolTipText("Enter "+toolTip+" here");
              aObj.setForeground(Color.red);
              aObj.setBackground(Color.green);
              if (aListener.indexOf("F")     != -1)
                   aObj.addFocusListener(this);
              //if (aListener.indexOf("M")     != -1)
                   //aObj.addMouseListener(this);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void myLayout(JComponent aObj, int x, int y, JPanel aPanel,String aListener)
              ordC.anchor=GridBagConstraints.NORTHWEST;
              aObj.setForeground(Color.red);
              aObj.setBackground(Color.green);
              if (aListener.indexOf("F")     != -1)
                   aObj.addFocusListener(this);
              //if (aListener.indexOf("M")     != -1)
                   //aObj.addMouseListener(this);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void myLayout(JButton aObj, int x, int y, JPanel aPanel,String aListener, String toolTip)
              aObj.setToolTipText(toolTip);
              ordC.anchor=GridBagConstraints.NORTHWEST;
              aObj.setForeground(Color.red);
              if (aListener.indexOf("F")     != -1)
                   aObj.addFocusListener(this);
              //if (aListener.indexOf("M")     != -1)
                   //aObj.addMouseListener(this);
              if (aListener.indexOf("A")     != -1)
                   aObj.addActionListener(this);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void myLayout(JTextField aObj, int x, int y, JPanel aPanel,String aListener,String toolTip)
              ordC.anchor=GridBagConstraints.NORTHWEST;
              //aObj = new JTextField(10);
              JLabel aLabel = new JLabel(toolTip);
              ordC.gridx = x-1;
              ordC.gridy = y;
              ordL.setConstraints(aLabel,ordC);
              aPanel.add(aLabel);
              aObj.setToolTipText("Enter "+toolTip+" here");
              aObj.setForeground(Color.red);
              if (aListener.indexOf("F")     != -1)
                   aObj.addFocusListener(this);
              //if (aListener.indexOf("M")     != -1)
              //     aObj.addMouseListener(this);
              if (aListener.indexOf("A")     != -1)
                   aObj.addActionListener(this);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void myLayout(JLabel aObj, int x, int y, JPanel aPanel)
              ordC.anchor=GridBagConstraints.SOUTH;
              aObj.setForeground(Color.blue);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void init()
              getContentPane().add(tabbedPane);
              sP = new JPanel();
              sPDet();
              oP = new JPanel();
              oPDet();
              pwdDet();
              tabbedPane.addTab("Login",null,pwd,"Login");
              tabbedPane.addTab("Shopper",null,sP,"Shopper Details");
              tabbedPane.addTab("Order",null,oP,"Order Details");
              tabbedPane.setEnabledAt(2, false);
              tabbedPane.setEnabledAt(1, false);
         public void actionPerformed(ActionEvent e)
              Object obj = e.getSource();
              if (obj == btnSubmit)
                   if (validShopperId() == false) return;
                   if (validPassword() == false) return;
                   if (validFirstName() == false) return ;
                   if (validLastName() == false) return ;
                   if (validEmailId() == false) return;
                   if (validAddress() == false) return;
                   if (validState() == false) return;
                   if (validCountryId() == false) return;
                   if (validZipCode() == false) return;
                   if (validCreditCardNo() == false) return ;
                   resetShopper();
                   tabbedPane.setEnabledAt(1,false);
                   tabbedPane.setEnabledAt(2,false);
                   tabbedPane.setSelectedIndex(0);
                   // also can be written as tabbedPane.setSelectedComponent(pwd);
                   //tabbedPane.remove(sP);
              if (obj == btnReset)
                   resetShopper();
                   tabbedPane.setEnabledAt(2,false);
                   //textExperyDate.setText("");
              if (obj == btnOSubmit)
                   if (validOrderNo() == false) return;
                   if (validToyId() == false) return;
                   if (chkNullEntry(txtQty, "Quantity")) return ;
                   if (chkNullEntry(txtToyCost, "Toy Cost")) return ;
              if (obj == btnOReset)
                   resetOrder();
              if (obj == btnPSubmit)
                   if (validPShopperId() && validPPassword())
                        tabbedPane.setEnabledAt(2, true);
                        tabbedPane.setEnabledAt(1, false);
                        txtShopperId.setText("");
                        txtPassword.setText("");
                        resetPassword();
                        //tabbedPane.addTab("Order",null,oP,"Order Details");
              if (obj == btnPReset)
                   resetPassword();
                   tabbedPane.setEnabledAt(1, false);
                   tabbedPane.setEnabledAt(2, false);
              if (obj == btnPNew)
                   tabbedPane.setEnabledAt(1, true);
                   tabbedPane.setEnabledAt(2, false);
                   resetPassword();
                   tabbedPane.setSelectedComponent(sP);
                   //tabbedPane.addTab("Shopper",null,sP,"Shopper Details");          
              if (obj == btnPLogoff)
                   tabbedPane.setEnabledAt(2, false);
                   tabbedPane.setEnabledAt(1, false);
                   resetPassword();
         public void focusGained(FocusEvent fe)
              //Object aObj = fe.getSource();
              //showStatus("Current Object is "+aObj);
         public void resetPassword()
              txtShopperId.setText("");
              txtPassword.setText("");
         public void resetShopper()
                   textShopperId.setText("");
                   textPassword.setText("");
                   textFirstName.setText("") ;
                   textLastName.setText("") ;
                   textEmailId.setText("") ;
                   textAddress.setText("") ;
                   textState.setText("") ;
                   textCountryId.setText("") ;
                   textZipCode.setText("") ;
                   textPhone.setText("") ;
                   textCreditCardNo.setText("") ;
         public void resetOrder()
              txtOrderNo.setText("");
              txtToyId.setText("");
              txtQty.setText("") ;
              txtToyCost.setText("") ;
              txtMsg.setText("") ;
         public void focusLost(FocusEvent fe)
              try{
                   Object obj = fe.getSource();
                   if (obj == textShopperId &&     validShopperId() == false)
                        //textShopperId.requestFocus();
                        return;
                   if (obj == textPassword && validPassword() == false)
                        //textPassword.requestFocus();
                        return;
                   if (obj == textFirstName && validFirstName() == false)
                        //textFirstName.requestFocus();
                        return;
                   if (obj == textEmailId && validEmailId() == false)
                        //textEmailId.requestFocus();
                        return;
                   if (obj == txtOrderNo && validOrderNo() == false)
                        //txtOrderNo.requestFocus();
                        return;
                   if (obj == txtToyId && validToyId() == false);
                        //txtToyId.requestFocus();
                        return;
              catch(Exception e)
                   showStatus("error in LostFocus() Method");
         public boolean validShopperId()
              if (chkNullEntry(textShopperId,"Shopper Id")) return false;
              return true;
         public boolean validPassword()
              if (chkNullEntry(textPassword,"Password")) return false;
              return true;
         public boolean validFirstName()
              if (chkNullEntry(textFirstName,"First Name")) return false;
              return true;
         public boolean validLastName()
              if (chkNullEntry(textLastName,"Last Name")) return false;
              return true;
         public boolean validAddress()
              if (chkNullEntry(textAddress,"Address")) return false;
              return true;
         public boolean validState()
              if (chkNullEntry(textState,"State")) return false;
              return true;
         public boolean validCountryId()
              if (chkNullEntry(textCountryId,"Country")) return false;
              return true;
         public boolean validZipCode()
              if (chkNullEntry(textZipCode,"Postal Code")) return false;
              return true;
         public boolean validCreditCardNo()
              if (chkNullEntry(textCreditCardNo,"Credit Card No.")) return false;
              return true;
         public boolean validEmailId()
              if (chkNullEntry(textEmailId,"Email Address")) return false;
              String s1 = textEmailId.getText();
              int abc = s1.indexOf("@");
              if (abc == -1 || abc == 0 || abc == (s1.length()-1))
                   JOptionPane.showMessageDialog(sP,"Invalid Email Address","Error Message",JOptionPane.ERROR_MESSAGE);
                   //textEmailId.requestFocus();
                   return false;
              return true;
         public boolean validOrderNo()
              if (chkNullEntry(txtOrderNo,"Order No.")) return false;
              return true;
         public boolean validToyId()
              if (chkNullEntry(txtToyId,"Toy Id")) return false;
              return true;
         public boolean chkNullEntry(JTextField aObj,String sDef)
              String s1 = aObj.getText();
              if (s1.length() ==0)
                   try
                        JOptionPane.showMessageDialog(sP,sDef+" cannot be left blank","Error Message",JOptionPane.ERROR_MESSAGE);
                        //showStatus(sDef+" cannot be left blank");
                        // nbvvvv vcz     z111111eeeefgggggggggg aObj.requestFocus();
                   catch(Exception e)
                        showStatus("Error in chkNullEntry() method");
                   return true ;
              else
                   return false;
         public boolean validPShopperId()
              if (chkNullEntry(txtShopperId,"Shopper Id")) return false;
              return true;
         public boolean validPPassword()
              if (chkNullEntry(txtPassword,"Password")) return false;
              return true;
    // end of code.

    Would it not be acceptable to check that each field has a value when Submit is pressed. If a field is found with no data then display the error message and return the focus to the empty field. This would solve the multiple cursors problem as you would not need any focusLost handler code.
    If this is entirely out of the question then you will have to override some of the FocusManager methods to prevent the JVM from handling focus for you :
    FocusManager.setCurrentManager(new DefaultFocusManager() {
      // Override FocusManager methods here.
    });Ronny.

Maybe you are looking for