Append method in JTextArea()????

when we use JTextArea :JTextArea area= new JTextArea();we can do like this : area.append("");but when we use JTextPane:
JTextPane area=new JTextPane();we can not do like this:
area.append("");so what equal append method in JTextPane();
Thanks,,

beshoyatefw wrote:
But i use append() for reading file..If all you're doing is reading a file into a text component, use the read() method:
BufferedReader r = new BufferedReader(new FileReader("myFile.txt"));
textComponent.read(r, null);
r.close();It will be much more efficient.
Also note that 'pane.setText(pane.getText() + "whatever")' is very inefficient if the text contained by the text component is very large. getText() creates a copy of the text represented in the component, so if you have a lot of text, or if you're appending text over and over in a loop, it's better to just call pane.getDocument() and add the text directly to the end of it.

Similar Messages

  • JEditorPane and using methods from JTextArea

    Hi there;
    I want to be able to use a method from JTextArea - public void insertString( String str, int pos) on my JEditorPane
    Is there a way to do this? I'm lost in the hierarchy - and my programming ain't too hot !!
    Thanks

    oops meant to say insert(Sting str, int pos )

  • Append text in JTextArea

    greetings.. i'm having the following code:
    public class GUI extends JPanel implements ActionListener
      JTextArea theText;
      public GUI()
         // and so on and so forth that initializes the textarea
          displayToTextArea("call from inside");
    public void displayToTextArea(String message)
      theText.append(message + "\n");
    }and at another class:
    GUI theGUI = new GUI;
    theGUI.displayToConsole("call from outside");but after running, the only text appended is the "call from inside", the "call from outside" is not appended into the textarea.
    any clues?
    please advice.
    thanks. ^_^

    I think you need to show how you are using it because if I use it from a simple test harness and add what must be missing (the creation of 'theText' and the action listener method) it works OK for me.
    Make sure you have defined the number of lines for the JTextArea.
    import javax.swing.*;
    import java.awt.event.*;
    public class Test20050115
        static class GUI extends JPanel implements ActionListener
            JTextArea theText = new JTextArea(4, 50); // 4 lines
            public GUI()
                add(theText);
                // and so on and so forth that initializes the textarea
                displayToTextArea("call from inside");
            public void displayToTextArea(String message)
                theText.append(message + "\n");
            public void actionPerformed(java.awt.event.ActionEvent actionEvent)
        public static void main(String[] args)
            JFrame frame = new JFrame("Test");
            GUI gui = new GUI();
            gui.displayToTextArea("call from outside");
            frame.getContentPane().add(gui);
            frame.pack();
            frame.setVisible(true);    
    }

  • String buffer's Append method is not working

    Hi,
      I am creating an application which uses AbstractPortal component. In the doContent() method , i am reading an XML file using buffered reader and appending the character by Charater from the XML file to an buffer String.It's not showing any error in the Eclipse , but if i try to run the application it shows the an error in the <i><b>buffer.append</b></i> statement.
    The error is
    java.lang.StringBuffer.append(C)Ljava/lang/Appendable;.
    Exception id: 10:55_12/03/06_0027_38431050
    See the details for the exception ID in the log file

    Hi Saravanan,
    I Understand your logic,i was doing the same but it never worked for me.
    In AbstractPortalComponent ,the request object is passed as parameter to the do… methods.
    http://help.sap.com/saphelp_nw04/helpdata/en/9b/ff3c41325fa831e10000000a1550b0/content.htm
    You need to access the original ServletRequest() of this request to process further.
    In my opinion,problem is not in buff.append.if you see it in debug you can see that (char)i itself null or something.
    For a change try my code and see what kind of parameters your ServletRequest()has.
    Good luck

  • I have a doubt about The Single-Thread Rule

    The [url http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html#rule]Single Thread Rule states:
    Rule: Once a Swing component has been realized, all code that might affect or depend on the state of that component should be executed in the event-dispatching thread.
    I began to wonder about this because so much code seems to work just fine when it isn't executed in the event dispatching thread. Why are there exceptions? I went looking for some code which acted differently when executed on the event thread than when it was not. I found this
    http://forum.java.sun.com/thread.jsp?forum=57&thread=410423&message=1803725#1803725
    Now I started wondering why this was the case. What I found was that DefaultCaret adds a document listener to the document of the JTextComponent. In this listener, the insertUpdate() method specifically tests if it is running on the event dispatch thread and if it is, it updates the caret position.public void insertUpdate(DocumentEvent e) {
        if (async || SwingUtilities.isEventDispatchThread()) {
            // ... update the caret position ...
    }I then copied the code from DefaultCaret and made a MyCaret. I needed to tweek the code a little bit, but it ran. I removed the event thread test. It worked outside the event thread. There was a small difference in the results though. The textarea did not scroll all the way to the bottom. Almost, but not quite. I didn't test enough to make sure this was the only problem, but there was at least one problem.
    Now I started think about why this would be. The thought crossed my mind that the order of the events which were posted to the event queue were probably important. Sun found bugs when components were updated out of the event thread, so they essentially ignored events which weren't on the event thread and created the The Single-Thread Rule.
    A few days pass. I'm starting to wonder if Sun could have done a better job making Swing components thread safe. I also don't know that this specific case I found was the rule or the exception to the rule. But without insight into the design philosopy of Swing, I would have to examine all their components and see how they have written them and see if I can come up with a better design. That sound like a lot of work. Especially without getting paid for it.
    But wait a second, all you have to do is call the append() method of JTextArea on the event thread. If that is the case, why didn't they write the freakin component that way? Well, I'll try itclass MyTextArea extends JTextArea {
      public MyTextArea(int rows, int columns) { super(rows,columns); }
      public void append(final String text) {
        if (SwingUtilities.isEventDispatchThread()) super.append(text);
        else {
          SwingUtilities.invokeLater(new Runnable() {
            public void run() { myAppend(text); }
      private void myAppend(String text) { super.append(text); }
    }I change [url http://forum.java.sun.com/thread.jsp?forum=57&thread=410423&message=1803725#1803725]camickr's code to use a MyTextArea and it works fine without calling from the event thread. I've essentially moved The Single-Thread Rule to the component itself rather than relying on each and every one of the [url http://www.aboutlegacycoding.com/default.htm?AURL=%2FSurveys%2FSurvey6intro%2Easp]2.5 million Java programmers worldwide to use SwingUtilities.invaokeLater().
    Now for my question...
    Why didn't Sun do this?

    Swing is slow enough as it is. Lets not make it slower
    just
    because dense "programmers" don't know what they are
    doing.I agree with you in defending the current model, but aren't you a bit harsh there?!? ;-)
    Well, there are a number of not-so-dense programmers that expect such high-level components to be thread-safe. The question is worth asking whether Sun intentionally favor the explicit thread management for performance reasons, or whether this was an oversight.
    I'd go for the former (intentional) : indeed any GUI toolkit is inherently thread-based; there is always a distinction between the graphical thread(s) and the application threads - and the programmer always has to manage explicit thread creation to handle long-running event handlers without blocking the event dispatching thread. Extending thread concerns to the updating of components is therefore not a big move.
    So it seems fair that a core GUI toolkit does not hide thread issues (though to the best of my knowledge there is no such limitation in updating AWT components), or at least that's what Sun deemed.
    An ease-of-use-focused toolkit wrapping the core toolkit for thread-safety can be provided as a third-party product. Though I agree that wrapping the dozens of existing widgets and hundreds of methods is cumbersome - and the lack of such products probably shows it would have a low added value to trained developpers.
    Because your way is an extra method call and if
    statement, neither of which is necessary if you already know you
    are in the correct thread. Now count the number of methods
    which will need to be changed (and add up the extra cost).Indeed it's quite common to update several properties of several widgets in one bulk (when user clicks "OK", add a row to the table, change the title of the window, update status bar, re-enable all buttons, change some color,...).
    In this case explicit thread management doesn't spare one if but a dozen of redundant ifs!
    Note that there could have been if-less ways to cope for thread safety, such as creating a copy of the component's model when a change is made to a component, and switching the model only before paint() is called in the event-dispatching - of course coalescing all changes into the same "updated" model until paint() is called.
    But this would trade ease of use for redundant memory consumption, especially for some components with potentially huge models (JTree, JTable, JTextArea,...). And Swing appears to be already quite memory-greedy!

  • JTextArea.append

    I have got some problem using the .append method of the JTextArea class. Below is my statement.
    The declaration
    private JTextArea ulist;
    ulist = new JTextArea();
    ulist.setFont(new Font("Tahoma", 0, 11));
    ulist.setEnabled(false);
    JScrollPane spulist = new JScrollPane(ulist);
    spulist.setLocation(24, 285);
    spulist.setSize(187, 150);
    con.add(spulist);
    spulist.append("Client" + clientno + "'s host name is" inetAddress.getHostName() "\n");
    The error message i got was " cannot find symbol method in java.lang.string"
    Can anyone help?

    try ulist.append() rather than spulist.append. it
    might workYes I rather think it will. I was hoping in reply 1 that the OP would spot the error of their ways with just a hint.

  • JTextArea can't append

    I need to append text to a JTextArea from a different class than the JTextArea is in. For example, my code is as follows:
    public JTextArea getJTextArea() {
    if (jTextArea == null) {
    jTextArea = new JTextArea();
    jTextArea.setBounds(new java.awt.Rectangle(115,8,274,181));
    jTextArea.setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.gray,1));
    jTextArea.setText("Chat initiated...");
    jTextArea.append("append");
              return jTextArea;
    Appending the text works in the above code, but if I try to append text using this code:
    jTextArea.append("appended text");
    anywhere else in the code it will not work. Why is this and how do I append text to the jTextArea?

    You can't expect one class to recognize a variable declared elsewhere, right?
    class Freader {
        public static void main(String args[]){
            jTextArea.append("new text"); //out of nowhere!
    }This really isn't a Swing question, it's a "how can I write code" question.
    To send message append (for example) to object jTextArea
    and do this from within method m of class C, then either:
    1. Create the object referred to by jTextArea in method m.
    2. Have jTextArea passed into method m
    3. Have jTextArea be a field of class C
    4. Invoke some other method that returns the reference to jTextArea.
    5. Don't do this directly in m: invoke another method that does
    it directly or indirectly.
    Do you get the idea?
    For example, Below I define Main, which will invoke append, and Display,
    which has the append method.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Main {
        public static void main(String[] args) {
            final JFrame f = new JFrame("Main");
            JButton btn = new JButton("append");
            btn.addActionListener(new ActionListener(){
                Display display = new Display(f);
                public void actionPerformed(ActionEvent evt) {
                    display.append("some more text\n");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(btn);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    class Display {
        public Display(JFrame owner) {
            JDialog dialog = new JDialog(owner, "Display");
            textComponent = new JTextArea(20, 50);
            dialog.getContentPane().add(new JScrollPane(textComponent));
            dialog.pack();
            dialog.setVisible(true);
        public void append(String text) {
            textComponent.append(text);
        private JTextArea textComponent;
    }

  • Append text on dropping in jTextArea

    Hello forum members;
    I need help for appending some text while dropping in a text area.
    My requirement is :
    I have a jtextfield and jtextarea.I have to drag the texts from the text field and drop on textarea.
    While dropping text from text field to textarea the text will move to textarea and then if the user will drag again the text from the textfield and drop on the textarea then the newly dragged text will append /add on the text at the end with a semicolon(;) .
    For example :-
    if the textfield contains text is "redtext" and drop for fist
    time on text area the text area text will be "redtext" and when user drag for second time the text "bluetext " then the new text in the text area will be "redtext;bluetext"
    and then if the user will drop "greentext " then the new text will be "redtext;bluetext;greentext" and so on. i.e a semicolon will be added at the end of the text.
    Below is the code , please help me.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class AppendOnDrop extends JFrame{
         private javax.swing.JLabel jLabel1;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JPanel jPanel2;
        private javax.swing.JTextField jTextField1;
         private javax.swing.JTextField jTextField2;
        private javax.swing.JTextArea jTextArea1;
          public AppendOnDrop() {
            super("AppendOnDrop Test");
            setSize(300, 100);
             jPanel1 = new javax.swing.JPanel();
            jLabel1 = new javax.swing.JLabel();
            jTextField1 = new javax.swing.JTextField(2);
              jTextField2 = new javax.swing.JTextField(2);
            jPanel2 = new javax.swing.JPanel();
            jTextArea1=new javax.swing.JTextArea(10,10);
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jLabel1.setText("100");
            jLabel1.setTransferHandler(new TransferHandler("text"));
            MouseListener listener = new DragMouseAdapter();
            jLabel1.addMouseListener(listener);
              jTextField1.setMaximumSize(new java.awt.Dimension(30, 28));
            jTextField1.setDragEnabled(true);
              jTextField1.setTransferHandler(new TransferHandler("text"));
              jTextField2.setMaximumSize(new java.awt.Dimension(30, 28));
            jTextField2.setDragEnabled(true);
              jTextField2.setTransferHandler(new TransferHandler("text"));
              jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder("Drag")));          
            jPanel1.setLayout(new BoxLayout(jPanel1, BoxLayout.X_AXIS));
            jPanel1.add(jLabel1);
             jPanel1.add(jTextField1);
              jPanel1.add(jTextField2);
            jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Drop"));
            jPanel2.setLayout(new BoxLayout(jPanel2, BoxLayout.X_AXIS));
              jPanel2.add(jTextArea1);
            getContentPane().add(jPanel1, BorderLayout.WEST);
            getContentPane().add(jPanel2, BorderLayout.EAST);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
         private class DragMouseAdapter extends MouseAdapter {
            public void mousePressed(MouseEvent e) {
                JComponent c = (JComponent)e.getSource();
                TransferHandler handler = c.getTransferHandler();
                handler.exportAsDrag(c, e, TransferHandler.COPY);
           public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new AppendOnDrop().setVisible(true);
    }Thanks

    Thanks very much hiwa;
    This code snippest helped me a lot.This is working fine.
    But on the first drag also the semicolon appended in the jTextArea. How to avoid the appending of semicolon for the first drag , is there any method for it i.e while user will drop for the first time the semicolon will not be appended but while drop for second time onwords the semicolon will be appended.
    And application requirement is bit changed .i.e
    I have a jlabel and a jtext area (as mentioned before).But now to make the functionality easy for user ,,
    the user will only drag the label not the text from the text field and then the corresponding texts from the text field will move with the label dragging and dropped on the text area i.e not the jlabel value will dropped only the text will drop on text area.
    For eexample:
    if the label value is 100 and the text fild contains the texts as "red" , if the user will drag the label i.e 100 the text "red" will be dragged and while dropping to text area the texts only from the text field i.e "red" will be dropped but 100 will not be dropped any where.
    please help me
    Thanks & Regards
    Mahenda

  • How do i append each String on a different line in a JTextArea

    Hi,
    I have the following lines of code and I would like each line to append into the JTextArea on a separate line. I know I need to use \n but i forgot how to do it with the following code:
    invoiceJTextArea.append(FirstName);
    invoiceJTextArea.append(Surname);
    invoiceJTextArea.append(Age);
    At the moment, it prints right next to each other like this: JohnSmith28
    Thanks for your help.

    A JTextComponent will accept "\r\n", and it will seem
    to work, but the "\r" will not be treated as part of
    the line separator. And "\r" alone won't function as
    a line separator--in fact, it won't be displayed at
    all.
    When you read text into a JTextComponent from a file
    via the built-in read() method, all line separators
    are converted to "\n". The type of separator used in
    the file is saved as a property of the Document, and
    when you write the text back to the file, they are
    reconverted. Text pasted in from the clipboard also
    undergoes this conversion (but I don't think it gets
    reconverted when you copy or cut).
    The issue of line separators is meant to be
    completely transparent to the user. Programmers
    usually don't have to think about it either, but we
    do have the power to insert any whitespace character
    into a text component. We need to be aware that only
    spaces, tabs and linefeeds will render as expected.First off, I apologize for being a bit curt or dogmatic ... I was in a bit of a hurry.
    Note thought that I did not state: Don't use '\n'.
    What I did state as being wrong was your statement of:
    "No, don't use the system line separator. JTextArea can only use "\n" as a line separator"
    I have tried used the system line separator and it works. So I am not saying one should not use '\n', only that should not say the system line sep does not work.

  • JTextArea.selectAll() method?

    why can not the method of "JTextArea.selectAll()" work in the ActionListener ??
    the following code:
    public void actionPerformed(ActionEvent event) {              
    textArea.selectAll();
    if you do as the above, and click the button that listened by above, there is no response. Please reply to us as soon as possible.
    Thanks!

    Selected text is only shown when the component has focus. When you click on a button it gains focus. Try:
    textArea.selectAll();
    textArea.requestFocus();

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

  • Having a JTextArea scroll when output is written to it

    I'm using a JTextArea (inside a JScrollPane) as a console, and I use the append() method to update the text area with various information. I'd like the JTextArea to automatically scroll down as more lines get added onto it, similar to a shell or command prompt.
    It seems "autoscroll" refers to something else, and the scrollpane horizontal/vertical policy refers to the display, not behavior, of the scrollpane. Can anyone point me in the right direction?
    Message was edited by:
    k1cheng

    i've done this in the past by adding
    textArea.setCaretPosition(
    textArea.getDocument().getLength());
    after the append. hope this helps!This works great. Thanks.
    camickr, you are right. Thanks.

  • How to get the content of text file to write in JTextArea?

    Hello,
    I have text area and File chooser..
    i wanna the content of choosed file to be written into text area..
    I have this code:
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.*;
    public class Test_Stemmer extends JFrame {
    public Test_Stemmer() {
    super("Arabic Stemmer..");
    setSize(350, 470);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setResizable(false);
    Container c = getContentPane();
    c.setLayout(new FlowLayout());
    JButton openButton = new JButton("Open");
    JButton saveButton = new JButton("Save");
    JButton dirButton = new JButton("Pick Dir");
    JTextArea ta=new JTextArea("File will be written here", 10, 25);
    JTextArea ta2=new JTextArea("Stemmed File will be written here", 10, 25);
    final JLabel statusbar =
                  new JLabel("Output of your selection will go here");
    // Create a file chooser that opens up as an Open dialog
    openButton.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent ae) {
         JFileChooser chooser = new JFileChooser();
         chooser.setMultiSelectionEnabled(true);
         int option = chooser.showOpenDialog(Test_Stemmer.this);
         if (option == JFileChooser.APPROVE_OPTION) {
           File[] sf = chooser.getSelectedFiles();
           String filelist = "nothing";
           if (sf.length > 0) filelist = sf[0].getName();
           for (int i = 1; i < sf.length; i++) {
             filelist += ", " + sf.getName();
    statusbar.setText("You chose " + filelist);
    else {
    statusbar.setText("You canceled.");
    // Create a file chooser that opens up as a Save dialog
    saveButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    JFileChooser chooser = new JFileChooser();
    int option = chooser.showSaveDialog(Test_Stemmer.this);
    if (option == JFileChooser.APPROVE_OPTION) {
    statusbar.setText("You saved " + ((chooser.getSelectedFile()!=null)?
    chooser.getSelectedFile().getName():"nothing"));
    else {
    statusbar.setText("You canceled.");
    // Create a file chooser that allows you to pick a directory
    // rather than a file
    dirButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int option = chooser.showOpenDialog(Test_Stemmer.this);
    if (option == JFileChooser.APPROVE_OPTION) {
    statusbar.setText("You opened " + ((chooser.getSelectedFile()!=null)?
    chooser.getSelectedFile().getName():"nothing"));
    else {
    statusbar.setText("You canceled.");
    c.add(openButton);
    c.add(saveButton);
    c.add(dirButton);
    c.add(statusbar);
    c.add(ta);
    c.add(ta2);
    public static void main(String args[]) {
    Test_Stemmer sfc = new Test_Stemmer();
    sfc.setVisible(true);
    }could you please help me, and tell me what to add or to modify,,
    Thank you..                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    realahmed8 wrote:
    thanks masijade,
    i have filter the file chooser for only text files,
    but i still don't know how to use FileReader to put text file content to the text area (ta) ..
    please tell me how and where to use it..How? -- See the IO Tutorials on Sun for the FileReader (and I assume you know how to call setText and append in the JTextArea).
    Where? -- In the actionPerformed method (better would be a separate thread that is triggered through the actionPerformed method, but that is probably beyond you at the moment), of course.
    Give it a try.

  • How can I add append text to a text box?

    I want to have it so I can add data to the textbox, through my program, and not overwrite what's currently in there. I'd also like to have new lines indented. Ex.
    I have:
    cp C:\Test C:\Test2
    I want to just add a console response as such:
    cp C:\Test C:\Test2
    Copy Successful
    I'm writing my own console like program. I'm not trying to actually get input from the system.

    Hi,
    You can use the append() method of the TextArea.
    For example:
    showText=new JTextArea(" ", 10, 20);
    showText.append("First\n");
    showText.append("\tSecond");\\adding a tab space
    Output:
    First
    Second
    Bye
    -Dani

  • Editable and Non editable portion in JTextArea

    hi all
    i have following problem:
    in my application i m using JTextArea and JButton when button is clicked some text is added as follows with append method
    textarea.append("darshan");
    textarea.append("\n\n");
    textarea.append("gajjar");
    now i want the text in textarea noneditable (ie 'darshan','gajjar') while other portion is editable (ie '\n\n')
    it means i can enter or change text between two texts 'darshan' and 'gajjar' but i can not edit 'darshan' and 'gajjar'.
    and finally i want to save thest text in a file
    please help me
    thanks
    darshan

    Hi,
    You have to use JEditorPane and linkit with extended HTMLDocument.
    this methods override HTMLDocument methods and make the content between
    to tags (in this example between tag<template>) not editable. There are some bugs to fix here but i hope that this will help.
    kit object is HTMLEditorKit instance of current JEditorPane editor kit.
    public void insertString(int offs, String str, AttributeSet a) throws
          BadLocationException {
        if (kit == null) {
          super.insertString(offs, str, a);
          return;
        if (!canEditTemplate) {
          Element curTag = kit.getCharacterAttributeRun();
          Element parent = curTag.getParentElement();
          try {
            int i = 0;
            for (; i < parent.getElementCount(); i++) {
              if (parent.getElement(i).equals(curTag)) {
                break;
            if (i != 0) {
              Element prev = parent.getElement(i - 1);
              Element next = parent.getElement(i + 1);
              if (prev.getName().equalsIgnoreCase("template") &&
                  next.getName().equalsIgnoreCase("template")) {
                System.out.println("Tempate element not editable");
                return;
          catch (ArrayIndexOutOfBoundsException exxx) {}
          catch (NullPointerException exe) {
            System.out.println("nullPointer in template insert");
        super.insertString(offs, str, a);
      public void remove(int offs,
                         int len) throws BadLocationException {
        if (!canEditTemplate) {
          if (kit == null) {
            super.remove(offs, len);
            return;
          Element curTag = kit.getCharacterAttributeRun();
          Element parent = curTag.getParentElement();
          try {
            int i = 0;
            for (; i < parent.getElementCount(); i++) {
              if (parent.getElement(i).equals(curTag)) {
                break;
            if (i != 0) {
              Element prev = parent.getElement(i - 1);
              Element next = parent.getElement(i + 1);
              if (prev.getName().equalsIgnoreCase("template") &&
                  next.getName().equalsIgnoreCase("template")) {
                System.out.println("Tempate element not editable");
                return;
          catch (ArrayIndexOutOfBoundsException exxx) {}
          catch (NullPointerException exe) {
            System.out.println("nullPointer in template remove");
            return;
        super.remove(offs, len);

Maybe you are looking for

  • ISAPI Filter IIS

    Hi All, We're trying to install OAS SSO Plugin in a IIS Server, we have made every step as described in Appendix B (Using Oracle Application Server SSO Plug In) but we haven't been able to load ISAPI Filter and get green in our IIS Console. Could any

  • IMessage in my iPad is not working for pictures

    I can't send pictures through iMessage on my iPad, I can receive pictures. This has been going on for quite some time now. I was able to use iMessage for pictures without a problem before, anyone knows if there's something wrong? I am not sure if thi

  • NVL with host variables in a where clause

    Does anyone know if using a host variable in a WHERE clause with the NVL function will actually work if the host variable is null without using the indicator variable too? In other words if the variable ":new_prmy_numb" which was selected previously

  • IPhoto 09/08 interoperability?

    I do an admittedly very dangerous thing with iPhoto. I have my iPhoto library stored on a shared drive, on an underpowered G4 iMac, that is running Tiger (10.4.11). I run iPhoto on the iMac, but I also run iPhoto on my MacBook Pro, and access the lib

  • What is the usable space of normal redundancy disk group with two uneven capacity fail groups

    Hi, I have a normal redundancy disk group (DATA) with two uneven capacity fail groups (FG1 and FG2). FG1 size is 10GB and FG2 size is 100GB. In this case what will be the usable space of the disk group (DATA)? is it 10G or 55G? Thanks, Mahi