Seprating string in JTextArea

hi,
I want to seprate the string in JTextArea.Any Suggestions....?
Thanx

i want to seprate it by words to display two different words in different colour How where we supposed to guess that you wanted to colour words based on your intial question?
Learn to post meaningfull questions with all the necessary information required to solve the problem so we don't waste time guessing what you really mean.
[url http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html]Text Component Features

Similar Messages

  • How to highlight Search string in JTextArea??

    I have a Search utility which search for a string in JTextArea. Search utility is able to locate the search string but it does not highlight it.
    Please let me know if you know what could be wrong
    Thanks
    Amit

    You have to highlight the string yourself. Try using:
    textArea.setSelectionStart( int );
    textArea.setSelectionEnd ( int );

  • Another help thread involving strings and jtextarea

    i have recently created a program, i have string message (which is made up of other strings created in my program) which i want to pass to a jtextarea box creating a list dont have a clue how to do so i tried using an arraylist but when i implemented it all it did was change the jtextarea output instead of creating a list. on top of this i have tried fixing it myself but only made the situation worse by deleting the way which i outputted the code, i have tried google but cant find an answer, any advice on my problem would be greatly appreciated
    if(e.getSource()==confirmation) {
       String message = "Your order of" + " " + mainDish+ " "+ "with"+ " "+ ingredients+ " "+ "costs" + " "+ pounds.format(bill);
       output.setText(message);
      if(e.getSource()==confirmationList) {
        ArrayList list = new ArrayList();
        list.add(output.getText()); 
        output.setText(" ");

    dbomb101 wrote:
    i have recently created a program, i have string message (which is made up of other strings created in my program) which i want to pass to a jtextarea box creating a list dont have a clue how to do so i tried using an arraylist but when i implemented it all it did was change the jtextarea output instead of creating a list. on top of this i have tried fixing it myself but only made the situation worse by deleting the way which i outputted the code, i have tried google but cant find an answer, any advice on my problem would be greatly appreciated
    if(e.getSource()==confirmation) {
    String message = "Your order of" + " " + mainDish+ " "+ "with"+ " "+ ingredients+ " "+ "costs" + " "+ pounds.format(bill);
    output.setText(message);
    if(e.getSource()==confirmationList) {
    ArrayList list = new ArrayList();
    list.add(output.getText()); 
    output.setText(" ");
    The biggest problem I see with your code is that you create a new ArrayList every time through your code segment. This will absolutely garentee that you only have at most 1 entry in your ArrayList.
    When you come into your code segment you create a new ArrayList
    When you go out of Scope, you loose the ArrayList
    So do you see a cyclic problem here?
    If you want your ArrayList to contain an accumulation of your output, then you have to make your ArrayList a class variable.

  • Removal of String from JTextArea

    Does anyone know how to remove a string from a JTextArea. The folowing do not work
    t1.remove(s1);
    t1.delete(s1);
    t1 being the text area and s1 the string

    Hello,
    If you want to "clear" the string, it's "setText("")".
    If you want do remove part of the string, its a little bit more complex ...
    String temp = getText();
    remove the string from the temp String
    setText(temp);
    I hope this help

  • Using a comma seprated string as rows

    i hv a column in which i store comma seprated name, i have to show them as rows in a report..
    plz help

    As with most things, it depends greatly on your Oracle version (you should always post this information).
    In release 11 here's a neat method.
    http://laurentschneider.com/wordpress/2009/07/select-from-column-separated-list.html
    In release 10 there's REGEXP
    http://nuijten.blogspot.com/2009/07/splitting-comma-delimited-string-regexp.html
    And it looks like you've been given a pre-10 answer already.

  • Drag & Drop from JTree (String) to JTextArea (Graphics2D)

    Hi everyone,
    I want to create a Drag & Drop from a JTree node to any location in a JTextArea. Upon dropping the node onto the JTextArea, I would want to draw a rectangle and the node name.
    I've created a custom transfer handler which allows the transferring of text from the tree node to the JTextArea.
    Any general ideas on how I can do that are wlecomed.

    I've managed to get hold of the JPanel via TransferHandler.TransferSupport.getComponent()
    the source seems a bit more tricky. I've tried this
    Transferable tr = support.getTransferable();
                   DataFlavor f = new DataFlavor();
                   f = new DataFlavor(MyTreeNode.class,"MyTreeNode");
                   try {
                        Object o = tr.getTransferData(f);...
    but the source does not provide a MyTreeNode instance, but something else (a String, I guess)
    how can I change this?

  • Loading String in JTextArea/JTextPane

    I'm trying to create an app that will display long Strings (veeerry looong and I know this is very easy) on the screen. When I display the String on screen, it should change the colors of certain text on the fly (much like many IDEs now). This is not necessarily required of the app but it would be good to have. My problem now lies in the fact that I originally used JTextArea, which worked very fine, loading the files very fast, too. Now, in order for me to be able to change the colors of the text, I have to switch to a JTextPane (not much change in code). I haven't even gotten to the point of making it change the text's colors, I've just changed my code to use JTextPane instead of JTextArea (shown below) but the speed of loading the file was so much affected. It's like the JTextPane is several times slower than JTextArea.
       //JTextArea txtDisplay = new JTextArea();
       JTextPane txtDisplay = new JTextPane();
       timer.start();
       txtDisplay.setText(aVeryLongString);
       timer.end();
       System.out.println(timer.status());
       ...After running this, using JTextArea, the timer.status() returns 3 seconds. Using the JTextPane() returns something like 10-15 seconds.
    Appreciate help fom anyone.

    Try something like this :
    JTextPane txtDisplay = new JTextPane();
    BufferedReader reader = new BufferedReader(new FileReader(big.txt));
    String line = null;
    while((line = reader.readLine()) != null) {
    txtDisplay.insertString(txtDisplay.getDocument().getLength(),line,null);
    Bye,
    Evert

  • To get the seprate string in a sentence

    For example, I input "Apple is a good fruit". what method can be used just get "Apple"?

    Feel free to to check the API:
    <quote>
    Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
    Examples:
    * "hamburger".substring(4, 8) returns "urge"
    * "smiles".substring(1, 5) returns "mile"
    </quote>

  • Working with comma seprated string in column

    hi,
    RDBMS:Oracle 10gR2
    I have a table with following structure
    Table : t1
    id int
    emails varchar2 (200)
    newEmail varchar2 (150)
    Sample data is as following
    id   emails                                                                                      newEmail
    1    [email protected],[email protected],[email protected]      null
    2
    [email protected],[email protected],[email protected]            null
    I can use following query to extract data from comma separation to row.
    select id,regexp_substr(emails, '[^,]+', 1, rownum) Emails
      from t1
      connect by level <= length(regexp_replace(emails, '[^,]+')) + 1
    Now I have to perform 2 operations
    1- find /count email ids per id, to estimate how many ids has single and how much  have multiple in emails.I have tried following but  it just remain in execution
    with Email as
    select id,regexp_substr(emails, '[^,]+', 1, rownum) Emails
      from t1
      connect by level <= length(regexp_replace(emails, '[^,]+')) + 1
    select id,emails from email
    group by id,emails
    having count (id)>1;
    2- I want to write update newEmail field from  first value in Emails in table t1 and remove updated value from emails field of table. so If emails has 5 email addresses (1,2,3,4,5) in it , after update it will have 4.I a not sure hoow to do that ?
    thanks

    You need to fix your data model.
    Storing multiple values in a single value column is bad database design and breaches the rules of normalization.
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select 1 as id, '[email protected],[email protected],[email protected]' as stupid_string from dual union all
      2             select 2, '[email protected],[email protected],email6.domain.com,[email protected]' from dual)
      3  -- ----------------------------------------------------
      4  -- END OF TEST DATA - USE QUERY BELOW AGAINST OWN TABLE
      5  -- ----------------------------------------------------
      6  select id
      7        ,level as email_id
      8        ,regexp_substr(stupid_string,'[^,]+',1,level) as email
      9  from   t
    10  connect by id = prior id
    11         and level <= regexp_count(stupid_string,',')+1
    12         and prior sys_guid() is not null
    13* order by 1,2
    SQL> /
            ID   EMAIL_ID EMAIL
             1          1 [email protected]
             1          2 [email protected]
             1          3 [email protected]
             2          1 [email protected]
             2          2 [email protected]
             2          3 email6.domain.com
             2          4 [email protected]
    7 rows selected.

  • Moving data string from a jtextarea into an array

    i was looking for some advice. how would i be able to take chunks of text on a paragraph by paragraph basis and enter them into an array. which would result in paragraph1 in array 0, and so on. is this possible to do? i have never really used straing arrays before, and if anyone knows of any online tutorials it would be a great help
    thank u

    here you go, forgive the gui, very sloppy looking, press the Click me button to store the jtextarea data into the array and show output button to see what the value stored in the array is. there are 2 classes:
    class MyMain {
          public static void main(String args[]){
              MyMain main = new MyMain();
              main.createIt();
          public void createIt() {
              MyFrame frame = new MyFrame();
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class MyFrame extends JFrame {
          String[] myString = new String[1];
          JTextArea textArea = new JTextArea();
          JButton myButton = new JButton("Click me");
          JButton outButton = new JButton("Show output");
          MyFrame() {
              myButton.addActionListener(new ButtonListener());
              outButton.addActionListener(new OutListener());
              getContentPane().setLayout(new GridLayout(1,3));
              getContentPane().add(myButton);
              getContentPane().add(textArea);
              getContentPane().add(outButton);
              setVisible(true);
          class ButtonListener implements ActionListener{
              public void actionPerformed(ActionEvent e){
                  myString[0] = textArea.getText();
          class OutListener implements ActionListener{
              public void actionPerformed(ActionEvent e) {
                  System.out.println(myString[0]);
    }

  • Cant Get Text To Show In JTextArea

    Hi guys,
    I'm trying to create a very simplistic GUI where the output of an IRC server is shown in a JTextArea. However for the life of me I can not get any text at all to show in the text area. Here's the class that creates the user interface:
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    public class SwingTest extends javax.swing.JFrame implements ActionListener {
         JButton connect = new JButton("Connect");
         JTextArea chat = new JTextArea();
        public SwingTest() {
             //set the title of the frame
             super("Chat Window");
             //set the size of the frame
             setSize(800, 600);
             //set what happens when the close button is clicked
             setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             // create the scroll pane to add the text area to
             chat.setLineWrap(true);
             JScrollPane scroll = new JScrollPane(chat, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
             //create the container panel
             JPanel jp = new JPanel();
             //create the layout manager and assign it to the container panel
             BoxLayout horizontal = new BoxLayout(jp, BoxLayout.Y_AXIS);
             jp.setLayout(horizontal);
             //add the text area and button to the container panel
             jp.add(scroll);
             jp.add(connect);
             //add the container panel to the frame
             add(jp);
             //make the frame and its contents visible
             setVisible(true);
             //add an event listener to the connect button
             connect.addActionListener(this);
        public void actionPerformed(ActionEvent event) {
             int temp = 1;
             SockThread mySock = new SockThread();
                 try {
                      Thread.sleep(20000);
                  while(temp == 1) {
                   while(mySock.pinger != false) {
                        chat.append(mySock.getStatus()+ "\n");
                        mySock.pinger = false;
                        break;
                 } catch  (InterruptedException ie) {
                      chat.setText("Error " + ie.getMessage());
        public static void main(String[] arguments)  {
             //create an instance of the SwingTest class and let it do its thing
             SwingTest st = new SwingTest();
    }

    Thanks hiwa, i did what you suggested and created a worker thread, but still I'm getting nothing in that JTextArea. I'm new to working with worker threads though, so if anyone wouldn't taking a look at my code just to see if I'm doing something wrong i would greatly appreciate it.
    Here is my worker class:
    import javax.swing.*;
    public class ChatWorker extends SwingWorker {
         String messages;
         String output;
         JTextArea chat;
         public ChatWorker() {
              super();
         protected String doInBackground() {
              int temp = 1;
              SockThread st = new SockThread();
              try {
                   Thread.sleep(20000);
                   //Perpetual loop needed to keep checking for server messages
                   while(temp == 1) {
                   while(st.pinger != false) {
                        messages = st.getStatus();
                        st.pinger = false;
                        break;
              } catch (InterruptedException ie) {
              return messages;
    }And here is the update gui class to make use of the worker thread:
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import java.beans.*;
    public class SwingTest extends javax.swing.JFrame implements ActionListener, PropertyChangeListener {
         JButton connect = new JButton("Connect");
         JTextArea chat = new JTextArea();
         ChatWorker cw;
        public SwingTest() {
             //set the title of the frame
             super("Chat Window");
             //set the size of the frame
             setSize(800, 600);
             //set what happens when the close button is clicked
             setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             // create the scroll pane to add the text area to
             chat.setLineWrap(true);
             JScrollPane scroll = new JScrollPane(chat, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
             //create the container panel
             JPanel jp = new JPanel();
             //create the layout manager and assign it to the container panel
             BoxLayout horizontal = new BoxLayout(jp, BoxLayout.Y_AXIS);
             jp.setLayout(horizontal);
             //add the text area and button to the container panel
             jp.add(scroll);
             jp.add(connect);
             //add the container panel to the frame
             add(jp);
             //make the frame and its contents visible
             setVisible(true);
             //add an event listener to the connect button
             connect.addActionListener(this);
        public void actionPerformed(ActionEvent event) {
             try {
             cw = new ChatWorker();
             cw.addPropertyChangeListener(this);
             cw.execute();
             } catch (Exception exc) {
        public void propertyChange(PropertyChangeEvent event) {
             try {
                  String tempText = (String)cw.get();
                  chat.append(tempText + "\n");
             }catch (Exception exc) {
        public static void main(String[] arguments)  {
             //create an instance of the SwingTest class and let it do its thing
             SwingTest st = new SwingTest();
    }

  • Using JTextArea - How do I clear it?

    Hi all.
    I have written a GUI program which transfers data from a method to a JTextArea/JScrollPane upon a button ActionEvent.
    When I press the "Next Record" button I want to be able to clear the previous details held in this JTextArea before I print the new ones in it. The Same for going backwards through an array. Does anybody know how to do this?
    Currently I am using the append method to add the returned String to my JTextArea. I have also tried using a replaceRange(String, int, int) method to clear the box before printing new details, but this isn't working properly as each Record in the array contains a different String length, so I can not enter the int values for each specific object.
    Below is the code for the application, and I've highlighted where I have used the methods to add a String to the JTextArea. I'm declaring the class for the action event within creating the actionListener, but can seperate it out if people need to see it more clearly.
    RECORDING CLASS ----------
    package RecordingManagerGUI;
    public class Recording
    private String title, artist, genre;
         public Recording (String theTitle, String theArtist, String theGenre)
              title = theTitle;
              artist = theArtist;
              genre = theGenre;
            public String getAlbum()
                return title;
            public String getArtist()
                return artist;
            public String getGenre()
                return genre;
         public String toString()
              String s = "Title: " + title + "\nArtist: " + artist + "\nGenre: " + genre + "\n\n";
              return s;
    }MANAGER CLASS ---------------
    package RecordingManagerGUI;
    import java.util.*;
    public class Manager
    private Recording[] theRecordings;
    private int numRecordings, maxRecordings, age;
    private String managerName;
    //Extending the Manager Class Instance Variables
    private int current = 0;
    private String record;
         public Manager (String theName, int theAge, int max)
              managerName = theName;
                    age = theAge;
              maxRecordings = max;
              numRecordings = 0;
              theRecordings = new Recording[maxRecordings];
         public boolean addRecording (Recording newRecording)
              if (numRecordings == maxRecordings)
                   System.out.println("The store is full");
                   return false;
              else
                   theRecordings[numRecordings] = newRecording;
                   numRecordings++;
                   return true;
            public int nextRecording ()
                if(current < numRecordings)
                    current += 1;
                else
                    record = "You have reached the end of the Records"; //initialise the string if no records
                return current;
            public int previousRecording()
                if(current > 1)
                    current -= 1;
                else
                    record = "You have reached the start of the Records"; //initialise the string if no records
                return current;
            public String displayCurrent()
                String displayRec = "";
                displayRec += theRecordings[current-1];
                return displayRec;
         public void displayDetails()
              System.out.println("Manager Name: " + managerName + ", " + age);
         //public void displayRecordings()
         //     System.out.println("\nThe Recordings: ");
         //     for (int i = 0; i < numRecordings; ++i)
         //          System.out.println(theRecordings);
    }RecordingManagerGUI CLASS ----------/*
    *Need to add a Label which tells me when I have reached the end of the Records
    package RecordingManagerGUI;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class RecordingManagerGUI extends JFrame {
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    JButton nextRecord;
    JButton previousRecord;
    JLabel recordLabel;
    JTextArea displayRecord;
    Manager theManager;
    public RecordingManagerGUI() {
    //Create and set up the window.
    super("Recording Manager Application");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Recording FooFighters = new Recording("The Colour and the Shape", "Foo Fighters", "Rock");
    Recording BlindMelon = new Recording("Blind Melon", "Blind Melon", "Alternative Rock");
    Recording JoeSatriani = new Recording("The Extremist", "Joe Satriani", "Instrumental Rock");
    Recording PercySledge = new Recording("When a Man Loves a Woman", "Percy Sledge", "Soul");
    Recording JustinTimberlake = new Recording("Justified", "Justin Timberlake", "Pop");
    Recording BeyonceKnowles = new Recording("Dangerously in Love", "Beyonce Knowles", "R'n'B");
    Recording TupacShakur = new Recording("2Pacalypse Now", "Tupac Shakur", "Hip Hop");
    theManager = new Manager("Cathy", 42, 7);
    theManager.addRecording(FooFighters);
    theManager.addRecording(BlindMelon);
    theManager.addRecording(JoeSatriani);
    theManager.addRecording(PercySledge);
    theManager.addRecording(JustinTimberlake);
    theManager.addRecording(BeyonceKnowles);
    theManager.addRecording(TupacShakur);
    displayRecord = new JTextArea(10, 30);
    displayRecord.setEditable(false);
    JScrollPane recordScroll = new JScrollPane(displayRecord);
    recordLabel = new JLabel("Record Details");
    nextRecord = new JButton("Next Record");
    nextRecord.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){theManager.nextRecording();displayRecord.append(theManager.displayCurrent());displayRecord.replaceRange(theManager.displayCurrent(), 0, 30);}}); //ADDING STRING TO JTEXTAREA
    previousRecord = new JButton("Previous Record");
    previousRecord.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){theManager.previousRecording();displayRecord.replaceRange(theManager.displayCurrent(), 0, 30);}}); //ADDING STRING TO JTEXTAREA
    getContentPane().setLayout(new FlowLayout());
    getContentPane().add(recordLabel);
    getContentPane().add(recordScroll);
    getContentPane().add(nextRecord);
    getContentPane().add(previousRecord);
    //Display the window.
    pack();
    setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    new RecordingManagerGUI();
    }Would appreciate any help thanks. I'm not sure if I just need to create a new instance of the JTextArea upon the event which would hold the String information. If so I'm not really sure how to do this.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    I don't know, the Swing experts are in the Swing forum. but setText() is defined in TextComponent, which a JTextArea is.

  • How to get the content of a jTextArea?

    hi everyone
    can some body provide me with some help???
    I want to know how to get the content of a jTextArea
    it may be a String and i want to use that String to make some applications
    I've use this :
    String ch=jTextArea.getSelectedText()
    but i'm not sure it will work and i'm not sure it will take the text writen inside the jTextArea ... please help
    Thanks

    http://forum.java.sun.com/thread.jspa?threadID=778988&tstart=0

  • Floating Height of JTextArea (as Renderer/Editor) in a JTable Cell

    Hey Folks,
    I'm kinda struggling with JTextAreas...
    There is this JTable, which consists of three colums (practically there are two - the other one's an ID-Field...) and only one
    of them ist editable für users.
    Left column is a commentary column which has a max of 150 characters - Right column fills automaticly with a user/date stamp.                                                                                                                                                                                    
    The main function is that on showing the table, old comments will be retrieved from database and new ones can be entered.
    This works all fine and is no matter of subject...
    The core of my problem is that there seems to be no straigh-forward way of determine a proper linecount from (a wordwrapped!) JTextArea.
    After a long search in the net, i found this approach:
        private static ArrayList<String> getWrappedLines(JTextArea myTextArea) {
            ArrayList<String> linesList = new ArrayList<String>();
            int length = myTextArea.getDocument().getLength();
            int offset = 0;
            try {
                while (offset < length) {
                    int end = Utilities.getRowEnd(myTextArea, offset);
                    if (end < 0) {
                        break;
                    // Include the last character on the line
                    end = Math.min(end + 1, length);
                    String line =
                        myTextArea.getDocument().getText(offset, end - offset);
                    // Remove the line break character
                    if (line.endsWith("\n")) {
                        line = line.substring(0, line.length() - 1);
                    linesList.add(line);
                    offset = end;
            } catch (BadLocationException e) {
                System.err.println("Bad Location at TextArea");
            return linesList;
        }    This code reads the content of a JTextArea an separates wrapped lines in an array.
    With manual line breaks ("\n") I get Exceptions (Bad Location) which isn't too bad, because
    I was trying to ban manual line breaks anyway...
    The above given method retrieves the lines, while the next sets the new Height (line count multiplied by Font Height) to the row.
        public static void setOptimalRowHeight(JTable table, JTextArea textArea, int row, int column) {
            if (
                row >= 0 &&
                column == VerwaltungsnotizController.IND_VNO_NOTIZ   
                int fontHeight =
                    textArea.getFontMetrics(textArea.getFont()).getHeight();
                ArrayList<String> wrappedLines = getWrappedLines(textArea);
                int nrOfLines = wrappedLines.size();
                int oldSize = table.getRowHeight(row);
                int newSize = (fontHeight * nrOfLines) + 5;
                if (newSize != oldSize) {
                    table.setRowHeight(row, newSize);
         public static void setOptimalRowHeight(JTable table, JTextArea textArea) {
         int row = table.getSelectedRow();
         int column = table.getSelectedColumn();
         if (
              row >= 0 &&
              column == VerwaltungsnotizController.IND_VNO_NOTIZ   
              setOptimalRowHeight(table, textArea, row, column);
         }The above combined Sources are used by two classes, which are "tied" to the table.
    One is the CellEditor (which works almost fine); the other one is the CellRenderer (which fails miserably!)
    CellEditor (with Listener):
    public class VnoCellEditor extends AbstractCellEditor implements TableCellEditor {
        private VnoTextArea textArea;
        private JTable table;
        public VnoCellEditor (JTable table) {
            this.table = table;
            textArea = new VnoTextArea(table);
            textArea.setMaximumInputLength(VerwaltungsnotizController.MAX_INPUT_VNO);
            textArea.addKeyListener(new TextAreaEnterAdapter());
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            Document document = textArea.getDocument();
            document.addDocumentListener(new VnoTextAreaDocListener(table, textArea));
        public Component getTableCellEditorComponent(JTable table, Object value,
                                                     boolean isSelected, int row,
                                                     int column) {
            if (value instanceof String) {
                textArea.setText((String)value);
            } else if (value instanceof Integer) {
                Integer intValue = (Integer)value;
                textArea.setText(intValue.toString());
            } else {
                Object objValue = value;
                textArea.setText(objValue.toString());
            System.err.println("Editor - get Component");
            return textArea;
        public Object getCellEditorValue() {
            return textArea.getText();
    public class VnoTextAreaDocListener implements DocumentListener {
        private JTable table;
        private JTextArea textArea;
        public VnoTextAreaDocListener(JTable table, JTextArea textArea) {
            this.table = table;
            this.textArea = textArea;
        public void insertUpdate(DocumentEvent e) {
            VnoTableRowHeightHelper.setOptimalRowHeight(table, textArea);
        public void removeUpdate(DocumentEvent e) {
            VnoTableRowHeightHelper.setOptimalRowHeight(table, textArea);
        public void changedUpdate(DocumentEvent e) {
            //Plain text components don't fire these events
    }As said the editor works almost as planned. On every Keystroke made in Edit-Mode of the table, insertUpdate() or removeUpdate()
    is being called, corresponding to the type of Keystroke ... (duh!)
    The Helpers method is called and the row-height is set real nicely.
    !But!
    when i navigate into an other row, a removeUpdate()-event is beeing thrown and due to the mechanism the cell selection
    gets somehow mixed around and row-heights get switched.
    Maybe this could get improved, but i don't se my error - which wouldn't be nescessary if this event wasn't thrown.
    (for what I don't see a reason anyway ... !)
    CellRenderer:
    public class VnoCellRenderer implements TableCellRenderer {
        private VnoTextArea textArea;
        private int Row = -1;
        private int Column = -1;
        private VnoTableModel jtmVno;
        public VnoCellRenderer(JTable table) {
            this.jtmVno = (VnoTableModel)table.getModel();
            textArea = new VnoTextArea(table);
            textArea.setLayout(new BorderLayout());
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
        public VnoTextArea getTextArea() {
            return textArea;
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected,
                                                       boolean hasFocus, int row,
                                                       int column) {
            Row = row;
            Column = column;
            String tmpValue = null;
            if (value instanceof String) {
                tmpValue = (String)value;
            } else if (value instanceof Integer) {
                tmpValue = ((Integer)value).toString();
            } else {
                tmpValue = value.toString();
            // FARBEN:
            // Normalmodus
            if (jtmVno == null) {
                System.err.println("Table Model noch nicht initialisiert!");
                textArea.setBackground(Color.LIGHT_GRAY);
            } else {
                if (jtmVno.isCellEditable(Row, Column)) {
                    textArea.setBackground(Color.WHITE);
                } else {
                    textArea.setBackground(Color.LIGHT_GRAY);
            textArea.setForeground(Color.BLACK);
            // Für ausgewählte Zeile
            if (isSelected && !hasFocus) {
                textArea.setBackground(CommonConstants.SELECTION_COLOR_BLUE);
                textArea.setForeground(Color.WHITE);
            textArea.setText(tmpValue);
            textArea.setEditable(true);
            if (Column == VerwaltungsnotizController.IND_VNO_NOTIZ) {
                VnoTableRowHeightHelper.setOptimalRowHeight(table, textArea, row, column);
            return textArea;
    }Okay, this is where the shit hits the fan!
    Since with renderers there is no manual content mutation, row-height-settings are not done with listeners.
    I put this at the very end of the getTableCellRendererComponent(), which is called every time a cell gets rendered.
    The main problem here is that at this point my methods can't determine any linewraps at all!
    getWrappedLines() always returns an empty Array (since Utilities.getRowEnd() returns "-1" beforehand...).
    I'm afraid that my methods are called way too early - at a point were the rendering is not completed or has not even started.
    And to accomplish my desired tasks the fully rendered JTextArea would be needed ... ?!
    I have very limited swing experience, so I can only guess about this core features ...
    But i this is the case - my methods should be called later on the rendered cell. But how? from which component?
    Btw: I have written my own JTextArea to limit the input size
    public class VnoTextArea extends JTextArea {
        private JTable table;
        private int _maximumInputLength = 0;
        public VnoTextArea(JTable table) {
            this.table = table;
        public void setMaximumInputLength(int maximumInputLength) {
          if (maximumInputLength != 0) {
            _maximumInputLength = maximumInputLength;
            super.setDocument(new PlainDocument() {
                public void insertString(int offset, String string, AttributeSet attributeSet) throws BadLocationException {
                  StringBuffer buffer = new StringBuffer(string);
                  int size = VnoTextArea.this.getText().length();
                  int bufferSize = buffer.length();
                  if ((size + bufferSize) > _maximumInputLength) {
                    buffer.delete((_maximumInputLength - size), bufferSize);
                  if (size < _maximumInputLength) {
                    super.insertString(offset, buffer.toString(), attributeSet);
                  } else {
                    Toolkit.getDefaultToolkit().beep();
    }I'm sorry for not providing a running example, but it's a pretty huge project...
    Providing all dependencies would go far beyond the scope.
    (and there are many sources which I'm not allowed to post)
    But I hope my examples get down to the core of my problem!
    I also tried different approaches:
    - using getPreferredSize() of the JTextArea (seemed to do nothing useful at all?!)
    - using getLineCount/() of the TextArea (only counts "\n" ...)
    - guessing that every row consist of an average of 20 characters cumpute by myself (low-tech, buggy but fast - unsatisfying)
    With my above mentioned approach I got by far the best results (partially) - but I'm at my wits' end.
    I don't know it any better... And i have tried for days without improvement.
    What would you do?
    vielen Dank im Voraus schon mal für eventuelle Mühen,
    Haye

    no solution - just a couple of comments:
    - never ever change the calling table in a renderer, I mean really NEVER
    - instead, listen to table events and resize the row height as appropriate
    - JTextArea has a somehow weird prefSize calculation (forgot the details, so don't nail me :), so you have to manually set one dimension and then ask the area to calculate the other. In your renderer, you can do something like:
    Component getTableCellRendererComponent(....) {
        int columnWidth = table.getColumnModel().getColumn(column).getWidth();
        textArea.setSize(columnWidth, Short.MAX_VALUE);
        ... here do the normal config
    // then somewhere else, triggered by appropriate change events
    void updateRowHeight(JTable table, int row) {
       int height = table.getRowHeight();
       foreach column {
             TableCellRenderer r = table.getCellRenderer(row, column);
             Component c = table.prepareCellRenderer(r, row, column);
             height = Math.max(height, c.getPreferredSize().height);
       table.setRowHeight(row, height);
    } HTH - ein bißchen wenigstens :-)
    Jeanette

  • How to clear JTextArea

    Hi,
    I am trying to clear the JTextArea when the user clicks on a button. I could not find a clear command in the JavaDocs but I did try the following:
    Is there a better way to do this or a different object.
    Thanks,
    Steve
    String abc = " ";
    int xcoord = 0;
    int ycoord = 40;
    msgout.replaceRange(abc, xcoord, ycoord);

    use a setText method.
    JTextArea.setText(String);
    if you wanted to make it blank...
    String str = "";
    JTextArea.setText(str);

Maybe you are looking for

  • How to modify text insertion position in HTML in a JEditorPane

    Hi all, Thanks in advance if anyone knows the type of code I need to look at to solve my problem. It involves the insertion point (in the actual HTML) when editing text in a JEditorPane using type html/txt. for example, lets say you start to add text

  • FaceTime is not working since the last time I've disconnected it...

    Since the last time I've disconnected it, Facetime is not working. At first, I thought it was working with no problems. Then, I realize that I could not make or receive calls, and then I disconnected. Now, I can't connect it. There's a message saying

  • Layers in an Acrobat file.

    How come when I export a layered InDesign file, and tell the settings to export Acrobat layers, when I open that files in Acrobat, there are no layers? what am I doing wrong?

  • G4 iBook running OS 10.5.8. problems with iTunes!

    I have just a G4 iBook for my dad, it is running OS 10.5.8. I was putting some updates and didnt think twice about updating itunes. Now it wont open. It needs Quicktime 7.5 or more to run. I downloaded Quicktime from the apple website and the most ad

  • Replacement of obsolete FM 'HELPSCREEN_NA_CREATE'

    hi all, Any one can help me with the replacement of 'HELPSCREEN_NA_CREATE'? Thanks Protyusha