JTextField array

I�m using an array of jTextFields within a pane and I want to know which of this jTextFields was edited. I used the getSource method but I cannot interpret the data since I don�t get the index of the jTextField.

Or, if you really do want to know which field was editted, here's one possible solution
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
public class JTextFieldTester extends JFrame implements ActionListener{
    JTextField[] fields;
    public JTextFieldTester() {
        JPanel mainPane = (JPanel) getContentPane();
        mainPane.setLayout(new GridLayout(5,0,5,5));
        fields = new JTextField[5];
        for (int i = 0 ; i < 5 ; i++){
            fields[i] = new JTextField(20);
            fields.setName(""+i);
fields[i].addActionListener(this);
mainPane.add(fields[i]);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
public void actionPerformed(ActionEvent e) {
Component comp = (Component) e.getSource();
if ( comp instanceof JTextField) {
System.out.println(comp.getName());
public static void main(String[] args) {
new JTextFieldTester();
This depends on user hitting enter after editting but you can do simular things with other types of events. The major point is that by assigning a name to each field you can rapidly determine which field fired the event. This is probably far more efficient for very large arrays of tields.
Good Luck
DB

Similar Messages

  • JTextField array help

    Hey guys,
    I'm working on a java GUI right now and I've come up with a problem, hopefully you guys can help.
    I have a page that contains 50 text fields in 2 columns, so instead of making 50 lines of text field code, I decided to make an array of text fields and a for loop to cycle through each one (setting sizes, colors, editable, etc). Now the problem I'm running into is I will later down the road like to setText in these but it will be very cumbersome to have to call them by the arrayName[index #]. Just so I can better express what I mean heres is how I have to call each text field right now:
    arrayName[0].setText("1");
    arrayName[1].setText("2");
    This is how I'd like to be able to call each field:
    1stTextField.setText("1");
    2ndTextField.setText("2");
    Is there anyway I can make it so I can make an array of JTextFields and still be able to call an individual text field inside the array by name? If not, is there a way to point to another variable such as making
    1stTextField = arrayName[0] ;
    2ndTextField = arrayName[1];
    Thanks for the help guys.

    50 text fields in 2 columns... why not just use a JTable?
    Is there anyway I can make it so I can make an array of JTextFields and still be able to call an individual text field inside the array by name?Try a HashMap
    is there a way to point to another variable such as making
    1stTextField = arrayName[0] ;
    2ndTextField = arrayName[1]; Yes, exactly as you coded it up

  • JtextField arrays newbie help

    Probem here
    import java.awt.*;
    import javax.swing.*;
    public class Display extends JFrame
    public static final int width = 500;
    public static final int height = 200;
    JPanel p;
    JTextField b[];
    for (int i = 0; i < 3; i++)
    b[i] = new JTextField();
    public Display()
    p = (JPanel) this.getContentPane();
    p.setLayout( new BorderLayout() );
    p.add(b[0], BorderLayout.NORTH);
    p.add(b[1], BorderLayout.CENTER);
    p.add(b[2], BorderLayout.SOUTH);
    for (int i = 0; i < 3; i++){
    b.setFont(new Font("Serif", Font.BOLD, 30));
    setSize(width, height);
    setVisible(true);
    public void paint(Graphics g){
    super.paint(g);
    However whenever i try to compile i always have an error of illegal start of type below for this part of code
    JTextField b[];
    for (int i = 0; i < 3; i++)
    b[i] = new JTextField();
    Please advise thanks!

    Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
    http://forum.java.sun.com/help.jspa?sec=formatting
    "Code" belongs in the constructor or a method.
    Only variables can be defined outside of the constuctor or methods.
    Also, why are you overriding paint(...)? Have you read the Swing tutorial for working examples?
    http://java.sun.com/docs/books/tutorial/uiswing/TOC.html

  • Jtextfield and array

    Hi ALL
    I'm trying to create a Jtextfield but i also want to have an array on the Textfield, is their a simple way of doing this. I have tried but failed so can anyone help please.
    wen i try i get nopointerexception (frustrating)

    yea i tried
    int i;
    for(i=0; i < array.length; i++)
    JTextField[] array = new JTextField;
    don't compile                                                                                                                                                                                                                                               

  • Using JTextField as an array.

    Hi I would like some help with createing a JTextField array. I cant seem to find anything wrong with my code but it keeps giving me an Error.
    Error Message: java.lang.ArrayIndexOutOfBoundsException
    This is what my code looks like.
    //Declare Component
    JTextField Length[];
    for(int i = 0; i < 5; i++)
    Length[i] = new JTextField("", 5);
    c.gridx = i;
    c.gridy = 0;
    panMiddle.add(Length, c);
    Please let me know what im doing wrong.

    You seem to have several things in error. Here is one way to do this. It creates an array of 4 JTextFields. A frequent beginner's mistake is to initialize the array but to forget to initialize the individual items, something that must be done if the items are objects (i.e., are not primative types such as int).
    public class MyClass extends JPanel
        private JTextField[] textFieldArray = new JTextField[4]; //array declared and initialized
        public MyClass()
            for (int i = 0; i < textFieldArray.length; i++)
                textFieldArray[i] = new JTextField(12); //init each array item here
                panMiddle.add(textFieldArray); // add it to my form here.
    Message was edited by:
    petes1234

  • How can I generate a component array using JBuilder?

    Now I'm using JBuilder to design my program's GUI. I wanted a JTextField array like this:nums[0]~nums[2].So I draged three JTextFields into the container at JBuilder's design view. But when I set the names of them as nums[x](x=0,1,2). I got a Error Message. It told me that I used a illegal name. How should I do, please?
    thank you a million!

    The DIO ports on a MIO will not satisfy your needs (unless you move to LV RT).
    They do not support buffered outputs.
    Your update rate (how often you can set the port and clear it) is going to be limited by how fast (a-hem slow) windows will let you iterate,
    and,
    be non-determinstic.
    You could use,
    1) LV RT with the existing board, or
    2) FieldPoint PWM module, or
    3) Arbitrary waveform generators, or
    4) HS DIO board, or
    5) use the analog output of your baord where you que-up a 0 -5V waveform of the proper shape (i.e. make sure that the duty cylce fraction of the update values are high, the rest low).
    This is just to get a PWM signal out.
    Now there is another issue. Determinism. How often do you plan on reading your inputs and making a change to you
    r PWM? If you plan on doing more often that 10/second, write your code to handle windows going out to la-la land when you expect it to be working.
    Can you tell I like LV-RT.
    I hope my ramblings have helped.
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • How to �extend� a JAVA class array?

    Hi,
    I would like to do the following :
    // I know this is not possible
    public class MyModel extends JTextField [] [] {
         class body, behaves as a JTextField array
    public class MyAppUsingMyModel {
         MyModel myMod01 = new MyModel (int01, int02);
    } instead of
    public class MyAppUsingAnArray {
         JTextField [] [] myod01 = new JTextField (int01, int02);
    } Reason:
    The application programmer doesn�t need to know the real model structure
    I�d like to change MyModel.java later on when there will be new needs, but don�t change the API
    I am looking for a kiss solution (keep it simple and stupid), so no academic thing like e.g. a factory pattern.
    Is there a (general) simple solution I was too blind to recognize?
    Thanks
    Michel

    1) The "factory" pattern is very much not some academic notion!
    2) The way you're currently doing it is preferable. Google "favour composition over inheritance" for more information
    Basically, the fact that there is an array of (for instance) JComponents is an implementation detail, keep it hidden. Best thing is to write the class (or even an interface) that exposes exactly the methods you think you need, and use whatever you need underneath to make them work

  • Use MousePressed with JTextField

    Hi all,
    I am now facing a problem with the MouseEvent on JTextField.
    I used loop to create a JTextField array to store something. And now, if I click the TextField, the field will change color and a new value will be stored in that textfield array. But I would like to know how to indicate that mouse press action is related to which textfield? Should I use .getSource() ?
    Thanks!
    CK

    Hallo,
    I think that you have posted this in the wrong forum.

  • Array of JPanel and Array of JTextField?

    Hi,
    I try to create array of jpanel and inizialize it in "for" , but when run it give me this error message:
    "Exception in thread "main" java.lang.NullPointerException"
    at the row: "panInsCantante.add(panInsNCC);"
    why?
    (ps. i tried in another code to create array of jtextfield and it give me same error message..)
    here part of code :
          JPanel [] panInsCantante = new JPanel[3];
          for(int i=0;i<=N;i++){
               JPanel panInsNCC= new JPanel();
               panInsNCC.setLayout( new GridLayout(3,1) );
               panInsNCC.add(campoTesto1);
               panInsNCC.add(campoTesto2);
               panInsNCC.add(campoTesto3);
               //panInsCantante[i] = new JPanel();
               //panInsCantante.setLayout( new GridLayout(1,1) );
         panInsCantante[i].add(panInsNCC);

    a question (theoric...)A VERY important question I may add.
    what's the difference between ..
    this instance :
    JPanel [] panInsCantante = new
    JPanel[3];This declares and initializes the array itself, nothing more. No JPanels have been initialized as yet, just the array. It's as if you have now built the shelves to hold the books, but you have no books up there yet...
    and this instance of panInsCantante? :
    panInsCantante[i] = new JPanel();and this initializes each JPanel in the array as you loop through the array. .... and now you have filled the shelves with the books and can use the books.
    You will need them both.
    In all likelihood, the reason for your confusion is that all of your previous arrays were arrays of primative types: int, double, float, and char. In this situation, you don't need to go through the step of initializing the variable.
    But now you are faced for the first time with an array of reference type, an array of Objects. This is a different situation and requires the steps that we have gone through.
    Message was edited by:
    petes1234

  • Array of JTextFields

    If I have an array of JTextFields e.g. tf = new JTextField[i] for 1<i<46, how can I get the cursor to automatically tab to the next field once a string of numbers has been inputted to one of them. I'm trying to design a Scan Frame for barcodes and I want to be able to scan the first one and automatically be able to scan the next and so on
    thanks
    I can show you code if you need it

    You can set actionListener to forcus on the JTextField[0] and make a function to do the action and then use grabforcus to move cursor to the next JTextField. For example
    JTextField exam [] = new JTextField[3];
    the actionperform function is here
    if(e.source == exam[0])
         dosomething;
         exam[1].grabforcus;//you may check the spelling for sure
    and so on for the next array index.
    Hope solving your problem.

  • Initialise a array of JTextFields

    I need to access an array of JTextfeilds publically because I need to reference it within a different method. But the problem is that I can only initialise it later because it depends on user input.
    How can I set it up publically but initialise the size later.
    for example
    constructor:
    public JTextField text[] = null;
    public main method()
    initialise(int R)
    public void initialise(int p)
    text[] = new JTextField[p];
    }

    public class BrokenDesign
      public JTextField[] fields;
      public BrokenDesign()
        fields = new JTextField[0];
      public void onUserInputInitialiseXJTextFields(int x)
        fields = new JTextField[x];
        for (int k = 0; k < x; k++) {
          fields[k] = new JTextField();
    }

  • Custom Document + Array of JTextFields

    Hi,
    I read through the tutorial and managed to get a Custom Document going for my JTextFields (of which i am using quite a few =))
    To cut my code down and aid getting data back from the textfields, I changed them from a page of declarations to a couple of grouped arrays.
    However, now that I have done that, whenever i change the text in one of the textfields, the text in all the textfields in the array change...
    I'm assuming it's something to do with the super.insertString(offs, str, a); that is being called from the Custom Document, but I'm not sure how to fix it up...
    Any help would be most appreciated.
    Cheers
    Andy

    whenever i change the text in one of the textfields, the text in all the textfields in the array change...This means that each text field is using the same document. It's hard to help since you don't post any code. Your code should look something like:
    textField1 = new JTextField()
    textField1.setDocument( new CustomDocument() );
    textField2 = new JTextField()
    textField2.setDocument( new CustomDocument() );

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

  • Add mouselisteners to an array of JTextField objects

    Hi. I am writing a program to emulate a calendar and I though I would do it for each day I would have a JTextField hold the contents of the field. A user could set the event for that time by clicking on the corresponding textfield. I'm still working on saving to file and whatnot, but my question is how can I add motionlisteners to an array of JTextFields?
    Here is what I've written so far:
    for(JTextField c: event)
                   c.addMouseListener(new MouseAdapter()
                   public void mousePressed(MouseEvent ev)
                        String in = JOptionPane.showInputDialog("Please Enter event for this time");
                        c.setText(in);
              }I run into I immediate error regarding setting the contents of c within an innerclass. I know it wouldn't be an issue if c was defined as a private variable, but I don't know if that is permitted for the for each loop. Also I get another error I'm not sure of, something about this can only work if the source level is 5.0 which I don't know what that means.
    also outside of this method I've set the object event:
    private JTextField[] event = new JTextField[168];any input would be appreciated.

    When you have an inner class, you can only access variables that are declared final. So, this should work:
    for (int i=0; i <168; i++)
              final JTextField tempEvent = event;
              event[i].addMouseListener(new MouseAdapter()
                   public void mousePressed(MouseEvent ev)
                        String in = JOptionPane.showInputDialog("Please Enter event for this time");
                        tempEvent.setText(in);

  • 2 parts: 1) integer array to string 2) string out to a jTextField

    I am completely new to Java and Netbeans, but I'm writing my 1st
    application that takes a "hex" character input from a jTextField,
    then converts it to an "binary" integer array. I then do a lot of bit
    manipulation, and generate a new "binary" integer array.
    String myhex = jTextField1.getText();
        int len = myhex.length();
        int[] binarray = new int[len*4];
            for (int i = 0; i < len; i++) {
               if (myhex.charAt(i) == '0'){
                  binarray[4*i]=0;
                  binarray[4*i+1]=0;
                  binarray[4*i+2]=0;
                  binarray[4*i+3]=0;
               else if (myhex.charAt(i) ==
               // repeat for '1 to 9' and 'a-f/A-F'
               // generate new integer array(s) using various bits from binarrayI realize it might not be the best way to do the
    conversion, but my input can be of arbitrary length,
    and it is my first time trying to write Java code.
    All of the above I've completed and it works...(thanks Netbeans
    for making the gui interface design a real breeze!)
    So I end up with:
    binarray[0]=0 or 1
    binarray[1]=0 or 1
    binarray[2]=0 or 1
    binarray[n]=0 or 1
    Where n can be any number from 0 to 63...
    I then manipulate the bits in binarray creating a new integer array
    and for the sake of expediency let's call it "newbinarray".
    newbinarray[0]=0 or 1
    newbinarray[1]=0 or 1
    newbinarray[2]=0 or 1
    newbinarray[n]=0 or 1
    Where n can be any number from 0 to 63...
    I first need to know how to convert this "newbinarray" integer array to a string.
    In the simplest terms if the first three elements of the array are [0][1][1],
    I want the string to be 011.
    Then I want to take this newly formed string and output it to a jTextField.
    string 011 output in JTextField as 011
    I've scoured the net, and I've seen a lot of complex answers involving
    formatting, but I'm looking for just a simple answer here so I can finish
    this application as quickly as possible.
    Thanks,
    Thorne Kontos

    Here's an example, not using NetBeans:
    import javax.swing.*;
    public class TextDemo extends JPanel
        public TextDemo()
            int[] newbinarray = {0, 1, 1};
            StringBuffer sb = new StringBuffer();
            for (int value : newbinarray)
                sb.append(value);
            String st = new String(sb);
            this.add(new JTextField(st));
        private static void createAndShowGUI()
            JFrame frame = new JFrame("TextDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new TextDemo());
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args)
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }

Maybe you are looking for