VK_TAB in a JTextField

The mouse listener attached to a JTextField does not recognize VK_TAB but works fine for VK_ENTER. Why?

If using jdk 1.4 look at the Component.setFocusTraversalKeysEnabled() family of methods. There is a similar but different way to do it in jdk 1.3, but I forget what it is.

Similar Messages

  • How to recognize the tab key in a JTextField

    I have a drawing program with a main window and a tools palette, which is a JDialog. The tools palette has JToggleButtons and one JTextField. When you have the focus in the JTextField and you press tab repeatedly, it tabs through all the JToggleButtons and then back into the JTextField.
    However I would like to recognize the pressing of the tab key and ask for the focus to go back to the main window.
    I subclassed the JTextField, added a KeyAdapter, but it does not recognize the tab key. I also added the processKeyBinding method, but it doesn't recognize the tab key either.
    How can I recognize the tab key?
    Here is a self-contained test program that illustrates the problem:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class AnanyaCurves extends JFrame
      Tools tools;
      public AnanyaCurves(Dimension windowSize)
        Basics.ananyaCurves = this;
        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        setTitle("Ananya Curves");
        tools = new Tools(this);
      public static void main(String[] args)
        int toolsWidth;
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        toolsWidth = 200;
        Dimension windowSize = new Dimension(screenSize.width - toolsWidth, screenSize.height - 58);
        AnanyaCurves ananyaCurves = new AnanyaCurves(windowSize);
        ananyaCurves.pack();
        ananyaCurves.setBounds(toolsWidth, 0, windowSize.width, windowSize.height);
        ananyaCurves.setVisible(true);
        ananyaCurves.requestFocus();
      public void setVisible(boolean b)
        tools.setVisible(b);
        super.setVisible(b);
    class Basics extends java.lang.Object
      public static AnanyaCurves ananyaCurves;
      public Basics()
    class Tools extends JDialog
      JToggleButton btnGrid;
      JTextField textGrid;
      JPanel panel;
      public Tools(JFrame frame)
        super(frame, "Tools", false);
        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        btnGrid = makeBtn("Grid");
        textGrid = makeTextField();
        panel = makePanel();
        pack();
      public JToggleButton makeBtn(String name)
        JToggleButton btn = new JToggleButton();
        btn.setMaximumSize(new Dimension(108, 24));
        btn.setPreferredSize(new Dimension(108, 24));
        btn.setText(name);
        btn.setFont(new Font("Verdana", Font.PLAIN, 11));
        btn.setMargin(new Insets(5, 10, 5, 10));
        btn.setOpaque(true);
        return btn;
      public ACJTextField makeTextField()
        ACJTextField textField = new ACJTextField();
        textField.setFont(new Font("Verdana", Font.PLAIN, 12));
        textField.setMaximumSize(new Dimension(108, 20));
        textField.setPreferredSize(new Dimension(108, 20));
        textField.setText("0.25");
        textField.setEnabled(true);
        return textField;
      public JPanel makePanel()
        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.add(btnGrid);
        panel.add(textGrid);
        getContentPane().add(panel);
        return panel;
    class ACJTextField extends JTextField
      KeyAdaption keyAdaption;
      public ACJTextField()
        super();
        keyAdaption = new KeyAdaption();
        this.addKeyListener(keyAdaption);
      class KeyAdaption extends KeyAdapter
        public void keyPressed(KeyEvent event)
          int keyCode = event.getKeyCode();
          if (keyCode == KeyEvent.VK_TAB)
            Basics.ananyaCurves.requestFocus();
      protected boolean processKeyBinding(KeyStroke keyStroke, KeyEvent keyEvent, int int2, boolean boolean3)
        int keyCode = keyEvent.getKeyCode();
        if (keyCode == KeyEvent.VK_TAB)
          Basics.ananyaCurves.requestFocus();
          return false;
        return super.processKeyBinding(keyStroke, keyEvent, int2, boolean3);
    }Thanks for looking at this.

    Wow, Michael, you work like magic! Thanks so much! I would be happy to give you a commercial key to my Ananya Curves program also once the second release is on my website. It's a program for drawing curves in an easier way without pulling on tangent lines, with all control points right on the curve. Just send me an email to [email protected] if you are interested!

  • JTextField: How to modify keybinding / keyboard response?

    Hello Experts,
    For a certain programming purpose, is there a way to modify keyboard response?
    I have created a JTextField txtSample. When it gets the focus, I want it to behave as following:
    1. When user presses '+' key, instead of printing '+' in the text field, I want to do some actions and the '+' is not printed.
    2. When user presses 'a' key, instead of printing 'a' in the text field, I want 'o' to be printed.
    I have done the following for the first purpose, but it doesn't work:
    Action addTrans = new AbstractAction() {
         public void actionPerformed(ActionEvent e){
              System.out.println("User has pressed + keypad");
    txtSample.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, 0), "addTrans");
    txtSample.getActionMap().put("addTrans", addTrans);Any advice would be greatly appreciated.
    Patrick

    camickr,
    First amazing thing, the first time I clicked on the link
    Works fine is this example:
    http://forums.sun.com/thread.jspa?forumID=57&threadID=622030 it gave an error message.
    Second amazing thing, I checked on the API of KeyStroke
    getKeyStroke
    public static KeyStroke getKeyStroke(char keyChar)
        Returns a shared instance of a KeyStroke that represents a KEY_TYPED event for the specified character.
        Parameters:
            keyChar - the character value for a keyboard key
        Returns:
            a KeyStroke object for that key
    getKeyStroke
    public static KeyStroke getKeyStroke(int keyCode,
                                         int modifiers)
        Returns a shared instance of a KeyStroke, given a numeric key code and a set of modifiers. The returned KeyStroke will correspond to a key press.
        The "virtual key" constants defined in java.awt.event.KeyEvent can be used to specify the key code. For example:
            * java.awt.event.KeyEvent.VK_ENTER
            * java.awt.event.KeyEvent.VK_TAB
            * java.awt.event.KeyEvent.VK_SPACE
        The modifiers consist of any combination of:
            * java.awt.event.InputEvent.SHIFT_DOWN_MASK
            * java.awt.event.InputEvent.CTRL_DOWN_MASK
            * java.awt.event.InputEvent.META_DOWN_MASK
            * java.awt.event.InputEvent.ALT_DOWN_MASK
            * java.awt.event.InputEvent.ALT_GRAPH_DOWN_MASK
        The old modifiers
            * java.awt.event.InputEvent.SHIFT_MASK
            * java.awt.event.InputEvent.CTRL_MASK
            * java.awt.event.InputEvent.META_MASK
            * java.awt.event.InputEvent.ALT_MASK
            * java.awt.event.InputEvent.ALT_GRAPH_MASK
        also can be used, but they are mapped to _DOWN_ modifiers. Since these numbers are all different powers of two, any combination of them is an integer in which each bit represents a different modifier key. Use 0 to specify no modifiers.
        Parameters:
            keyCode - an int specifying the numeric code for a keyboard key
            modifiers - a bitwise-ored combination of any modifiers
        Returns:
            a KeyStroke object for that key
        See Also:
            KeyEvent, InputEventThere is no indication that one method consume the keystroke, while the other does not. Now, I understand that keybinding can prevent the key from reaching the model.
    And last, yes, you are right. It would be better to use DocumentFilter to serve
    When user presses 'a' key, instead of printing 'a' in the text field, I want 'o' to be printed.Thanks for all your effort to guide me and sorry for the misunderstanding,
    Patrick

  • Listening Tab Key Event On JTextField

    Hi
    i am unable to listen Tab Key Event on JTextField ....
    tField.addKeyListener(new KeyAdapter()
    public void keyPressed(KeyEvent e)
    if (e.getKeyCode()==e.VK_TAB)
    JOptionPane.showMessageDialog(null,"Tab Pressed");
    else
    JOptionPane.showMessageDialog(null,"Tab Not Pressed");
    When i pressed Tab Key then it dont come in KeyPressed Event ...Actually it go towards next FocusAble component ..
    Any help in this regard.....

    I also Checked it by using
    tField..setFocusTraversalKeysEnabled(false);
    tField.addKeyListener(new KeyAdapter()
    public void keyPressed(KeyEvent e)
    if (e.getKeyCode()==e.VK_TAB)
    JOptionPane.showMessageDialog(null,"Tab Pressed");
    else
    JOptionPane.showMessageDialog(null,"Tab Not Pressed");
    In this case each time e.getKeyCode() returns 0...
    plz help me

  • Catch TAB and jump to new position in JTextField!!!

    Hi,
    first of all i wanna say Hi to everyboy, 'cause this is my first post in this forum. and here comes my question:
    I have a JTextfield and if the TAB-Button will be used there, the cursor should jump to a new position. So in detail, it SHOULDN'T do the normal TAB stuff (insert some blanks). Only the cursor should jump to a new position.
    What I did: (workaround)
    I used a KeyFieldsListener(extends KeyAdapter) which catches the TAB, copies the text before and after the blanks (which comes from the TAB). The PROBLEM is, this is to slow. The user can see what the TAB is doing.
    For any suggestions I would be grateful !!!
    Regards,
    Robin
    My Code:
    if ((key == KeyEvent.VK_TAB)){
         // now position of caret (after TAB)
         int offset = HitlistFrame.searchText.getCaretPosition();
         String tempText = HitlistFrame.searchText.getText().substring(0, offset-1) +  HitlistFrame.searchText.getText().substring(offset);
         // copy text before TABING into TextField
         HitlistFrame.searchText.setText(tempText);
         // search for next blank
         while ((offset < HitlistFrame.searchText.getText().length()) &&
                   (HitlistFrame.searchText.getText().charAt(offset) != ' '))
              offset++;
         // set cursor to position of next blank
         HitlistFrame.searchText.setCaretPosition(offset);
    }

    The long and short of it that the code simply assumes theat the layers don't exceed the comp size or leave the comp. Depending on where you apply the code, that may not be true. You would have to add extra stuff to make it more safe and things like specific shape layer modifications or the anchor point coordinates on shape layers being based on the middle of the layer, thus regularly producing negative values, would further complicate the matter. The code is simply too simplistic to cover such scenarios and the internal calculations in your case probably produce these aforementioned negative vlaues that the Puppet effect can't handle since in its world they don't exist. Anyway, without seeing what's actualyl going on, nobody can provide the ultimate solution. I could write an endlessly complex expression and it may still not solve your dilemma. as a start, you might consider pre-composing everything to comps of the same size and using these comps instead of the native AI file. This would also eliminate all the hocuspocus with the layer space transforms and greatly simplify things (and help performance).
    Mylenium

  • Jtextfields and accepting tabs instead or in addiction to CR

    I'm wondering, (I've done a quick search and found nothing exactly like it, but maybe someone can help). How does one set up (simply) a single jtextfield to accept a tab as an actionevent (or to fire an action event). Here is what I'm trying to do. When the person inputs a name or something and then tabs to the next component (Jtextfield or jspinner in this case) it fires off an event saything that the content has changed and that the Controller must now update the Model from the input within the view (Jtextfield). Is there a simple way to do this?
    Thanks in advance.

    Here is a sample program that will detect the tab key using the suggestions I made earlier (alternate method is commented out):
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class Test1 extends JPanel implements ActionListener {
       Test1() {
          myJTextField tf1,tf2,tf3;
          tf1=new myJTextField(10);     
          tf1.addActionListener(this);
          tf2=new myJTextField(10);     
          tf2.addActionListener(this);
          tf3=new myJTextField(10);     
          tf3.addActionListener(this);
          add(tf1);
          add(tf2);
          add(tf3);
          tf1.requestFocus();
       public void actionPerformed(ActionEvent e) {
          System.out.println("ENTER detected -- Do what you want here and move on");
       public static void main(String s[]) {
          WindowListener l = new WindowAdapter() {
             public void windowClosing(WindowEvent e) {
                System.exit(0);
          JFrame f = new JFrame("Test1");
          f.addWindowListener(l);
          f.getContentPane().add("Center", new Test1());
          f.pack();
          f.setSize(new Dimension(400,300));
          f.setVisible(true);
       class myJTextField extends JTextField {
          myJTextField(int col) {
             super(col);
             setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,Collections.EMPTY_SET);
             setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,Collections.EMPTY_SET);
    /* uncomment this section and remove the processKeyBinding
             KeyStroke tab=KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0);
             getActionMap().put("tabAction", new tabAction());
             getInputMap(JComponent.WHEN_FOCUSED).put(tab,"tabAction");
             getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(tab,"tabAction");
          public boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
             if (ks == KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0)) {          // TAB
                System.out.println("TAB detected! do what you want here and move on");
                return true;
             return super.processKeyBinding(ks,e,condition,pressed);
    /* uncomment this section and remove the processKeyBinding
       private class tabAction extends AbstractAction {
          public void actionPerformed(ActionEvent e) {
             System.out.println("TAB detected! do what you want here and move on");
    }Since I don't know what you're trying to do once you have detected either the ENTER or TAB key, I leave that part up to you.
    ;o)
    V.V.

  • Open and Close OnScreen Keyboard while focus gain on JTextField

    Hi
    I have a Jtextfield when ever I click on textfield I want to open OSK(On Screen Keyboard) of Windows 8 OS and windows 7.
    I tried in below mentioned way to open and close in focus listener focusGained() and focusLost() but it is not working. could some body do needful.
    Opening OSK:
    builder = new ProcessBuilder("cmd /c " + sysroot + " /System32/osk.exe");
    Closing Osk:
    Runtime.getRuntime().exec("taskkill /f /im osk.exe");

    You need to start() the ProcessBuilder and you need to split the command like this:
    builder  = new ProcessBuilder("cmd", "/c", sysroot + " /System32/osk.exe");
    builder.start();
    And naturally you should wrap the call in a new Thread or use an ExecutorService to avoid EDT problems.

  • Unable to capture VK_TAB in JTable

    Hi,
    One of our application screen contains a JTable. The problem in this screen is whenever the user press TAB key, the event is not gettting triggered. I have confirmed this by writing s.o.p in the ActionListener class. All the KEYS are getting fired expect VK_TAB.
    The most important point is the same screen works fine in WINDOWS platform i.e VK_TAB is getting triggered. Whereas the same is not working properly in UNIX.
    What could be the reason ? Do i need to make any settings ?
    Please provide me the solution.
    Thanks in advance,
    Karthik
    Message was edited by:
    tkarthikeyan
    Message was edited by:
    tkarthikeyan

    Hi camickr,
    The following was the one, which i referred as ActionListener.
    /* START - SAMPLE CODE BLOCK */
    private void registerTabEvent(){
         new DBPTabListener(this);
    public class DBPTabListener implements ActionListener {
         public DBPTabListener(JTable tabJtable){
              tabJtable.registerKeyboardAction(this,"TAB_KEY",KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0,false),JComponent.WHEN_FOCUSED);
         public void actionPerformed(ActionEvent e)
              System.out.println("key pressed = " + e.getActionCommand());
              if (e.getActionCommand().compareTo("TAB_KEY")==0) {
                   System.out.println("TAB_KEY has been pressed");
    /* END - SAMPLE CODE BLOCK */
    Moreover inputMap solution also doesn't work for us as we use JDK 1.2.2
    Following is the JDK version which we use for our application.
    java version "1.2.2"
    Solaris VM (build Solaris_JDK_1.2.2_10, native threads, sunwjit)
    This version doesn't have setInputMap() & getInputMap for JComponents.
    Could you please help me out.
    Thanks in advance,
    Karthik

  • Displaying the results of an iterator in JTextfields.

    Hi people,
    I have got two methods which basically iterate through statements (forward and back).
    However I have a separate class which is basically the GUI for my program. I want the user to be able to click the next button and it iterates through the list and displays the element in the list in the JTextField.
    The problem I am having is that it will not display the element in the predefined fields, does anyone know how I can go about this? My code for my two methods is below:
    public void MusicNext()
               try
               if(titerator==null)
                   titerator = iList.listIterator();
               if(titerator.hasNext())
                   System.out.println(titerator.next());//Just prints out the iterator atm.
               else
                  titerator = null;
                  MusicNext();
               catch(ConcurrentModificationException ex)
                  titerator = iList.listIterator();
                  System.out.println("Iterator has been reset.");
              public Music MusicNext(String pTitle)
                Music tTitle = null;
             boolean found = false;
                Iterator it = iList.iterator();
                if(it.hasNext() && !found)
              tTitle = (Music) it.next();
              found = tTitle.getTitle().equalsIgnoreCase(pTitle);
                return tTitle;
            public void MusicPrevious()
               try
               if(titerator==null)
                   titerator = iList.listIterator();
               if(titerator.hasPrevious())
                   System.out.println(titerator.previous());//Just prints out the iterator atm.
               else
                  titerator = null;
               catch(ConcurrentModificationException ex)
                  titerator = iList.listIterator();
                  System.out.println("Iterator has been reset.");
               catch(NoSuchElementException ex)
                  //titerator = iList.listIterator();
                  System.out.println("No such element.");
         }I am pretty sure they shouldn't be void but should return an element, but I am really not sure what to return.
    Many Thanks,
    Rob.
    (Sorry I posted this before but I left out alot of detail).

    Don't get or instantiate the iterator in often-called methods.
    It should be get or instantiated as a class global field once and for all.
    Your ListIterator is good for such treatment becuase it can be
    freely scanned backward, while Iterator can't.

  • Initial JTextField value

    Hello!
    I'm puzzled with API docs:
    public JTextField()
    Constructs a new TextField. A default model is created, the initial string is null, and the number of columns is set to 0.
    But when I read the textfield with textfield.getText I do not get a null Object but an empty String object, i.e(""). Why?

    Hmm, very curious.Yes it is, so I looked into it.
    Perhaps the no-arugument constructor creates a default
    Document with an empty string?You are correct sir. In a round about way a character array is created which consists of a single character, that being the null terminator. If your still curious, its done in the GapContent constructor.

  • Can't Copy text unless console is opened before applet with JTextField

    If an applet uses JTextFields, it is impossible to copy text from the console to the clipboard (or anywhere else) if the console is opened after the applet.
    See http://demo.capmon.dk/~pvm/nocopy/nocopy.html for a working applet with source and class file to try it out on...
    So if something bad has happened, and there are hints in the console e.g. a stack trace, it all has to be retyped by hand, since all Copy or export is impossible...
    Does anyone know of a workaround for this? I'd like to be able to e.g. copy stack traces to bug reports.
    Try these test cases:
    * Close all browser windows. Open a browser and visit this page. After the page with this applet has loaded, then open the console with "Tools/Sun Java Console" (or "Tools/Web Development/Java Console" in Mozilla). Select some text in the console. There is no way to put this text on the clipboard; the "Copy" button doesn't work, and neither does CTRL+Insert, CTRL+C or anything else.
    * Close all browser windows. Open a browser window no some non-java page and then open the console with "Tools/Sun Java Console" (or "Tools/Web Development/Java Console" in Mozilla). Then visit this page. Select some text in the console. Now the "Copy" button does work, enabling "export" of e.g. stack traces to other applicaitons e.g. email.
    The difference is which is opened first: The console or the applet. If you look at the very rudimentary Java source code, it is the mere creation of a JTextField is what disables or breaks the Copy functionality.
    I've tried this on Windows XP with IE 6.0 and Mozilla 1.3 and they behave exactly the same. The JVM is Sun's 1.4.2 and I've tried 1.4.1_02 also with the same behavior. I've also tried javac from both 1.4.2 and 1.4.1_01

    hey .. this seems like a bug.. can you please file a bug at
    http://java.sun.com/webapps/bugreport
    thanks...

  • How to capture the event on changing focus from a JTextField?

    Hi All,
    I have got a problem...
    I want to do something (say some sort of validations/calculations) when I change the focus by pressing tab from a JTextField. But I am not able to do that.
    I tried with DocumentListener (jtf01.getDocument().addDocumentListener(this);). But in that case, it's calling the event everytime I ke-in something in the text field. But that's not what I want. I want to call that event only once, after the value is changed (user can paste a value, or even can key-in).
    Is there any way for this? Is there any method (like onChange() in javascript) that can do this.
    Please Help me...
    Regards,
    Ujjal

    Hi Michael,
    I am attaching my code. Actual code is very large containing 'n' number of components and ActionListeners. I am attaching only the relevant part.
    //more codes
    public class PaintSplitDisplay extends JApplet implements ActionListener
         JFrame jf01;
         JPanel jp01;
         JTextField jtf01, jtf02;
         //more codes
         public void start()
              //more codes
             jtf01 = new JTextField();
              jtf01.setPreferredSize(longField);
              jtf01.setFont(new Font("Courier new",0,12));
              jtf01.setInputVerifier(new InputVerifier(){public boolean verify(JComponent input)
                   //more codes
                   System.out.print("updating");
                   jtf02.setText("updated value");
                   System.out.print("updated");
                   return true;
              //more codes
              jtf02 = new JTextField();
              jtf02.setPreferredSize(mediumField);
              jtf02.setEditable(false);
              jp01.add(jtf02, gbc);
              //more codes
              jf01.add(jp01);
              jf01.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              jf01.setVisible(true);
              //more codes
         public static void main(String args[])
              PaintSplitDisplay psp = new PaintSplitDisplay();
              psp.start();
         public void actionPerformed(ActionEvent ae)
              //more codes
    }As you can see I want to update the second JTextField based on some calculations. That should happen when I change the focus from my frist JTextField. I have called jtf02.setText() method inside InputVerifier. But it's giving error...
    Please suggest...
    Ujjal

  • Leaving JTextField with TAB

    A simple question really ... I have a JTextField that I would like to have the user exit from with TAB and get
    the same action as if they had left the field with the
    ENTER key, i.e., I'd like to be able to use the getText
    method to retrieve what the user entered. Currently, with
    no modifcations whatsoever to the JTextField, when I
    invoke getText after the user leaves the field with a TAB,
    getText returns NULL. I've tried just about everything,
    but can't get any of it to work (removeKeyStrokeBinding(), extending JTextField, etc.).
    Thanks in advance for any suggestions.

    As you have niticed this is not such a simple question at all.
    After some experimentation I decided to make the enter key cause the text field to loose focus.
    addKeyListener (new KeyAdapter()
    public void keyPressed (KeyEvent evt)
    int key = evt.getKeyCode();
    if (key == KeyEvent.VK_ENTER)
    transferFocus ();
    Then give the text field a focus listener
    class TextListener extends java.awt.event.FocusAdapter
    public void focusLost (FocusEvent e)
    // evalutate the text using getText()
    Which gets the field's content, validates it and then save it in the appropriate place.
    The advantage to this approach is the whole field edits are always done in the same place (the focus adapter), and the enter and tab actions appear the same to the user.
    The disadvantage is that, unless you know the initial value, you won't be able to tell if the value has changed.
    hope this helpds some.
    Terry

  • Getting values from a JTextField on a JPanel in another class

    I have created a class which extends a JPanel and added a JTextField to it, which has an addActionListener for getting the values typed in the JTextField. I want to use the class created in another class and retrieve the values typed in the JTextField, so how do i go about that? I have the class created below so the problem is how to retrieve content of val[val] in another class?
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class TextFieldChooser extends JPanel{
      int val;
      public TextFieldChooser(String str){
        val = 0;     
        setLayout(new FlowLayout());
        add(new JLabel(str));
        JTextField txtf = new JTextField(5);
        txtf.addActionListener(new TextFieldListener());
        add(txtf);
      }//end constructor     
      private class TextFieldListener implements ActionListener{
        public void actionPerformed(ActionEvent e) {
           val = Integer.parseInt(e.getActionCommand());
      }//end text field listener
      public int getValue(){
        return val;     
    }//class

    The problem is which listener can be programmed to handle the event performed on the class TextFieldChooser in the other class?
    I have created a class which extends a JPanel and
    added a JTextField to it, which has an
    addActionListener for getting the values typed in the
    JTextField. I want to use the class created in
    another class and retrieve the values typed in the
    JTextField, so how do i go about that? I have the
    class created below so the problem is how to retrieve
    content of val[val] in another class?
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class TextFieldChooser extends JPanel{
    int val;
    public TextFieldChooser(String str){
    val = 0;
    setLayout(new FlowLayout());
    add(new JLabel(str));
    JTextField txtf = new JTextField(5);
    txtf.addActionListener(new TextFieldListener());
    add(txtf);
    }//end constructor
    private class TextFieldListener implements
    s ActionListener{
    public void actionPerformed(ActionEvent e) {
    val = Integer.parseInt(e.getActionCommand());
    }//end text field listener
    public int getValue(){
    return val;
    }//class

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

Maybe you are looking for

  • Remit-To Address in OraFin AR Module (Invoice part)

    Hi, I can't figure out how to set up an invoice in AR. Someone was created it before I was starting to work for that company. The template has the same address on the top of a page as remit address with our logo and at the bottom... I was requested t

  • Hiding columns in workbook

    Hi Experts, I am trying to hide 3 columns in a workbook so that the user wont see them when he opens the workbook. what is the best way to achieve this?Thank you

  • How to run small struts module in OC4J embeded in Oracle Jdeveloper 10g

    hi , As i am novice in Oracle JDeveloper10g i tried small module in Struts 1.2, i was able to compile sucessfully all action classes and actionfrom and jsp file , setting required libries . Now when i build my project which under my work space it sho

  • Don't have permission

    I was doing an Airdrop to my wifes macbook air and weird things happened and now the Air has lost all permissions- I can not see any files and cannot reset permissions.  Doing a search it seemed like full reinstall is the only answer... pain in the b

  • How to change country of origin

    During the start up process I accidentally scrolled down to the wrong country of origin. How do I change this?