Appending JTextArea

I have a problem with the javax.swing.JTextArea.
I have:
JTextArea mytextarea = new JTextArea(5,5);
JScrollPane myscrollpane = new JScrollPane(mytextarea);
The most common order:
mytextarea.append("some_text_larger_than_the_visible_area");
would append the text, but only sometimes scrolls to the end of the appended text. Threfeore I wouldn't always even notice if some text has been appended. How can I make the program always to scroll to the end section of the appended text?
Thanks

Hi again,
you should figure out, if JTextArea is the right class for you - it is for plain text, in one font, in one size, in one color only - if you like to extend your display with colors, multiple fonts and so on, you are trapped with JTextArea because it can't do the job.
JTextPane has more possibilites - by using a DefaultStyledDocument in it, it is capable of displaying multi-color multi-fonts text - you have a little more to do, to get it work, but it is more flexible than JTextArea.
If you wonder, why the caret is set in an non-editable context also - setting of the caret dont edit a text and setting the caret by mouseclick and keep track of the message for the changing of the caret, is an easy way to find out, where in the text the user clicks. I use that to generate commands for the MUD by extracting the word at the clicked position and than process them to generate a MUD-command.
There is one point, that is really evil - when the user scrolls up with the scroller and text is expanded in that moment, the scroller is adjusted to the end of the text - if the Area displays incoming text from a MUD for example, then the user is not able to scroll up, if the lines come in to quickly - the caret than must be adjusted to the position before the end of the text or so, to prevent being adjusted by the appended text.
greetings Marsian

Similar Messages

  • How to append a file directory and its contents in a jTextArea

    how will i display the contents of this file and file directory in a jTextArea or ...let's say it will display the content of "c:/AutoArchive2007-05-24.csv" in a jTextarea
    say this file "c:/AutoArchive2007-05-24.csv"contains the ff:details
    user:jeff AutoArchive-Process Started at Thu May 24 15:41:54 GMT+08:00 2007
    and ended at Thu May 24 15:41:54 GMT+08:00 2007
    Message was edited by:
    ryshi1264

    use the append(...) to append data to the text area.

  • JTextArea append problem

    I have the following problem:
    I am creating a JFrame with a JTextArea in it.
    After all components are added to the JFrame
    I call:
    setLocation(100, 100);
    pack();
    setVisible(true);
    Then a method is called that generates files and uses
    jTextArea.append(".");
    to add a "." to the JTextArea for each created file
    to show the progress.
    Now the problem is that the dots are not shown one after the other.
    The window pops up AFTER all the dots are written and not when
    setVisible(true);
    is called.
    What do I have to do that every single dot is shown in the
    JTextArea right after it is appended ?

    Move your actual file generating process to a different thread. The best way to do it is using SwingWorker. There is a tutorial on the Sun's web site at http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html that demonstrates how to use SwingWorker.
    Hope this helps
    Sai Pullabhotla

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

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

  • Question on JTextArea.append(String str)

    Hi All,
    When i provide JTextArea.append("FMTL") it is showing me on the JTextArea but when i give it as
    String item="Viswanadh";
    JTextArea.append(item).this particular statement is remaming blank on the TextArea.
    Any idea why this is happening and is there any other method to be used instead of append.???
    Thanks in advance..
    regards,
    Viswanadh

    class OnApplyFormat implements ActionListener{
         public void actionPerformed(ActionEvent formatevent){
              JComboBox source = (JComboBox) formatevent.getSource();
                   String item =  source.getSelectedItem().toString();
                     System.out.println("Selected Format is:"+item);
                     try
                       if ( item!=null )
                              System.out.println("Format is:"+item);
                     infoarea.append("FMTL");
                   infoarea.append(item);
                     infoarea.append("\r\n");
                   infoarea.append("FMTU");
                   infoarea.append("\r\n");
                   infoarea.append("wait 5");
                   infoarea.append("\r\n");
              else
                   throw new Exception("FormatNotFoundException");
                          }catch(Exception e){
                          e.printStackTrace();
    }That is my code and still i am facing the same FMTL is not getting appended with the item variable.
    Help me in solving this issue.
    Thanks in advance.
    regards,
    Viswanadh

  • Doubt to be Clarified on JTextArea appending a string

    Hi All,
    Here is the actual code.
    String msg="Settings Details Will be Produced after the Connection is Successful";
                        String msg1=      "-------------------------------------------------------------------------";
                        String comdetails="1)Comport Enabled is:";
                        String baudratedetails="2)BaudRate Selected is:";
                        String databitdetails="3)DataBit is:";
                        String paritybitdetails="4)ParityBit is:";
                        String stopbitdetails="5)Stopbit is:";
    contentarea.setText("");
                           contentarea.append(msg);
                        contentarea.append("\r\n");
                        contentarea.append(msg1);
                        contentarea.append("\r\n");
                        contentarea.append(msg1);
                        contentarea.append("\r\n");
                        contentarea.append(comdetails);contentarea.append(cv);
                        contentarea.append("\r\n");
                        contentarea.append(baudratedetails);contentarea.append(bv);
                        contentarea.append("\r\n");
                        contentarea.append(databitdetails);contentarea.append(dv);
                        contentarea.append("\r\n");
                        contentarea.append(paritybitdetails);contentarea.append(pv);
                        contentarea.append("\r\n");
                        contentarea.append(stopbitdetails);contentarea.append(sv);
                        contentarea.append("\r\n");
                        contentarea.append(msg1);
                        contentarea.append("\r\n");
                        contentarea.append(msg1);I have a JTextArea which is basically linked up with a JBUtton.So when i click on JButton in the JTextArea thte following will be displayed.
    "Settings Details Will be Produced after the Connection is Successful"
    1)Comport Enabled is:COM3
    2)BaudRate Selected is:38400
    3)DataBit is:8bit
    4)ParityBit is:NONE
    5)Stopbit is:1bitSo my question when i again click on the same JButton the same data which is highlighted in the code tags need to be displayed again from the next end line of the previous data instead of overriding operation.Can any one help me out in doing this???
    Thanks in advance.
    regards,
    Viswanadh

    Hi toodburch,
    Thanks for the reply.My requirement is for every click on the JButton it should be in the following way.Assume i have pressed 3 times.then it should be displayed as shown.
    "Settings Details Will be Produced after the Connection is Successful"
    1)Comport Enabled is:COM3
    2)BaudRate Selected is:38400
    3)DataBit is:8bit
    4)ParityBit is:NONE
    5)Stopbit is:1bit
    "Settings Details Will be Produced after the Connection is Successful"
    1)Comport Enabled is:COM3
    2)BaudRate Selected is:38400
    3)DataBit is:8bit
    4)ParityBit is:NONE
    5)Stopbit is:1bit
    "Settings Details Will be Produced after the Connection is Successful"
    1)Comport Enabled is:COM3
    2)BaudRate Selected is:38400
    3)DataBit is:8bit
    4)ParityBit is:NONE
    5)Stopbit is:1bitThanks
    regards,
    Viswanadh

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

  • 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 text always has \n appended, why?

    I have a JTextArea with custom extension of PlainDocument. When the text area is going
    away, I write the text to an ArrayList for later use with the following code. Every time the
    document gets flushed it contains an extra '\n', even if the user never touched it. Is this
    normal behavior?
    private void flushElement(Element element, ArrayList stringList) {
    String content = null;
    int children = element.getElementCount();
    if (children>0) {
    for (int i = 0; i < children; i++) {
    flushElement(element.getElement(i), stringList);
    } else {
    try {
    if (element.isLeaf()) {
    AbstractDocument.LeafElement leaf = (AbstractDocument.LeafElement)element;
    int offset = leaf.getStartOffset();
    int length = leaf.getEndOffset()-offset;
    if (length>0) {
    content = doc.getText(offset, length);
    stringList.add(content);
    } catch (BadLocationException ble) {

    Sometimes a bit of sleep is better than any thinking!
    I had an idea this morning and it seams to be working. I change the recursive method to:
         private void writeDocRec(javax.swing.text.Element element,
                   DefaultStyledDocument doc) {
              if (element.isLeaf()) return;
              for (int i=0; i<element.getElementCount(); i++) {
                   javax.swing.text.Element child = element.getElement(i);
                   if (child.isLeaf()) {
                        int start = child.getStartOffset();
                        int end = child.getEndOffset();
                        int len = doc.getLength();
                        if (end > len) System.out.println("len " + len
                                  + " start " + start + " end " + end);
                        else System.out.print(this.getTextOfElement(child, doc)
                                  + "END OF ELEMENT\n");
                   writeDocRec(child, doc);
         }I found that the last element, that I do NOT want and that contains that \n has endIndex > doc.getLength(). So if I find an element that satisfies this condition I know it is the last, not wanted element, and skip it. Does it make any sense to have an element with index > length?
    Do you think that this is a good solution? Or is it some kind of trial and error and not really understanding what is going on?
    I would appreciate some advices. Thank you!
    Annette

  • To refresh the contents in JTextArea on selection of a row in JTable.

    This is the block of code that i have tried :
    import java.awt.GridBagConstraints;
    import java.awt.SystemColor;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.table.DefaultTableModel;
    import ui.layouts.ComponentsBox;
    import ui.layouts.GridPanel;
    import ui.layouts.LayoutConstants;
    import util.ui.UIUtil;
    public class ElectronicJournal extends GridPanel {
         private boolean DEBUG = false;
         private boolean ALLOW_COLUMN_SELECTION = false;
    private boolean ALLOW_ROW_SELECTION = true;
         private GridPanel jGPanel = new GridPanel();
         private GridPanel jGPanel1 = new GridPanel();
         private GridPanel jGPanel2 = new GridPanel();
         DefaultTableModel model;
         private JLabel jLblTillNo = UIUtil.getHeaderLabel("TillNo :");
         private JLabel jLblTillNoData = UIUtil.getBodyLabel("TILL123");
         private JLabel jLblData = UIUtil.getBodyLabel("Detailed View");
         private JTextArea textArea = new JTextArea();
         private JScrollPane spTimeEntryView = new JScrollPane();
         private JScrollPane pan = new JScrollPane();
         String html= " Item Description: Price Change \n Old Price: 40.00 \n New Price: 50.00 \n Authorized By:USER1123 \n";
         private JButton jBtnExporttoExcel = UIUtil.getButton(85,
                   "Export to Excel - F2", "");
         final String[] colHeads = { "Task No", "Data", "User ID", "Date Time",
                   "Description" };
         final Object[][] data = {
                   { "1", "50.00", "USER123", "12/10/2006 05:30", "Price Change" },
                   { "2", "100.00", "USER234", "15/10/2006 03:30", "Price Change12345"},
         final String[] colHeads1 = {"Detailed View" };
         final Object[][] data1 = {
                   { "Task:Price Change", "\n"," Old Price:50.00"," \n ","New Price:100.00"," \n" }
         JTable jtblTimeEntry = new JTable(data, colHeads);
         JTable jTbl1 = new JTable(data1,colHeads1);
         ComponentsBox jpBoxButton = new ComponentsBox(LayoutConstants.X_AXIS);
         public ElectronicJournal() {
              super();
              jtblTimeEntry.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              if (ALLOW_ROW_SELECTION) { // true by default
    ListSelectionModel rowSM = jtblTimeEntry.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    //Ignore extra messages.
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    System.out.println("No rows are selected.");
    } else {
    int selectedRow = lsm.getMinSelectionIndex();
    System.out.println("Row " + selectedRow
    + " is now selected.");
    textArea.append("asd \n 123 \n");
    } else {
         jtblTimeEntry.setRowSelectionAllowed(false);
              if (DEBUG) {
                   jtblTimeEntry.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
         printDebugData(jtblTimeEntry);
              initialize();
         private void printDebugData(JTable table) {
    int numRows = table.getRowCount();
    int numCols = table.getColumnCount();
    javax.swing.table.TableModel model = table.getModel();
    System.out.println("Value of data: ");
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + model.getValueAt(i, j));
    System.out.println();
    System.out.println("--------------------------");
         private void initialize() {
              this.setSize(680, 200);
              this.setBackground(java.awt.SystemColor.control);
              jBtnExporttoExcel.setBackground(SystemColor.control);
              ComponentsBox cmpRibbonHORZ = new ComponentsBox(LayoutConstants.X_AXIS);
              cmpRibbonHORZ.addComponent(jBtnExporttoExcel, false);
              jpBoxButton.add(cmpRibbonHORZ);
              this.addFilledComponent(jGPanel, 1, 1, 1, 1, GridBagConstraints.BOTH);
              this.addFilledComponent(jGPanel1, 2, 1, 11, 5, GridBagConstraints.BOTH);
              this.addFilledComponent(jGPanel2, 2, 13, 17, 5, GridBagConstraints.BOTH);
              jGPanel.setSize(650, 91);
              jGPanel.setBackground(SystemColor.control);
              jGPanel.addFilledComponent(jLblTillNo,1,1,GridBagConstraints.WEST);
              jGPanel.addFilledComponent(jLblTillNoData,1,10,GridBagConstraints.BOTH);
              jGPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,0));
              jGPanel1.setBackground(SystemColor.control);
              jGPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0,
                        0));
              spTimeEntryView.setViewportView(jtblTimeEntry);
              jGPanel1.addFilledComponent(spTimeEntryView, 1, 1, 11, 4,
                        GridBagConstraints.BOTH);
              jGPanel2.addFilledComponent(jLblData,1,1,GridBagConstraints.WEST);
              jGPanel2.setBackground(SystemColor.control);
              jGPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0,
                        0));
              //textArea.setText(html);
              pan.setViewportView(textArea);
         int selectedRow = jTbl1.getSelectedRow();
              System.out.println("selectedRow ::" +selectedRow);
              int colCount = jTbl1.getColumnCount();
              System.out.println("colCount ::" +colCount);
              StringBuffer buf = new StringBuffer();
              System.out.println("Out Of For");
              /*for(int count =0;count<colCount;count++)
              {System.out.println("Inside For");
              buf.append(jTbl1.getValueAt(selectedRow,count));
              // method 1 : Constructs a new text area with the specified text. 
              textArea  =new JTextArea(buf.toString());
              //method 2 :To Append the given string to the text area's current text.   
             textArea.append(buf.toString());
              jGPanel2.addFilledComponent(pan,2,1,5,5,GridBagConstraints.BOTH);
              this.addAnchoredComponent(jpBoxButton, 7, 5, 11, 5,
                        GridBagConstraints.CENTER);
    This code displays the same data on the JTextArea everytime i select each row,but my requirement is ,it has to refresh and display different datas in the JTextArea accordingly,as i select each row.Please help.Its urgent.
    Message was edited by: Samyuktha
    Samyuktha

    Please help.Its urgentThen why didn't you use the formatting tags to make it easier for use to read the code?
    Because of the above I didn't take a close look at your code, but i would suggest you should be using a ListSelectionListener to be notified when a row is selected, then you just populate the text area.

  • How to refresh a JPanel/JTextArea

    My main problem is that I don't know how to correctly refresh a JTextArea in an Applet. I have an Applet with 2 internal frames. Each frame is comprised of a JPanel.
    The first internal frame calls the second one as shown below:
    // Set an internal frame for Confirmation and import the Confirm class into it//
    Container CF = nextFrame.getContentPane();
    //<Jpanel>
    confirmation = new Confirmation( );
    CF.add ( confirmation, BorderLayout.CENTER );
    mFrameRef.jDesktopPane1.add(nextFrame,JLayeredPane.MODAL_LAYER);
    currentFrame.setVisible(false); // Hide this Frame
    nextFrame.setVisible(true); // Show Next Frame/Screen of Program
    confirmation (Jpanel) has a JTextArea in it. When it's called the first time it displays the correct information (based on choices from the first frame). If a user presses the back button (to return to first frame) and changes something, it doesn't refresh in the JTextArea when they call the confirmation(Jpanel) again. I used System.out.println (called right after jtextareas code), and it shows the info has indeed changed...I guess I don't know how to correctly refresh a JTextArea in an Applet. Here is the relevent code for the 2nd Internal Frame (confirmation jpanel):
    // Gather Info to display to user for confirmation //
    final JTextArea log = new JTextArea(10,35);
    log.setMargin(new Insets(5,5,5,5));
    log.setEditable(false);
    log.append("Name: " storeInfoRef.getFirstName() " "
    +storeInfoRef.getLastName() );
    log.append("\nTest Project: " +storeInfoRef.getTestProject() );
    JScrollPane logScrollPane = new JScrollPane(log);

    Here is the relevant code that I am having the problem with...
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    public class Confirmation extends JPanel {
    // Variables declaration
    private StoreInfo storeInfoRef; // Reference to StoreInfo
    private MFrame mFrameRef; // Reference to MFrame
    private Progress_Monitor pmd; // Ref. to Progress Monitor
    private JLabel ConfirmMessage; // Header Message
    private JButton PrevButton;                // Navigation Button btwn frames
    private JInternalFrame prevFrame, currentFrame; // Ref.to Frames
    // End of variables declaration
    public Confirmation(MFrame mFrame, StoreInfo storeInfo) {
    mFrameRef = mFrame; // Reference to MFrame
    storeInfoRef = storeInfo; // Reference to Store Info
    prevFrame = mFrameRef.FileChooserFrame; // Ref. to Previous Frame
    currentFrame = mFrameRef.ConfirmationFrame; // Ref. to this Frame
    initComponents();
    // GUI for this class //
    private void initComponents() {
    ConfirmMessage = new JLabel();
    PrevButton = new JButton();
    UploadButton = new JButton();
    setLayout(new GridBagLayout());
    GridBagConstraints gridBagConstraints1;
    ConfirmMessage.setText("Please confirm that the information "
    +"entered is correct");
    add(ConfirmMessage, gridBagConstraints1);
    // Gather Info to display to user for confirmation //
    final JTextArea log = new JTextArea(10,35);
    log.setMargin(new Insets(5,5,5,5));
    log.setEditable(false);
    log.append("Name: " storeInfoRef.getFirstName() " "
    +storeInfoRef.getLastName() );
    log.append("\nTest Project: " +storeInfoRef.getTestProject() );
    log.append("\nTest Director: " +storeInfoRef.getTestDirector() );
    log.append("\nTest Location: " +storeInfoRef.getTestLocation() );
    log.append("\nDate: " +storeInfoRef.getDate() );
    String fileOutput = "";
    Vector temp = new Vector( storeInfoRef.getFiles() );
    for ( int v=0; v < temp.size(); v++ )
    fileOutput += "\n " +temp.elementAt(v);  // Get File Names
    log.append("\nFile: " +fileOutput );
    // log.repaint();
    // log.validate();
    // log.revalidate();
    JScrollPane logScrollPane = new JScrollPane(log);
    System.out.println("Name: " storeInfoRef.getFirstName() " " +storeInfoRef.getLastName() );
    System.out.println("Test Project: " +storeInfoRef.getTestProject() );
    System.out.println("Test Director: " +storeInfoRef.getTestDirector() );
    System.out.println("Test Location: " +storeInfoRef.getTestLocation() );
    System.out.println("Date: " +storeInfoRef.getDate() );
    System.out.println("File: " +fileOutput );
    // End of Gather Info //
    add(logScrollPane, gridBagConstraints1);
    PrevButton.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
    PrevButtonMouseClicked(evt);
    PrevButton.setText("Back");
    JPanel Buttons = new JPanel();
    Buttons.add(PrevButton);
    add(Buttons, gridBagConstraints1);
    // If User Presses 'Prev' Button //
    private void PrevButtonMouseClicked(java.awt.event.MouseEvent evt) {
    try
    currentFrame.setVisible(false); // Hide this Frame
    prevFrame.setVisible(true); // Show Next Frame/Screen of Program
    catch ( Throwable e ) // If A Miscellaneous Error
    System.err.println( e.getMessage() );
    e.printStackTrace( System.err );
    }// End of Confirmation class

  • How to repaint a JTextArea inside a JScrollPane

    I am trying to show some messages (during a action event generated process) appending some text into a JTextArea that is inside a JScrollPane, the problem appears when the Scroll starts and the text appended remains hidden until the event is completely dispatched.
    The following code doesnt run correctly.
    ((JTextArea)Destino).append('\n' + Mens);
    Destino.revalidate();
    Destino.paint(Destino.getGraphics());
    I tried also:
    Destino.repaint();
    Thanks a lot in advance

    Correct me if I am wrong but I think you are saying that you are calling a method and the scrollpane won't repaint until the method returns.
    If that is so, you need to use threads in order to achieve the effect you are looking for. Check out the Model-View-Contoller pattern also.

Maybe you are looking for