Results 1 to 6 of 6
  1. #1
    valdeEdius is offline Member
    Join Date
    Mar 2012
    Posts
    3
    Rep Power
    0

    Default Monitoring JTextArea for change and then changing it.

    Hi, I'm having some trouble with figuring out ActionListeners(), I have a loop that creates a 2D array of JTextArea cells[][] and populates it with JTextAreas that are called cell inside the loop. I need to watch the cells and perform actions on the cells that will alter them, and also compare them to a map using bijection (so I need to know the location of cells[x][y] to compare to key[x][y]).int[][] key is a parameter passed to the GUI class and for the life of me I can't figure out how to use it inside the ActionListener. I've tried creating an ActionListener, but that only responds when the user hits enter within the cell, I want to call this action the moment they type a new value into the cell. The ActionListener also doesn't seem to allow me to edit the value of my cell? The code below seems like it should get the text, keep only the first character, and discard the rest and then set it to the JTextField, but it doesn't set the text.
    Java Code:
    cell.addActionListener(new ActionListener() 
             {
               public void actionPerformed(ActionEvent event)
               {
                 JTextField cell = (JTextField) event.getSource();
                 System.out.print(cell.getText()+" response triggered...");
                 //Trim cells that are >1 length.
                 if(cell.getText().length()>1)
                 {
                   String str = cell.getText();
                   str.replaceAll("(.)*", "$1");
                   System.out.println(cell.getText());
                   cell.setText(str);
                 }
               }
             });
    Thank you for your help,
    Valde

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Monitoring JTextArea for change and then changing it.

    I want to call this action the moment they type a new value into the cell.
    Use a DocumentListener. (But is there some reason you aren't using a JTable?)

    The ActionListener also doesn't seem to allow me to edit the value of my cell? The code below seems like it should get the text, keep only the first character, and discard the rest and then set it to the JTextField, but it doesn't set the text.
    In the if block you are printing the text in cell, however you have already printed this text. Try printing the changed text to see what you are setting the cell's contents to.

    Java Code:
    if(cell.getText().length()>1)
    {
        String str = cell.getText();
        str.replaceAll("(.)*", "$1");
        //System.out.println(cell.getText());
        cell.setText(str);
        System.out.println("Changed to: " + cell.getText());
    }

  3. #3
    valdeEdius is offline Member
    Join Date
    Mar 2012
    Posts
    3
    Rep Power
    0

    Default Re: Monitoring JTextArea for change and then changing it.

    Should I be using a JTable? I'm teaching myself Java and I'm trying to piece together a sudoku GUI. It started as me just wanting to print the puzzle as it solves using line draws and paint, eventually it evolved to this. I added the println, and it prints what the current value of the cell is, not the single character that I'm looking for. I've uploaded my GUI to : [Java] import java.awt.Dimension; import java.awt.Font; import java.awt.Frame; imp - Pastebin.com should you wish to see it. if you believe a JTable would be a better way of accomplishing this I will begin researching JTable w/DocumentListener (I also need to be able to lock the cell and want to be able to change it rapidly&frequently).

    Also, why am I having problems passing key[][] into that anonymous method? It is still within a class that receives it as a parameter, I would think I would be allowed to use it.

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Monitoring JTextArea for change and then changing it.

    For sudoku a grid of components sounds OK - when you referred to a 2d array I had visions of hundreds of cells...

    It is worth reading the DocumentListener page to see what these things do. Basically they allow you to respond to changes being made to the document (text) in the text area any way you like. As far as "locking" cells is concerned the text areas can be disabled like any component.

    I added the println, and it prints what the current value of the cell is, not the single character that I'm looking for.
    It prints the contents of the cell after you changed them with setText(). If this is not what you were wanting or expecting to see then it appears that str.replaceAll("(.)*", "$1"); did not do what you thought. Remember that String instances are immutable: there is no method that will change the sequence of characters making up a string. replaceAll() will return a new String instance and if you want to use what it returns you should assign it to something, possibly str.

    Also, why am I having problems passing key[][] into that anonymous method? It is still within a class that receives it as a parameter, I would think I would be allowed to use it.
    I'm not sure I understand this. You don't pass anything to the method: it gets its an ActionEvent argument by whatever magic these listeners get their arguments, and that's all it gets. I can sort of guess what you might be driving at with "It is still within a class that receives it as a parameter" but would prefer not to guess. If the compiler is grumbling and you can't understand its message, post the message and the code it is referring to.

  5. #5
    valdeEdius is offline Member
    Join Date
    Mar 2012
    Posts
    3
    Rep Power
    0

    Default Re: Monitoring JTextArea for change and then changing it.

    Quote Originally Posted by pbrockway2 View Post
    For sudoku a grid of components sounds OK - when you referred to a 2d array I had visions of hundreds of cells...

    It is worth reading the DocumentListener page to see what these things do. Basically they allow you to respond to changes being made to the document (text) in the text area any way you like. As far as "locking" cells is concerned the text areas can be disabled like any component.
    Thanks, I have started reading about document listeners. I know I can lock the text areas, but I wasn't sure about JTable. Since I won't be using it I will answer that question later when I use them on another project.


    It prints the contents of the cell after you changed them with setText(). If this is not what you were wanting or expecting to see then it appears that str.replaceAll("(.)*", "$1"); did not do what you thought. Remember that String instances are immutable: there is no method that will change the sequence of characters making up a string. replaceAll() will return a new String instance and if you want to use what it returns you should assign it to something, possibly str.
    Thanks, newbie mistake. I've changed it to str = str.replaceall(...);

    I'm not sure I understand this. You don't pass anything to the method: it gets its an ActionEvent argument by whatever magic these listeners get their arguments, and that's all it gets. I can sort of guess what you might be driving at with "It is still within a class that receives it as a parameter" but would prefer not to guess. If the compiler is grumbling and you can't understand its message, post the message and the code it is referring to.
    Let me simplify this, I asked it poorly. Line 186 has this:
    Java Code:
    else cell.addActionListener(new ActionListener() 
             {
               public void actionPerformed(ActionEvent event)
               {
    just above that in my for loop I determine the [row][column] for my cell, I want to be able to pass that reference through the listener so that I can compare the cell[row][col] to a value at key[row][col]. But I can't modify the listener to accept more parameters, or at least I don't know how. I updated the pastebin code so that key[][] is passed all the way down properly. But I can't get it or the values of row/col into the listener. Being able to retrieve the location of the cell being changed would also achieve this for me, I believe.
    Last edited by valdeEdius; 03-17-2012 at 09:37 AM.

  6. #6
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Monitoring JTextArea for change and then changing it.

    An ActionListener - or any other sort of listener, or any other sort of "call back" for that matter - is a sort of free floating, independent, object. You create it and, from that point on, it sits there waiting to be notified and when it is, it does its job. You *can't* modify the actionPerformed() mechanism: either the arguments or the way that method gets invoked (given particular values for those those arguments).

    Such a listener "knows about" things defined in the context where it, itself, was defined. So, for example, if there is a key instance variable defined in the class where that last snippet occurs, the listener will be able to access it and find out the value of its contents. But row and col are (probably) different. Ordinary method variables disappear, as far as your program is concerned, the moment the method finishes. When your listener is awoken and does its thing they will not be there to be accessed.

    One way for actionPeformed() to have access, not to row and col, but to their values at the time the listener was created is to make new final variables for that purpose. As in the following code (untested, and faith-based rather than grounded on any knowledge of the surrounding code)

    Java Code:
    int row;
    int col;
    
    // calculation to determine row and col proper to cell
    // goes here
    
    else {
        final int rowNdx = row;
        final int colNdx = col;
        cell.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                // rowNdx and colNdx can be accessed here
            }
        });
    }
    An alternative is to define and use a subclass of ActionListener that knows about row/col ie is given their values in its constructor. A sketch

    Java Code:
    class CellListener extends ActionListener {
        private int row;
        private int col;
        CellListener(int row, int col) {
            this.row = row;
            this.col = col;
        }
        @Override
        public void actionPerformed(ActionEvent event) {
            // row and col can be accessed here
            // something will have to be done to make the key array accessible
        } 
    }
    
    class ??? {
        ??? ???() {
            // ...
            else cell.addActionListener(new CellListener(row, col)); 
        }
    }
    I haven't checked but I would bet that near by the DocumentListener page I linked to is a pretty decent description of the XxxListener mechanism employed by Swing. (And saying that gives me the opportunity to remind you that if the listener is responding to changes in the cell's text content then that is a different thing from responding to actions or responding to keystrokes. The different listeners are there for a reason.)

    -----

    Do these cells move around? I ask because you mention doing a calculation to determine the cell's row/col coordinates. But if the cells are static within their grid, can't these values be determined at the time the cell is created? The cell's constructor, itself, could create and add the listener. And that way the listener would certainly have access to the row/col values as these would be part of its "context".

    -----

    I don't usually follow pastebin or other links. (and haven't/won't in this case) It's not that there's a "rule" or whatever, and others may act differently, but I'm just saying in case there's confusion. I recognise this makes it a bit harder on you - but if it were easy, the code would write itself!:)

Similar Threads

  1. Change appearance of lines in a JTextArea
    By blackbird in forum AWT / Swing
    Replies: 11
    Last Post: 07-11-2011, 06:58 PM
  2. Replies: 0
    Last Post: 08-14-2010, 11:09 AM
  3. Swing - Changing text in JTextArea from void
    By Lawllerskates in forum New To Java
    Replies: 4
    Last Post: 02-18-2010, 06:37 PM
  4. JTextArea on PopUp -JTextArea isn't editable
    By Richy76 in forum AWT / Swing
    Replies: 3
    Last Post: 02-01-2010, 08:51 PM
  5. Changing JTableModel does not change JScrollpane size
    By stelzergil in forum New To Java
    Replies: 3
    Last Post: 10-19-2009, 03:14 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •