Trapping ENTER in a JTextField

I have an applet that has a textfield and a submit button....
I want to be able to have the applet run the submit code when the user presses ENTER in the JTextField... like is done on many websites, so the user does not have to manually click 'submit'
How do I trap ENTER?

Darn it....
Here's the thing.. it works, but it compiles two classes, because I'm making a new KeyAdapter...
How do I avoid that? I'm not an expert Java programmer here, I learn as much as I need to write for my website...
Any help /guidance would be appreciated...
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.net.*;
public class applet1 extends JApplet implements ActionListener
    JLabel label1 = new JLabel("Please enter street address of organization here");
    JLabel label2 = new JLabel("Enter unique ID here");
    JTextField textbox1 = new JTextField();
    JTextField textbox2 = new JTextField();
    JButton button1 = new JButton("Submit");
   public void init(){
      Container c1 = getContentPane(); 
       GridBagLayout gridbag = new GridBagLayout();
      GridBagConstraints constraints = new GridBagConstraints();
     '//removed gridbad constraint settings for clarity on this forum
      textbox2.addKeyListener(new KeyAdapter() {
          public void keyReleased(KeyEvent evt)
               if (evt.getKeyCode() == KeyEvent.VK_ENTER)
                         button1.doClick();
          button1.addActionListener(this);
    public void actionPerformed(ActionEvent event)
        int i=0;
        int f=0;
        Date myDate = new Date();
        int day = myDate.getDate();
        int month = myDate.getMonth() + 1;
        int code = Integer.parseInt(textbox2.getText());
        boolean matchFound=false;
        String h = (new String(textbox1.getText()).substring(0,10));
        String str;
        //search database
        try{
            URL url = new URL(getCodeBase(), "address.txt");
            InputStream inStream = url.openStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inStream));
            StringBuffer l = new StringBuffer(10);
            StringBuffer r = new StringBuffer(20);
           //....removed code for clarity on this forum
        catch (Exception e)
            textbox1.setText("Data file missing");

Similar Messages

  • How to trap ENTER Key ????

    I am doing setup wizard in my project. I trapped Enter key, if i press enter key to go to next screen, The behaviour of my wizard is unpredictable.

    The same goes if you have a text field(s):
    final JTextField tname = new JTextField(30);
    final JButton ok = new JButton("OK");
    tname.setText(nodeName);
    tname.setMinimumSize(new Dimension(50,10));
    tname.setSize(new Dimension(70,10));
    tname.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {  //action on JTextField - pressing Enter
    ok.doClick(); //or whatever you like
    cp.add(tname);
    cp.add(ok);
    ...

  • How to limit the number of characters entered in a JTextfield???

    Hello there,
    I have created a Text box using swing component JTextField and I want to limit the number of characters entered to 8 characters..how do i proceed with that?
    Thanks in advance!
    Joe

    Ty out this
    import com.sun.java.swing.text.*;
    //import javax.swing.text.*;
    public class JTextFieldLimit extends PlainDocument {
    private int limit;
    // optional uppercase conversion
    private boolean toUppercase = false;
    JTextFieldLimit(int limit) {
    super();
    this.limit = limit;
    JTextFieldLimit(int limit, boolean upper) {
    super();
    this.limit = limit;
    toUppercase = upper;
    public void insertString
    (int offset, String str, AttributeSet attr)
    throws BadLocationException {
    if (str == null) return;
    if ((getLength() + str.length()) <= limit) {
    if (toUppercase) str = str.toUpperCase();
    super.insertString(offset, str, attr);
    import java.awt.*;
    import com.sun.java.swing.*;
    //import javax.swing.*;
    public class tswing extends JApplet{
    JTextField textfield1;
    JLabel label1;
    public void init() {
    getContentPane().setLayout(new FlowLayout());
    label1 = new JLabel("max 10 chars");
    textfield1 = new JTextField(15);
    getContentPane().add(label1);
    getContentPane().add(textfield1);
    textfield1.setDocument
    (new JTextFieldLimit(10));

  • Press enter on a JTextField

    Hi,
    i have a JTextField a class that listenes to events coming from it. I changed it's text and now i have to press enter. How can i do it by program?
    I tried
    jTextField.postActionEvent();but it gave me an ArrayIndexOutOfBoundsException.

       //... in your main class ...
       public YourMainClass() {
          // Create GUI
          initComponents();
          // Run your code
          doSomeCode();   // There you are
          // And then
          showGUI();     
       // Creates the GUI
       public void initComponents() {
          // Whatever...
          JTextField URL = new JTextField();
          URL.addURLLIstener(this);
          URL.setText("http://forum.java.sun.com"); // will call the action
       // Shows the GUI
       private void showGUI() {
          yourMainFrame.setVisible(true);   // or whatever...
       // This method is called from the event generated by ENTER
       public void URLActionPerformed(java.awt.event.ActionEvent evt) {
          doSomeCode();
       // This method is called from the event generated by ENTER or by the program itself
       private void doSomeCode() {
          //... some code ...
       }

  • Trap enter key? please help

    how will i trap the enter key?
    example: jTextField1 has the focus or insertion point, if the user presses the enter key from the keyboard the next focus or insertion point will be on jTextField2.
    thank you in advance.
    killuasoft

    Swing related questions should be posted in the Swing forum.
    By default a "Tab" key is used as the "focus traversal key". You can also add the "Enter" key as a focus traversal key to any given component.
    I'll let you read the Swing tutorial for information on how to do this.

  • Entering data from JTextfield into Database--- Techniques

    hello friends,
    I am developing an application where i want to insert data from my Jtextfield to data base.
    I know all the procedure but i am confused.
    I have 11 fields in my frame, out of which 3 are compulsory. rest are optional.
    i am validating those 3 compulsory fields.
    so i have to generate run time insert query, depending on the fields Populated.
    Also i have my connection to db in other class. that not a problem as i can call a method. But how to pass so many arguments. when no. of arguments also change runtime.

    Thanks Aniruddha,
    But i didn't understand what u said.
    I think I will do as following
    1. check the populated field.
    2. if yes then insert them into a hashmap .
    key = field name, value = field value
    3. send the hash map as the argument to function connecting my db.
    4. retrieve the fields. and dependingly make a prepared statement for insertion.
    5. as some of my fields are integer, convert them to int . then set them
    6. then execute the query.
    if u have any other suggestions please tell....

  • How do I trap 'enter keypress' after certain presses and disable further typing in atext area?

    my textarea needs to be restricted to 16 lines no matter
    what. I have used the change listener and tried getting the number
    of 'enter' clicks. But how do i lock the textarea such that, the
    user cannot type anything further, but can edit what all he has
    written.
    I can disable the textarea but this will not allow editing.
    Can anyone provide me with the thing i need? Hope the idea is
    clear.
    Regards
    Roshan

    use a regular input textfield and its bottomScroll and
    maxscroll properties.

  • How to make buttons enabled after the data is entered in JTextField?

    I got a JTextField. I want to test the entered data in JTextField is eight length. If the data is of length eight then i want to enable two buttons. How to make it enable? I am getting the length eight, but the buttons are not enable. What listeners I have to use.
    Can anybody help me out.
    Thanks for your help in advanced.

    Create a class that extends KeyAdapter. Add a field that is an array of buttons. Override the keyTyped(KeyEvent e) method to use getSource() to access the text area, check the length of the text, and if > 8, go through the array and enable the buttons in the array. Then, when you create the text area, create an instance of your listener, passing it an array of the two buttons you want to enable, and then use addKeyListener(yourKeyListener) to add your key listener to the text area.
    Doug

  • Swing JTextField becomes slow after entering large unicode text.

    Hi All,
    We are developing a Indian s/w in Java, where we are using Indic InputMethods for taking user input in Hindi.
    Things works fine for small amount of text entered into a JTextField, but when we try to enter large amount of hindi text (let's say 100+ lines), it becomes slow bit by bit, ultimately giving impression of a application hang.
    We are using linux OS (Mandrake 10.1) on intel boxes with 265 MB RAM.
    Can any one help?
    Thanks in advance.
    Sanjeev

    Hmm .. I think I may be aware of that cutting edge application ;)
    Kindly let me know the solution.
    Abhi.

  • Capture special key struck within a JTextField

    Hello I'm trying to create a customized JTextField that does the following ...
    1. accepts only numbers - usually in the format of x.xx
    2. capture when a decimal key (.) is hit and move the cursor to the other side of the decimal and edit only that side
    Item 2 is really where I'm lost. Is there a way to listen for a 'key' to be struck and then within the JTextField place the cursor? ... I've done it before within a document with setcaret or something like that but not sure about this ....
    Help!

    Is there a way to
    listen for a 'key' to be struck and then within the
    JTextField place the cursor?When I did something like this I used a regular JTextField and overrode the processKeyEvent(KeyEvent e) method. That method gets called 3 times per keystroke (key pressed, key released, key typed) but I was only interested in key pressed. So if (e.getID() != KeyEvent.KEY_PRESSED) then super.processKeyEvent(e) and get out. After that, you're in complete control of what gets entered into the JTextField. If you don't call super.processKeyEvent(e) then the character won't be entered, so that way you can "trap" certain keys and react accordingly by setting the caret position, etc.

  • Weird problem in JTextFields ..!!

    Hi thr,
    It seems a buffer is held within , when a text in unicode is entered
    in the JTextFields,
    Following is the code snippet from the Class which overrides PlainDocument class
    and attached to a JTextfield
    public void insertString(int r_iOffset, String r_stNewText,
    AttributeSet r_objAttr) throws BadLocationException
         System.out.println( r_stNewText );
    int Entered = (int) r_stNewText.toCharArray()[ r_stNewText.length()-1 ] ;
    if (Entered > 255)
    r_stNewText = "";
    r_objAttr = null;
    return;
    // Further processing for ascii text
    Assuming two keyboard layouts are setup in the OS , one English and other Japanese.
    When the textfield is in focus , the OS keyboard layout is changed to japanese
    by alt+~ keys , and all the japanese keys input are succesfully blocked, but when keys "\\"
    is entered , the hidden buffered string is displayed in the Jtextfield, and all the
    keys therafter has only ascii values !! , and there by bypassing the constraint.
    When System.out is used to debug , each and every character , we can see the new string
    passed , is continually is increasing with evry new charecter , even though we make it
    as empty string.
    can somebody comment this issue ?
    cheers,
    thanks (ver much ) in advance.

    Any suggestions , at least ?

  • JTextField and JPasswordField

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

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

  • Exact length of a JTextField

    Hi,
    I have a program where I read integer value from the database & create a JTextField on the GUI side. Number of characters user should enters in the JTextField should be equal to the value I have got from the database & only JTextField with columns 10 should be displayed
    e.g If I get integer value 10 , I create a JTextField & call setColumns(10);
    here is my program:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    public class test extends javax.swing.JFrame
         public test(String title) throws Exception
              super(title);
              this.setLayout(new java.awt.FlowLayout());
              javax.swing.JTextField tf = new javax.swing.JTextField();
              tf.setDocument(new LimitDocument(2));
              tf.setMargin(new Insets(0,0,0,0));
              tf.setColumns(2);
              this.getContentPane().add(tf);
         public static void main(String[] args) throws Exception
              test t = new test("Test");
              t.setSize(new java.awt.Dimension(500,500));
              t.setVisible(true);
    //Inner Class
    class LimitDocument extends PlainDocument {
    private int limit;
    public LimitDocument(int limit) {
    super();
    setLimit(limit); // store the limit
    public final int getLimit(){
    return limit;
    public void insertString(int offset, String s, AttributeSet attributeSet) throws BadLocationException {
    if(offset < limit){ // if we haven't reached the limit, insert the string
    super.insertString(offset,s,attributeSet);
    } // otherwise, just lose the string
    public final void setLimit(int newValue) {
    this.limit = newValue;
    after running this propgram , I found that even if user is able to enter only the number of characters specified , but still JTextField leaves some SPACE after number of characters entered
    In above example , I have Limit number of characters to be entered to 2
    but after entering 2 chars , it showd some SPACE in the end, I dont want to show this SPACE to the user.
    Pleae guide me
    Thanks in advance
    NJP

    In above example , I have Limit number of characters to be entered to 2
    but after entering 2 chars , it showd some SPACE in the end, I dont want to show this SPACE to the user.
    Type "mm" into the field and you'll see that the string fills the box. Naturally, with a proportional font, "ii" etc won't.
    By the way, the logic in your LimitDocument is flawed: as an illustraction, paste a string in there - or type two characters, move the cursor left and carry on typing.

  • JTextField max length, JTextArea automatic scrolling

    i cant find how to do 2 things,
    i would like to limit the size of the text entered in a JTextField
    i could probably do this by making its KeyListener trim off the extra from getText() and use setText(whateverIsLeft) but i was hoping there was a better way of doing this with something that is already there as this is a lot of work considering soemoen could just hold down a button and it would have to do it several times a second
    also i need to set a JTextArea inside a JScrollPane so that when new text is appended to it, it scrolls the jtextpane down to the bottom, i could just make it write it at the top instead of appending it to the bottom but i REALLY dont want to =p
    thanks

    i've got the same probelm with the JSrollPane
    this is what i usually do
    public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
    ta.setText(ta.getText() + "\n" + tf.getText());
    tf.setText("");
    jsp.setPreferredSize(new Dimension(0, 0));
    jsp.revalidate();
    where tf is a JTextField, ta is a JTextArea and jsp is the JScrollPane in which ta is added
    this worked great so far but when i try to set it through this
    BufferedReader in = new BufferedReader(
    new InputStreamReader(port.getInputStream()));
    it just refuses to work and i haven't got the slightest clue why ...
    here is the Thred i use :
    private class Reciever extends Thread {
    private BufferedReader in = null;
    private String change = "";
    public String getChange() {
    return change;
    public Reciever() {
    Socket port = conMan.getPort();
    try {
    in = new BufferedReader(new InputStreamReader(port.getInputStream()));
    } catch (IOException e) {
    e.printStackTrace();
    System.err.println("[system] : I/O Exception ");
    } catch (NullPointerException e) {
    e.printStackTrace();
    System.err.println("[system] : Null Pointer Exception ");
    start();
    public void run() {
    for (; ;) {
    try {
    change = in.readLine();
    setText(change);//this is the method that sets the text in the JTextArea
    } catch (SocketException e) {
    Main.getStatus().setMsg("Closed " + conMan.getPort());
    return;
    } catch (IOException e2) {
    e2.printStackTrace();
    return;
    and the setText(); method :
    public void setText(String txt) {
    if (txt != null && !txt.equals(null) && !txt.equals("")) {
    receive.setText(receive.getText() + "\n" + txt);
    i tryed all of the above ways nothing works so far ...

  • JTextField.setDocument(null) in 1.3 and 1.4

    Hi
    We are upgrading to Java 1.4 from 1.3. The method JTextField.setDocument(doc) works fine in 1.3 when 'doc' is null. But in 1.4, it throws null pointer exception. I am not using JTextField directly, I am using a derived class of JTextField. 'doc' is a class var that implements interface Document.
    Can anybody tell how to solve this problem in 1.4?
    Thanks

    Well, a Document is used to store the text entered into the JTextField. If the Document is null then you can't store any text. If you can't store any text then you don't need the JTextField. If you don't need the JTextField, remove it from the screen.
    Of course a simpler solution would be to not set the Document to null. Why do you set it do null?

Maybe you are looking for

  • Help! can't see CR2 thumbnails In Bridge

    what can I try? I cannot see the thumbnails in Bridge but can go into CS4 and open them up no problem I shoot Canon 5d Mark II I downloaded Camera Raw 5.3 works fine for my regular 5D but no on the new Mark II any suggestions? thanks!

  • Help with STDIN

    Sorry if this is a dumb newbie question, but how does one go about capturing command line input and assign it to a string? Say if I typed in "My dogs name is Bingo", how do I assign that to a string strDogName? I've looked in 3 Java books, as well as

  • Batch File Won't Run as a Scheduled Task

    I have two batch files that won't run as scheduled tasks but run perfectly fine when I double-click them. I've already set them to run with highest privileges, the account running them is an administrator account, that account has full permissions to

  • How to update JAR through URL

    Hello, I have implemented a standalone JAR file for windows, that runs in a system tray for our users to use. The application is using URL class to connect to our server and feed information. Trouble is that from time to time it may be necessary to u

  • Need to change Adobe PDF Port.....where??

    When I select File/Print and select the Adobe PDF printer I get a message saying the PDF printer is not "bound" to Adobe PDF port. It wants me to change the Port to Adobe PDF Port but I can't find where to change it. Anyone know where to find the por