Listening to MouseEvents in an array of JTextFields

// BlockWerteFeld is a JTextFiled
private BlockWerteFeld wertedArray[]= {
        null,null,null,null,null,null,
        null,null,null,null,null,null,
        null,null,null,null,null,null,
        null,null,null,null,null,null
for ( int i = 0 ; i <= GESAMT_SUMME ; i++ ){
            werteArray = new BlockWerteFeld(
"tfWert" + i,
i * Jobs.BLOCK_HOEHE,
Jobs.BLOCK_LINKS+ Jobs.BLOCK_BREIT
// some more settings
werteArray [i].addMouseListener(eventHandler);
panelBlock.add( werteArray[i]);
private EventHandler eventHandler = new EventHandler();
// inner Class
class EventHandler implements
java.awt.event.ActionListener,
java.awt.event.KeyListener,
java.awt.event.MouseListener{
public void mouseEntered(MouseEvent e) {
for ( int i = 0; i < werteArray.length; i++ ){
if ( e.getComponent() =??
// more Events handled
How can I know, that "werteArray " has been mouseEntered, and which element ?
TIA Hanns

Hi,
You have already added the listener (you did that in the first loop).
Your second loop should have this
for ( int i = 0; i < werteArray.length; i++ ){
   if ( e.getComponent()  = werteArray) {
//werteArray[i] is the source
Kaj

Similar Messages

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

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

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

  • Arrays with JTextField

    JTextField[] textfields = { JTextField inTroop  = new JTextField( 7 ), JTextField inTank  = new JTextField( 7 ) }; im getting an identifier expected error cxan someone point out what i am doing wrong please?

    is there anyway that i could put on a identifier ? sort of like
    JTextField[] textfields = {intank =  new JTextField( 7 ), introop = new JTextField( 7 ) };

  • 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                                                                                                                                                                                                                                               

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

  • Listen for change in JTextField

    I would like to write an event listener to listen for any changes made to a JTextField. Normally I would think that keyListeners would do the trick except that the contents of this field can be altered by the application itself, and I would like to trap those changes too.
    Does anyone know of an event listener that listens for any changes made in the text of a JTextField, regardless of how those changes are made?

    use DocumentListener
    for more info see http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#doclisteners

  • JTextField [] and MouseEntered

    Hello
    I know this type of question has been asked in the forums before, but might is kind of different...i think.
    I have an array of JTextFields and i want each of there color to turn to GRAY when the mouse is on top of them.
    So if mouse is on top of TextField1 then only TextField1 turns GRAY.
    my Current mouseEntered() method is this
    public void mouseEntered(MouseEvent me)
                 for (int i=0; i < nasdaqTFs.length; i++){
                nasdaqTFs.setEditable(false);
              nasdaqTFs[i].setBackground(Color.GRAY);
    This, obviously, turns ALL the TextFields to GRAY when the cursor is in the Panel. So cursor can be anywhere and they all turn GRAY.
    So the question is...how do i find out when the Cursor is on the Specific TextField.

    Learning from earlier today This time i did write a Short Example of what i want done.
    Maybe this time i didnt do a bad job at it
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Listener extends JFrame implements MouseListener
         JTextField t;
         JTextField t1;
         public Listener ()
              super ("test");
              Container c = getContentPane();
              c.setLayout(new BorderLayout());
              t = new JTextField(4);
              c.add(t, BorderLayout.NORTH);
              t1 = new JTextField (4);
              c.add(t1, BorderLayout.SOUTH);
              addMouseListener(this);
              setVisible(true);
              setSize(300,300);
              MouseMotionListener don = new MouseMotionAdapter(){
              public void mouseEntered(MouseEvent me) {
                   System.out.println("Enterd)");
                 me.getComponent().setBackground(Color.GRAY);
              t.addMouseMotionListener(don);
              t1.addMouseMotionListener(don);
         public static void main (String args[])
              Listener l = new Listener ();
           public void mouseEntered(MouseEvent me)
             /*JTextField tf = (JTextField) me.getSource();
             tf.setBackground(Color.GREEN);*/
                me.getComponent().setBackground(Color.GREEN);
           public void mouseExited(MouseEvent me)
             /*JTextField tf = (JTextField) me.getSource();
             tf.setBackground(Color.white);*/
                me.getComponent().setBackground(Color.WHITE);
           public void mousePressed(MouseEvent me){}
           public void mouseReleased(MouseEvent me){}
           public void mouseClicked(MouseEvent me){}
    }This GUI wont change colors of TF's either. However when i move around the GUI i see somethin Green flickering!

  • Using Event Structures with Array of Clusters

    Using LabVIEW 8.5
    Hi all,
    I'm trying to convert an existing application to one that can be used
    through a touch screen. I updated the UI and added an event structure
    to listen for mouse ups on controls that require a HMI keyboard or
    numpad to show up. Although I've been programming for a while, I'm new
    to LabVIEW and am struggling with a problem:
    Is there any way to have an event case listen to an event within
    arrays? I've seen a few examples on the forums, but they all start with
    breaking up the arrays into individual variables. Using the variables,
    they build arrays. This seems pretty tedious, and I'm pretty sure I
    can't apply it to one of my arrays. Essentially, I just want to know
    which cluster in which array the user has clicked on, so I can open the
    HMI keyboard or numpad and send the text to that cluster. In my watered down app (Array of Clusters.vi), I've put 3 arrays of clusters and a few stand-alone controls to give you guys an idea of what I'm taking about.
    BTW, I'm using the HMI Keyboard and Numpad built by the Beta Community (http://decibel.ni.com/content/docs/DOC-1062) and modified it to add a "Clear" button to the keyboard and numpad. Please let me know if I implemented this in the best way.
    Thanks for the help,
    Kunal
    Message Edited by bhatiak on 08-04-2008 03:55 PM
    Attachments:
    Array of Clusters4.llb ‏274 KB

    My old tic tac toe example shows how to determine which square of a 2D array has been clicked.
    http://forums.ni.com/ni/board/message?board.id=170&view=by_date_ascending&message.id=247044#M247044
    You probably can adapt some of it for the arrays on the right. If the array can be scrolled, you also need to account for the "indexvals" offset.
    The Layers controls is easiest, because you only show one element. Just read the "index vals" property to get the array element and parse the coordinates to get the cluster element.
    btw: the small while loop on the right serves no purpose at all and acts just as a CPU burner. You can delete it without any change in functionality. Is there anything else to it?
    LabVIEW Champion . Do more with less code and in less time .

  • MouseEvents and KeyEvents in the same form is not working

    Hello!
    I'm newbee in java althought i've bee programing for a long time in other languages, C, C++ wich i'm proud of.
    Now i land on java and there are a lot of cuestions (nothing that cant be solved by trying and reading).
    But today i hitted my head against all posible solutions and nothing (but bad mood) came out.
    The code with trouble is this...
    public class NewJFrame extends javax.swing.JFrame
        public NewJFrame()
            initComponents();
        private void initComponents() {
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            addKeyListener(new java.awt.event.KeyAdapter() {
                public void keyPressed(java.awt.event.KeyEvent evt) {
                    formKeyPressed(evt);
                public void keyReleased(java.awt.event.KeyEvent evt) {
                    formKeyReleased(evt);
                public void keyTyped(java.awt.event.KeyEvent evt) {
                    formKeyTyped(evt);
            jButton1.setText("jButton1");
            jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    jButton1MouseClicked(evt);
            pack();
        private void formKeyTyped(java.awt.event.KeyEvent evt) {
            Integer i = evt.getKeyCode();
        private void formKeyPressed(java.awt.event.KeyEvent evt) {
            Integer i = evt.getKeyCode();
        private void formKeyReleased(java.awt.event.KeyEvent evt) {
            Integer i = evt.getKeyCode();
        private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
            Integer i = evt.getButton();
        private javax.swing.JButton jButton1;
    }In debug mode i cant listen to mouse events and key events in the same form. Is that normal ?
    In case this is normal, how can i surround this "problem" and make it work.
    Thanks a lot in ahead.

    Thanks for trying to understand whats going on ...
    There is my SSCCE
    * NewJFrame.java
    * Created on 2 de mayo de 2008, 20:32
    * @author  edu
    public class NewJFrame extends javax.swing.JFrame
        public NewJFrame()
            initComponents();
            setFocusable(true);
            requestFocus();
        private void initComponents() {
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            addKeyListener(new java.awt.event.KeyAdapter() {
                public void keyPressed(java.awt.event.KeyEvent evt) {
                    formKeyPressed(evt);
                public void keyReleased(java.awt.event.KeyEvent evt) {
                    formKeyReleased(evt);
                public void keyTyped(java.awt.event.KeyEvent evt) {
                    formKeyTyped(evt);
            jButton1.setText("jButton1");
            jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    jButton1MouseClicked(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 400, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addGap(0, 0, Short.MAX_VALUE)))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 300, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addGap(0, 0, Short.MAX_VALUE)))
            pack();
        private void formKeyTyped(java.awt.event.KeyEvent evt) {                             
            setTitle(String.valueOf(evt.getKeyCode()));
        private void formKeyPressed(java.awt.event.KeyEvent evt) {                               
            setTitle(String.valueOf(evt.getKeyCode()));
        private void formKeyReleased(java.awt.event.KeyEvent evt) {                                
            setTitle(String.valueOf(evt.getKeyCode()));
        private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
            setTitle(String.valueOf(evt.getButton()));
        private javax.swing.JButton jButton1;
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
    }It's quite simple, its suposed to show on the windows title the KeyCode (if there is any) or the MouseButton when pressed.
    The problem is: it doesnt work... (if i comment out the jButton1 related code, that means that i dont listen to MouseEvents & dont add the MouseAdapter as MouseListner to the form, the KeyEvents are raised and i can listen to them - but there are no MouseEvents - if i run the SSCCE like above i can listen to the MouseEvents, but cant listen to the KeyEvents. Can you tell me why?
    Just before posting i realized it was a focus issue ! The button got the focus and got all the events redirected towards him ! I solved it with the code
            jButton1.setFocusable(false);and it finally worked !
    Thanks!

  • Why cann't setText to a JTextField??

    Need your help!
    I produce an array of JTextField and add it to a JPanel.
    But I can only set text when initialized.
    In other place,even I call setText function, it doesn't work.
    Who know the reason??
    thanks in advance!!
    hgs.

    the code is like this:
    public class JFrame {
    JPanel contentPane;
    JPanel panel1 = new JPanel();
    JTextField jt = new JTextField(20);
    JPanel panel2 = new JPanel();
    MyClass class = new MyClass();
    public JFrame(){
    panel1.add(jt);
    panel2.add(class);
    contentPane = (JPanel)this.getContentPane();
    contentPane.add(panel1);
    contentPane.add(panel2);
    class MyClass{
    public MyClass(){
    // here if I call setText,It will work
    // jt.setText("test");
    public otherFunction(){
    // here ,it dosen't work
    jt.setText("test"); // it throw no exception when running

Maybe you are looking for

  • 64 bit iTunes 11.0.1.12 on Windows 7 Ultimate does not recognize iPad. What to do?

    After upgrade of iTunes to 11.0.1.12 (64bit) on Windows 7 Ultimate, iTunes claims it cannot connect my iPad Mini. It recommends me to uninstall iTunes and upgrade to the 64bit version - which is the one I installed in the first place. Reconnect, rest

  • ** if you want to be a JCP ** - hoax?

    On feb 11 someone posted a thread called 'IF YOU WANT TO BE A JCP...", it had an amazing 435 replies on 30 pages... 1) for those of you who posted your email addresses: did you receive a copy of these papers? 2) the response was overwhelming... maybe

  • Macbook Retina HDMI to VGA

    I'm looking for the best solution to connect my Macbook Retina to VGA projectors at work.  I see two adapters on the Apple store both with bad reviews.  Has anyone had good sucess with any adapters that go from HDMI to VGA? Thanks

  • Airplay mirroring from my iMac (late 2013) suddenly stop working.

    Is it a known Yosemite issue? Airplay worked perfectly with Mavericks and if I don't remember wrong, it also did after installing Yosemite. When I turn on Airplay my TV screen goes black and only the sound goes through. My Apple TV is gen 3. Airplay

  • Hi! REALLY REALLY NEED HELP WITH IPOD!

    Hi, I need to know if my ipod is damaged or if this is just a quirk. I have a fifth gen. video ipod. All of the sudden my ipod stopped playing all songs and videos that were purchased from itunes. I have no idea why. I looked up on the internet and i