Scrolling of a JTextArea in a JScrollPane

I have a JTextArea in a JScrollPane.
It is for a chat and I am constantly appending messages at the bottom of the JTextArea.
Currently the scrollPanel is scrolling the view so the last line is visible for quite some lines, which is what I want, but from a certain amount of text in the textarea it stops doing that.
Why does it scroll along at first and then suddenly stops?

Actually it is a JTextPane instead of JTextArea. My bad.
And actually it are 2 JTextPanes with a common Document where I am appending the text on (and at the appending I don't have the references to the textpanes).
Maybe I can add document listeners to the components that have the refs to the textpanes and set the caret position there?

Similar Messages

  • Invisible JTextArea in a JScrollPane

    I want to have an invisible JTextArea in a JScrollPane (i only want a thin border either vieport border or JTextArea border). i tried setOpaque(false) for JTextArea, JScrollPane and both, and it wont work, i dont know why. Could anyone help me?

    This poster is 0 for 3 in responding to previous postings he has made.I did notice - that's why I didn't post the link.
    he/she might now learn how to do a search (for when future questions are ignored)
    What do you think the chances are he'll bother to thank anyone for the help
    he received on this posting?Nil
    a 'thank you' does go a long way to getting the next query answered, but I'd prefer just
    an acknowledement of "it works/doesn't work" - makes it so much easier, when
    searching the forums, when you spot a "yes, that works" at the end.

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

  • Swing bug?: scrolling BLIT_SCROLL_MODE painting JTextArea components hangs

    java version "1.5.0_04"
    Hello,
    When drawing JComponent Text Areas and dynamically scrolling, Java gets confused, gets the shivers and freezes when the viewport cannot get its arms around the canvas. ;)
    Possible problem at JViewport.scrollRectToVisible().
    When painting non-text area components eg. graphics circles, it is ok.
    Have provided example code. This code is based on the ScrollDemo2 example provided in the Sun Java
    Tutorial
    thanks,
    Anil Philip
    juwo LLC
    Usage: run program and repeatedly click the left mouse button near right boundary to create a new JComponent node each time and to force scrolling area to increase in size to the right.
    When the first node crosses the left boundary, then the scroll pane gets confused, gets the shivers and hangs.
    The other scroll modes are a bit better - but very slow leaving the toolbar (in the oroginal application) unpainted sometimes.
    * to show possible bug when in the default BLIT_SCROLL_MODE and with JTextArea components.
    * author: Anil Philip. juwo LLC. http://juwo.com
    * Usage: run program and repeatedly click the left mouse button near right boundary to
    * create a new JComponent node each time and to force scrolling area to increase in size to the right.
    * When the first node crosses the left boundary, then the scroll pane gets confused, gets the shivers
    and hangs.
    * The other scroll modes are a bit better - but very slow leaving the toolbar (in the oroginal
    application)
    * unpainted sometimes.
    * This code is based on the ScrollDemo2 example provided in the Sun Java Tutorial (written by John
    Vella, a tutorial reader).
    import javax.swing.*;
    import javax.swing.border.EtchedBorder;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    /* ScrollDemo2WithBug.java is a 1.5 application that requires no other files. */
    public class ScrollDemo2WithBug extends JPanel {
    private Dimension area; //indicates area taken up by graphics
    private Vector circles; //coordinates used to draw graphics
    private Vector components;
    private JPanel drawingPane;
    public ScrollDemo2WithBug() {
    super(new BorderLayout());
    area = new Dimension(0, 0);
    circles = new Vector();
    components = new Vector();
    //Set up the instructions.
    JLabel instructionsLeft = new JLabel(
    "Click left mouse button to place a circle.");
    JLabel instructionsRight = new JLabel(
    "Click right mouse button to clear drawing area.");
    JPanel instructionPanel = new JPanel(new GridLayout(0, 1));
    instructionPanel.add(instructionsLeft);
    instructionPanel.add(instructionsRight);
    //Set up the drawing area.
    drawingPane = new DrawingPane();
    drawingPane.setBackground(Color.white);
    drawingPane.setPreferredSize(new Dimension(200, 200));
    //Put the drawing area in a scroll pane.
    JScrollPane scroller = new JScrollPane(drawingPane);
    // scroller.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
    if(scroller.getViewport().getScrollMode() == JViewport.BACKINGSTORE_SCROLL_MODE)
    System.out.println("BACKINGSTORE_SCROLL_MODE");
    if(scroller.getViewport().getScrollMode() == JViewport.BLIT_SCROLL_MODE)
    System.out.println("BLIT_SCROLL_MODE");
    if(scroller.getViewport().getScrollMode() == JViewport.SIMPLE_SCROLL_MODE)
    System.out.println("SIMPLE_SCROLL_MODE");
    //Lay out this demo.
    add(instructionPanel, BorderLayout.PAGE_START);
    add(scroller, BorderLayout.CENTER);
    /** The component inside the scroll pane. */
    public class DrawingPane extends JPanel implements MouseListener {
    private class VisualNode {
    int x = 0;
    int y = 0;
    int id = 0;
    public VisualNode(int id, int x, int y) {
    this.id = id;
    this.x = x;
    this.y = y;
    title.setLineWrap(true);
    title.setAlignmentY(Component.TOP_ALIGNMENT);
    titlePanel.add(new JButton("Hi!"));
    titlePanel.add(title);
    nodePanel.add(titlePanel);
    nodePanel.setBorder(BorderFactory
    .createEtchedBorder(EtchedBorder.RAISED));
    box.add(nodePanel);
    ScrollDemo2WithBug.this.drawingPane.add(box);
    Box box = Box.createVerticalBox();
    Box titlePanel = Box.createHorizontalBox();
    JTextArea title = new JTextArea(1, 10); // 1 rows x 10 cols
    Box nodePanel = Box.createVerticalBox();
    public void paintNode(Graphics g) {
    int ix = (int) x + ScrollDemo2WithBug.this.getInsets().left;
    int iy = (int) y + ScrollDemo2WithBug.this.getInsets().top;
    title.setText(id + " (" + ix + "," + iy + ") ");
    box.setBounds(ix, iy, box.getPreferredSize().width, box
    .getPreferredSize().height);
    int n = 0;
    DrawingPane() {
    this.setLayout(null);
    addMouseListener(this);
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.fill3DRect(10, 10, 25, 25, true);
    Point point;
    for (int i = 0; i < circles.size(); i++) {
    point = (Point) circles.elementAt(i);
    VisualNode node = (VisualNode) components.get(i);
    node.paintNode(g);
    //Handle mouse events.
    public void mouseReleased(MouseEvent e) {
    final int W = 100;
    final int H = 100;
    boolean changed = false;
    if (SwingUtilities.isRightMouseButton(e)) {
    //This will clear the graphic objects.
    circles.removeAllElements();
    area.width = 0;
    area.height = 0;
    changed = true;
    } else {
    int x = e.getX() - W / 2;
    int y = e.getY() - H / 2;
    if (x < 0)
    x = 0;
    if (y < 0)
    y = 0;
    Point point = new Point(x, y);
    VisualNode node = new VisualNode(circles.size(), point.x,
    point.y);
    // add(node);
    components.add(node);
    circles.addElement(point);
    drawingPane.scrollRectToVisible(new Rectangle(x, y, W, H));
    int this_width = (x + W + 2);
    if (this_width > area.width) {
    area.width = this_width;
    changed = true;
    int this_height = (y + H + 2);
    if (this_height > area.height) {
    area.height = this_height;
    changed = true;
    if (changed) {
    //Update client's preferred size because
    //the area taken up by the graphics has
    //gotten larger or smaller (if cleared).
    drawingPane.setPreferredSize(area);
    //Let the scroll pane know to update itself
    //and its scrollbars.
    drawingPane.revalidate();
    drawingPane.repaint();
    public void mouseClicked(MouseEvent e) {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    public void mousePressed(MouseEvent e) {
    * Create the GUI and show it. For thread safety, this method should be
    * invoked from the event-dispatching thread.
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("ScrollDemo2");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new ScrollDemo2WithBug();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.setSize(800, 600);
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    }

    I changed the name so you can run this as-is without name clashing. It works okay now.
    import javax.swing.*;
    import javax.swing.border.EtchedBorder;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class SD2 extends JPanel {
        public SD2() {
            super(new BorderLayout());
            //Set up the instructions.
            JLabel instructionsLeft = new JLabel(
                    "Click left mouse button to place a circle.");
            JLabel instructionsRight = new JLabel(
                    "Click right mouse button to clear drawing area.");
            JPanel instructionPanel = new JPanel(new GridLayout(0, 1));
            instructionPanel.add(instructionsLeft);
            instructionPanel.add(instructionsRight);
            //Set up the drawing area.
            DrawingPane drawingPane = new DrawingPane(this);
            drawingPane.setBackground(Color.white);
            drawingPane.setPreferredSize(new Dimension(200, 200));
            //Put the drawing area in a scroll pane.
            JScrollPane scroller = new JScrollPane(drawingPane);
            // scroller.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
            if(scroller.getViewport().getScrollMode() == JViewport.BACKINGSTORE_SCROLL_MODE)
                System.out.println("BACKINGSTORE_SCROLL_MODE");
            if(scroller.getViewport().getScrollMode() == JViewport.BLIT_SCROLL_MODE)
                System.out.println("BLIT_SCROLL_MODE");
            if(scroller.getViewport().getScrollMode() == JViewport.SIMPLE_SCROLL_MODE)
                System.out.println("SIMPLE_SCROLL_MODE");
            //Lay out this demo.
            add(instructionPanel, BorderLayout.PAGE_START);
            add(scroller, BorderLayout.CENTER);
         * Create the GUI and show it. For thread safety, this method should be
         * invoked from the event-dispatching thread.
        private static void createAndShowGUI() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("ScrollDemo2");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new SD2();
            newContentPane.setOpaque(true);      //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.setSize(800, 600);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    /** The component inside the scroll pane. */
    class DrawingPane extends JPanel implements MouseListener {
        SD2 sd2;
        private Dimension area;     //indicates area taken up by graphics
        private Vector circles;     //coordinates used to draw graphics
        private Vector components;
        int n = 0;
        final int
            W = 100,
            H = 100;
        DrawingPane(SD2 sd2) {
            this.sd2 = sd2;
            area = new Dimension(0, 0);
            circles = new Vector();
            components = new Vector();
            this.setLayout(null);
            addMouseListener(this);
         * The 'paint' method is a Container method and it passes its
         * Graphics context, g, to each of its Component children which
         * use it to draw themselves into the parent. JComponent overrides
         * this Container 'paint' method and in it calls this method in
         * addition to others - see api. So the children of DrawingPane will
         * each paint themselves. Here you can do custom painting/rendering.
         * But this is not the place to ask components to paint themselves.
         * That would get swing very confused...
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.fill3DRect(10, 10, 25, 25, true);
            g.setColor(Color.red);
            Point point;
            for (int i = 0; i < circles.size(); i++) {
                point = (Point) circles.elementAt(i);
                g.fillOval(point.x-2, point.y-2, 4, 4);
        //Handle mouse events.
        public void mousePressed(MouseEvent e) {
            if (SwingUtilities.isRightMouseButton(e)) {
                //This will clear the graphic objects.
                circles.removeAllElements();
                components.removeAllElements();
                removeAll();                    // to clear the components
                area.width = 0;
                area.height = 0;
                setPreferredSize(area);
                revalidate();
                repaint();
            } else {
                int x = e.getX() - W / 2;
                int y = e.getY() - H / 2;
                if (x < 0)
                    x = 0;
                if (y < 0)
                    y = 0;
                Point point = new Point(x, y);
                VisualNode node = new VisualNode(this, circles.size(), point.x, point.y);
                // add(node);
                components.add(node);       // not needed
                circles.addElement(point);
                checkBoundries(x, y, node);
        private void checkBoundries(int x, int y, VisualNode node) {
            boolean changed = false;
            // since we used the setPreferredSize property to set the size
            // of each box we'll have to use it again to let the JScrollPane
            // know what size we need to show all our child components
            int this_width = (x + node.box.getPreferredSize().width + 2);
            if (this_width > area.width) {
                area.width = this_width;
                changed = true;
            int this_height = (y + node.box.getPreferredSize().height + 2);
            if (this_height > area.height) {
                area.height = this_height;
                changed = true;
            if (changed) {
                //Update client's preferred size because
                //the area taken up by the graphics has
                //gotten larger or smaller (if cleared).
                setPreferredSize(area);
                scrollRectToVisible(new Rectangle(x, y, W, H));
                //Let the scroll pane know to update itself
                //and its scrollbars.
                revalidate();
            repaint();
        public void mouseReleased(MouseEvent e) { }
        public void mouseClicked(MouseEvent e)  { }
        public void mouseEntered(MouseEvent e)  { }
        public void mouseExited(MouseEvent e)   { }
    * We are adding components to DrawingPanel so there is no need to get
    * into the paint methods of DrawingPane. Components are designed to draw
    * themseleves when their parent container passes them a Graphics context
    * and asks them to paint themselves into the parent.
    class VisualNode {
        DrawingPane drawPane;
        int x;
        int y;
        int id;
        Box box;
        public VisualNode(DrawingPane dp, int id, int x, int y) {
            drawPane = dp;
            this.id = id;
            this.x = x;
            this.y = y;
            box = Box.createVerticalBox();
            Box titlePanel = Box.createHorizontalBox();
            JTextArea title = new JTextArea(1, 10);     // 1 rows x 10 cols
            Box nodePanel = Box.createVerticalBox();
            title.setLineWrap(true);
            title.setAlignmentY(Component.TOP_ALIGNMENT);
            titlePanel.add(new JButton("Hi!"));
            titlePanel.add(title);
            nodePanel.add(titlePanel);
            nodePanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
            box.add(nodePanel);
            // here we are adding a component to drawPane so there is really
            // no need to keep this VisualNode in a collection
            drawPane.add(box);
            int ix = (int) x + drawPane.getInsets().left;
            int iy = (int) y + drawPane.getInsets().top;
            title.setText(id + " (" + ix + "," + iy + ") ");
            // since we are using the preferredSize property to setBounds here
            // we'll need access to it (via box) for the scrollPane in DrawPane
            // so we expose box as a member variable
            box.setBounds(ix, iy, box.getPreferredSize().width,
                                  box.getPreferredSize().height);
    }

  • No Scroll bar with JTextArea on unix machine

    hi am using JTextArea with Unix machine... The problem is not enabling scroll bars
    can anyone help me

    JTextArea agreeTxt;
    agreeTxt = new JTextArea(11, 42);
    agreeTxt.setAutoscrolls(true);
    agreeTxt.setLineWrap(true);
    agreeTxt.setEditable(false);
    JScrollPane pane = new JScrollPane( agreeTxt );Now add the JScrollPane object to your JPanel or where ever you have your JTextArea

  • JTextArea within a JScrollPane

    Hi!
    I've searched through the Project Swing archive and found lots of questions regarding how you ensure that when text is entered into a JTextArea control (via the append() method) the JScrollPane automatically scrolls to the position where the text was appended.
    Unfortunately I haven't yet found a satisfactory solution to this issue.
    I have a JTextArea control within a JScrollPane control. I start a seperate thread in order to perform some processing. This operation being run within this thread needs to provide progress information to the user and I present this progress information via the JTextArera control. Although the information is displayed within the JTextArea the JScrollPane unfortunately doesn't scroll down so that the last message entered into the JTextArea is visible. The user needs to scroll down manually in order to see the messages.
    I have read that if you invoke JTextArea.setText() or JTextArea.append() from within a thread otherthan the event dispatching thread then the JScrollPane will have no knowledge that text as been added. The article suggested using SwingUtilities.invokeLater(Runnable run) to ensure that the call to JTextArea.setText() or JTextArea.append() is performed within the event dispatching thread. I did create a Runnable class whose sole purpose was to call JTextArea.append() with message information but still the JScrollPane fails to automatically scroll as successive lines of text are being added to the JTextArea control.
    Can somebody please shed some light on my problem?

    Here's a simple program that works for me. Note, if you comment out the setCaretPosition() method it stops working.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TestTextArea extends JFrame
         JTextArea textArea;
    public TestTextArea()
         JPanel panel = new JPanel();
         setContentPane( panel );
         panel.setPreferredSize( new Dimension( 200, 200 ) );
              textArea = new JTextArea( "one two", 3, 15 );
              JScrollPane scrollPane = new JScrollPane( textArea );
              panel.add( scrollPane );
              JTextArea textArea2= new JTextArea( "abcd", 3, 15 );
              textArea2.setPreferredSize( new Dimension( 50, 10 ) );
              panel.add( textArea2 );
         public void updateTextArea2()
              int line = 0;
              while ( true )
                   textArea.append( "\nline: " + ++line );
                   textArea.setCaretPosition( textArea.getText().length() );
                   try
                        Thread.sleep(1000);
                   catch (Exception e) {}
    public static void main(String[] args)
    TestTextArea frame = new TestTextArea();
    frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
    frame.pack();
    frame.setVisible(true);
              frame.updateTextArea2();

  • Disabling JTextArea in a JScrollPane

    Hello,
    I have an application that contains some JTextFields
    and a JScrollPane with a JTextArea as the viewport.
    The JTextArea is readonly for displaying messages with
    setEnable to false (setEditable and setFocusable are also false).
    The problem is that I can tab thru the fields fine,
    skipping over the scroll pane, however as soon as a
    message is deposited in the scroll pane things
    screw up. What happens is that as I tab
    down to the scroll pane, I loose my cursor and I
    have to tab again to get it back. It is like it gets lost when I try to tab past scroll pane.
    Is it possible that something is being added to the focus
    cycle when I insert a string into the JTextArea?
    Thanks in Advance
    KarlBH

    Also make sure that the JScrollBars are set to not focus.

  • Disabling "auto scroll to the bottom function" on JScrollPane

    Hi all!
    I have a little problem with JScrollPane.
    I have a JEditor Pane on my JScrollPane which content type is text/html. When the content of html code is too large scrollbars are appear and vertical scrollbar automatically scrolls down to the bottom of my JEditorPane. How can I disable this "function", because I don't want to see the bottom of the page after contet is loaded. (Only in case when the user scrolls down manually.)
    Thanks for your help!

    after loading the file you should be able to use:
    textComponent.setCaretPosition(0);

  • Scroll position and JTextArea

    I hava a JFrame with a JScrollPane/JTextArea in it.
    I frequently update the textarea with a setText(string), but for every update the scrollbar jumps to the bottom. The things is that I want the scrollbar to remember its position and not change its position after an update.
    The string in setText varies in length.
    Any ideas, please.
    Thanks!!

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ScrollingTest {
      static JTextArea textArea;
      static int updateCount = 0;
      static int i;
      public static void main(String[] args) {
        JButton button = new JButton("add data");
        button.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            updateDisplay();
        JPanel panel = new JPanel();
        panel.add(button);
        textArea = new JTextArea();
        textArea.setMargin(new Insets(10,10,10,10));
        textArea.setLineWrap(true);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(panel, "North");
        f.getContentPane().add(new JScrollPane(textArea));
        f.setSize(400,300);
        f.setLocation(400,300);
        f.setVisible(true);
      private static void updateDisplay() {
        String text = "";
        for(i = updateCount; i < 40 + updateCount; i++)
          text += String.valueOf(i) + "\n";
        int caretPosition = textArea.getDocument().getLength();
        textArea.setText(textArea.getText() + text);
        updateCount = i;
        textArea.setCaretPosition(caretPosition);
    }

  • JTextArea within a JScrollPane within a JSplitPane

    public class CamoDataGUI
         JScrollPane primaryPane;
         JTextArea infoTextArea;
         public CamoDataGUI()
              infoTextArea = new JTextArea("Information", 10,10);
              primaryPane = new JScrollPane(infoTextArea);
         public JScrollPane getContent()
              return primaryPane;
    }Its simply not visible. getContent() is being used to provide one of the values for the SplitPane constructor that asks for an orientation and a left and right component.
    any ideas as to why its MIA?
    Thanks!

    I would like to apologize before anyone responds. I added the wrong class into the constructor of my splitpane.

  • JTextArea in  a JScrollPane autoscrolling chatroom...

    How can I get the JScrollPane to autoscroll and stay at the bottom? It can't be locked at the bottom either because you couldn't scroll up to see what someone had said earlier. Any idea's on this? I'm stumped.

    Sorry, don't have an answer for your latest question, but I was thinking about another of your questions. You only want it to scroll down if it is already at the bottom (like most chat clients). Try:
    JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
    if(scrollBar.getValue() == scrollBar.getMaximum() )
        scrollBar.setValue( scrollBar.getMaximum() );Except that won't work because you'll have already added a line, and the scrollbar won't be at maximum. You could introduce a window, ie, if the scrollbar value is within 5 of the maximum, keep scrolling down.... but if someone sends a message longer than 5 lines, you're screwed....
    Seemed like a good idea to begin with, but I think it introduces more problems.
    Maybe you'll find it useful anyway.
    Good luck,
    Radish21

  • Java2D/Swing bug? scrolling with painting JTextArea components hangs app

    Please see
    http://forum.java.sun.com/thread.jspa?threadID=653181

    Please see
    http://forum.java.sun.com/thread.jspa?threadID=653181

  • JTextArea output problem

    When i create a text file and then open it back up with the below applcation,
    i get little squares appended to the end of the text.
    the application
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class FileIO extends JFrame implements ActionListener
         JButton btn_open;
         JButton btn_save;
         JButton btn_clear;
         JTextField file_path;
         JTextArea stuff;
          ///  Edited for size  ///
         //Methods
         private void Read_File()
              File input = new File(file_path.getText());
              FileReader reader;
              JDialog msg;
              char[] lines = new char[80];
              try {
                   reader = new FileReader(input);
                   while(reader.read(lines) != -1)
                        stuff.append(new String(lines));
                   reader.close();
              } catch (FileNotFoundException e) {
                   e.printStackTrace();
                   msg = new JOptionPane("FILE NOT FOUND ERROR", JOptionPane.ERROR_MESSAGE,
                             JOptionPane.DEFAULT_OPTION).createDialog("ERROR_MESSAGE");
                   msg.setVisible(true);     
              } catch (IOException e) {
                   e.printStackTrace();
                   msg = new JOptionPane("FILE IO ERROR", JOptionPane.ERROR_MESSAGE,
                             JOptionPane.DEFAULT_OPTION).createDialog("ERROR_MESSAGE");
                   msg.setVisible(true);
         private void Write_File()
              File output = new File(file_path.getText());
              FileWriter w;
              JDialog msg;
              try {
                   w = new FileWriter(output);
                   stuff.write(w);
                   w.close();
              } catch (IOException e) {
                   e.printStackTrace();
                   msg = new JOptionPane("FILE IO ERROR", JOptionPane.ERROR_MESSAGE,
                             JOptionPane.DEFAULT_OPTION).createDialog("ERROR_MESSAGE");
                   msg.setVisible(true);
         //ActionListener
         public void actionPerformed(ActionEvent evt)
              Object source = evt.getSource();
              if(source == btn_open)
                   Read_File();
              else if(source == btn_save)
                   Write_File();
              else if(source == btn_clear)
                   stuff.setText("");
            ///  Edited for size  ///
    }

    using sun-jdk 1.6.0.20 on Gentoo 32 bit
    source code:(copy/paste/run)
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class FileIO extends JFrame implements ActionListener
         JButton btn_open;
         JButton btn_save;
         JButton btn_clear;
         JTextField file_path;
         JTextArea stuff;
         public FileIO()
              super("FILE IO Example");
              setSize(300, 300);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              GridBagLayout bag_layout = new GridBagLayout();
              setLayout(bag_layout);
              GridBagConstraints c = new GridBagConstraints();
              //TextField file_path
              file_path = new JTextField(40);
              c.fill = GridBagConstraints.HORIZONTAL;
              c.gridx = 0;
              c.gridwidth = 4;
              c.gridy = 0;
              c.gridheight = 1;
              c.weightx = 1.0;
              add(file_path, c);
              //TextArea stuff and JScrollPane scroll
              stuff = new JTextArea(40, 40);
              JScrollPane scroll = new JScrollPane(stuff,
                        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              c.fill = GridBagConstraints.BOTH;
              c.gridy++;
              c.gridheight = 4;
              c.weighty = 1.0;
              add(scroll, c);
              //JButton btn_open
              btn_open = new JButton("Open File");
              btn_open.addActionListener(this);
              c.fill = GridBagConstraints.HORIZONTAL;
              c.gridy = 5;
              c.gridheight = 1;
              c.gridwidth = 1;
              c.weightx = 1.0;
              c.weighty = 0.0;
              add(btn_open, c);
              //JButton btn_save
              btn_save = new JButton("Save File");
              btn_save.addActionListener(this);
              c.gridx++;
              add(btn_save, c);
              //JButton btn_clear
              btn_clear = new JButton("Clear");
              btn_clear.addActionListener(this);
              c.gridx++;
              add(btn_clear, c);
              setVisible(true);
         //Methods
         private void Read_File()
              File input = new File(file_path.getText());
              FileReader reader;
              JDialog msg;
              char[] lines = new char[80];
              try {
                   reader = new FileReader(input);
                   while(reader.read(lines) != -1)
                        stuff.append(new String(lines));
                   reader.close();
              } catch (FileNotFoundException e) {
                   e.printStackTrace();
                   msg = new JOptionPane("FILE NOT FOUND ERROR", JOptionPane.ERROR_MESSAGE,
                             JOptionPane.DEFAULT_OPTION).createDialog("ERROR_MESSAGE");
                   msg.setVisible(true);     
              } catch (IOException e) {
                   e.printStackTrace();
                   msg = new JOptionPane("FILE IO ERROR", JOptionPane.ERROR_MESSAGE,
                             JOptionPane.DEFAULT_OPTION).createDialog("ERROR_MESSAGE");
                   msg.setVisible(true);
         private void Write_File()
              File output = new File(file_path.getText());
              FileWriter w;
              JDialog msg;
              try {
                   w = new FileWriter(output);
                   stuff.write(w);
                   w.close();
              } catch (IOException e) {
                   e.printStackTrace();
                   msg = new JOptionPane("FILE IO ERROR", JOptionPane.ERROR_MESSAGE,
                             JOptionPane.DEFAULT_OPTION).createDialog("ERROR_MESSAGE");
                   msg.setVisible(true);
         //ActionListener
         public void actionPerformed(ActionEvent evt)
              Object source = evt.getSource();
              if(source == btn_open)
                   Read_File();
              else if(source == btn_save)
                   Write_File();
              else if(source == btn_clear)
                   stuff.setText("");
         //Main
         public static void main(String[] args)
              new FileIO();
    }the appended nonprintable characters show up as little squares in the JTextArea, but they do not show up in any file editors on my computer.
    Edited by: grimx on Jul 3, 2010 7:24 PM
    Edited by: grimx on Jul 3, 2010 7:31 PM

  • JTextArea w/Scroll bar wont scroll AND code drops through if statements

    Hi, I'm still having trouble with the text area in the following code. When you run the code, you get the top arrow on the scroll bar, but the bottom is cut off. Also, a big problem is that no matter what choice is selected from the combo box, the code drops through to the last available value each time. Someone on the forums suggested using an array list for the values in the combo box, but I have not been able to figure out how to do that. A quick example would be apprciated.
    Thank you in advance for any help
    //Import required libraries
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.text.*;
    import java.math.*;
    import java.util.*;
    //Create the class
    public class Week3Assignment407B extends JFrame implements ActionListener
         //Panels used in container
         private JPanel jPanelRateAndTermSelection;         
         //Variables for Menu items
         private JMenuBar menuBar;    
         private JMenuItem exitMenuItem; 
         private JMenu fileMenu; 
         //Variables for user instruction and Entry       
         private JLabel jLabelPrincipal;   
         private JPanel jPanelEnterPrincipal;  
         private JLabel jLabelChooseRateAndTerm; 
         private JTextField jTextFieldMortgageAmt;
         //Variables for combo box and buttons
         private JComboBox TermAndRate;
         private JButton buttonCompute;
         private JButton buttonNew; 
         private JButton buttonClose;
         //Variables display output
         private JPanel jPanelPaymentOutput;
         private JLabel jLabelPaymentOutput;
         private JPanel jPanelErrorOutput;
         private JLabel jLabelErrorOutput;  
         private JPanel jPanelAmoritizationSchedule;
         private JTextArea jTextAreaAmoritization;
         // Constructor 
         public Week3Assignment407B() {            
              super("Mortgage Application");      
               initComponents();      
         // create a method that will initialize the main frame for the GUI
          private void initComponents()
              setSize(700,400);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      
              Container pane = getContentPane();
              GridLayout grid = new GridLayout(15, 1);
              pane.setLayout(grid);       
              //declare all of the panels that will go inside the main frame
              // Set up the menu Bar
              menuBar = new JMenuBar();
              fileMenu = new JMenu();
              fileMenu.setText("File");        
              exitMenuItem = new JMenuItem(); 
               exitMenuItem.setText("Exit");
              fileMenu.add(exitMenuItem); 
              menuBar.add(fileMenu);       
              pane.add(menuBar);
              //*******************TOP PANEL ENTER PRINCIPAL*****************************//
              // Create a label that will advise user to enter a principle amount
              jPanelEnterPrincipal = new JPanel(); 
              jLabelPrincipal = new JLabel("Amt to borrow in whole numbers");
              jTextFieldMortgageAmt = new JTextField(10);
              GridLayout Principal = new GridLayout(1,2);
              jPanelEnterPrincipal.setLayout(Principal); 
                jPanelEnterPrincipal.add(jLabelPrincipal);
              jPanelEnterPrincipal.add(jTextFieldMortgageAmt);
              pane.add(jPanelEnterPrincipal);
              //****************MIDDLE PANEL CHOOSE INTEREST RATE AND TERM*****************//
              // Create a label that will advise user to choose an Int rate and term combination
              // from the combo box
              jPanelRateAndTermSelection = new JPanel();
              jLabelChooseRateAndTerm = new JLabel("Choose the Rate and Term");
              buttonCompute = new JButton("Compute Mortgage");
              buttonNew = new JButton("New Mortgage");
              buttonClose = new JButton("Close");
              GridLayout RateAndTerm = new GridLayout(1,5);
              //FlowLayout RateAndTerm = new FlowLayout(FlowLayout.LEFT);
              jPanelRateAndTermSelection.setLayout(RateAndTerm);
              jPanelRateAndTermSelection.add(jLabelChooseRateAndTerm);
              TermAndRate = new JComboBox();
              jPanelRateAndTermSelection.add(TermAndRate);
              TermAndRate.addItem("7 years at 5.35%");
              TermAndRate.addItem("15 years at 5.5%");
              TermAndRate.addItem("30 years at 5.75%");
              jPanelRateAndTermSelection.add(buttonCompute);
              jPanelRateAndTermSelection.add(buttonNew);
              jPanelRateAndTermSelection.add(buttonClose);
              pane.add(jPanelRateAndTermSelection);
              //**************BOTTOM PANEL TEXT AREA FOR AMORITIZATION SCHEDULE***************//
              jPanelAmoritizationSchedule = new JPanel();
              jTextAreaAmoritization = new JTextArea(26,50);
              // add scroll pane to output text area
                   JScrollPane scrollBar = new JScrollPane(jTextAreaAmoritization, 
                   JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                     JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
              jPanelAmoritizationSchedule.add(scrollBar);
                pane.add(jPanelAmoritizationSchedule);
              //***************ADD THE ACTION LISTENERS TO THE GUI COMPONENTS*****************//
              // Add ActionListener to the buttons and menu item
              exitMenuItem.addActionListener(this);
              buttonCompute.addActionListener(this);         
              buttonNew.addActionListener(this);
              buttonClose.addActionListener(this);
              TermAndRate.addActionListener(this);
              jTextFieldMortgageAmt.addActionListener(this);
              //*************** Set up the Error output area*****************//
              jPanelErrorOutput = new JPanel();
              jLabelErrorOutput = new JLabel();
              FlowLayout error = new FlowLayout();
              jPanelErrorOutput.setLayout(error);
              pane.add(jLabelErrorOutput);
              setContentPane(pane);
              pack();
              setVisible(true);
         //Display error messages
         private void OutputError(String ErrorMsg){
              jLabelErrorOutput.setText(ErrorMsg);
              jPanelErrorOutput.setVisible(true);
         //create a method that will clear all fields when the New Mortgage button is chosen
         private void clearFields()
              jTextAreaAmoritization.setText("");
              jTextFieldMortgageAmt.setText("");
         //**************CREATE THE CLASS THAT ACTUALLY DOES SOMETHING WITH THE EVENT*****//
         //This is the section that receives the action source and directs what to do with it
         public void actionPerformed(ActionEvent e)
              Object source = e.getSource();
              String ErrorMsg;
              double principal;
              double IntRate;
              int Term;
              double monthlypymt;
              double TermInYears = 0 ;
              if(source == buttonClose)
                   System.exit(0);
              if (source == exitMenuItem) {      
                       System.exit(0);
              if (source == buttonNew)
                   clearFields();
              if (source == buttonCompute)
                   //Make sure the user entered valid numbers
                   try
                        principal = Double.parseDouble(jTextFieldMortgageAmt.getText());
                   catch(NumberFormatException nfe)
                        ErrorMsg = (" You Entered an invalid Mortgage amount"
                                  + " Please try again. Please do not use commas or decimals");
                        jTextAreaAmoritization.setText(ErrorMsg);
                   principal = Double.parseDouble(jTextFieldMortgageAmt.getText());
                    if (TermAndRate.getSelectedItem() == "7 years at 5.35%") ;
                        Term = 7;
                        IntRate = 5.35;
                    if (TermAndRate.getSelectedItem()  == "15 years at 5.5%") ;
                        Term = 15;
                        IntRate = 5.5;
                    if (TermAndRate.getSelectedItem() == "30 years at 5.75%") ;
                        Term = 30;
                        IntRate = 5.75;
                   //Variables have been checked for valid input, now calculate the monthly payment
                   NumberFormat formatter = new DecimalFormat ("$###,###.00");
                   double intdecimal = intdecimal = IntRate/(12 * 100);
                   int months = Term * 12;
                   double monthlypayment = principal *(intdecimal / (1- Math.pow((1 + intdecimal),-months)));
                   //Display the Amoritization schedule
                   jTextAreaAmoritization.setText(" Loan amount of " + formatter.format(principal)
                                                    + "\n"
                                                    + " Interest Rate is " +  IntRate + "%"
                                            + "\n"
                                            + " Term in Years "  + Term
                                            + " Monthly payment "+  formatter.format(monthlypayment)
                                            + "\n"
                                            + "  Amoritization is as follows:  "
                                            + "------------------------------------------------------------------------");
         public Insets getInsets()
              Insets around = new Insets(35,20,20,35);
              return around;
         //Main program     
         public static void main(String[]args) { 
              Week3Assignment407B frame = new Week3Assignment407B(); 
       }

    here's your initComponents with a couple of changes, the problem was the Gridlayout(15,1)
    also, the scrollpane needed a setPreferredSize()
      private void initComponents()
        setSize(700,400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Container pane = getContentPane();
        JPanel pane = new JPanel();
        //GridLayout grid = new GridLayout(15, 1);
        GridLayout grid = new GridLayout(2, 1);
        pane.setLayout(grid);
        menuBar = new JMenuBar();
        fileMenu = new JMenu();
        fileMenu.setText("File");
        exitMenuItem = new JMenuItem();
        exitMenuItem.setText("Exit");
        fileMenu.add(exitMenuItem);
        menuBar.add(fileMenu);
        //pane.add(menuBar);
        setJMenuBar(menuBar);
        jPanelEnterPrincipal = new JPanel();
        jLabelPrincipal = new JLabel("Amt to borrow in whole numbers");
        jTextFieldMortgageAmt = new JTextField(10);
        GridLayout Principal = new GridLayout(1,2);
        jPanelEnterPrincipal.setLayout(Principal);
          jPanelEnterPrincipal.add(jLabelPrincipal);
        jPanelEnterPrincipal.add(jTextFieldMortgageAmt);
        pane.add(jPanelEnterPrincipal);
        jPanelRateAndTermSelection = new JPanel();
        jLabelChooseRateAndTerm = new JLabel("Choose the Rate and Term");
        buttonCompute = new JButton("Compute Mortgage");
        buttonNew = new JButton("New Mortgage");
        buttonClose = new JButton("Close");
        GridLayout RateAndTerm = new GridLayout(1,5);
        jPanelRateAndTermSelection.setLayout(RateAndTerm);
        jPanelRateAndTermSelection.add(jLabelChooseRateAndTerm);
        TermAndRate = new JComboBox();
        jPanelRateAndTermSelection.add(TermAndRate);
        TermAndRate.addItem("7 years at 5.35%");
        TermAndRate.addItem("15 years at 5.5%");
        TermAndRate.addItem("30 years at 5.75%");
        jPanelRateAndTermSelection.add(buttonCompute);
        jPanelRateAndTermSelection.add(buttonNew);
        jPanelRateAndTermSelection.add(buttonClose);
        pane.add(jPanelRateAndTermSelection);
        jPanelAmoritizationSchedule = new JPanel();
        jTextAreaAmoritization = new JTextArea(26,50);
        JScrollPane scrollBar = new JScrollPane(jTextAreaAmoritization,
          JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollBar.setPreferredSize(new Dimension(500,100));//<------------------------
        jPanelAmoritizationSchedule.add(scrollBar);
        getContentPane().add(pane,BorderLayout.NORTH);
        getContentPane().add(jPanelAmoritizationSchedule,BorderLayout.CENTER);
        exitMenuItem.addActionListener(this);
        buttonCompute.addActionListener(this);
        buttonNew.addActionListener(this);
        buttonClose.addActionListener(this);
        TermAndRate.addActionListener(this);
        jTextFieldMortgageAmt.addActionListener(this);
        jPanelErrorOutput = new JPanel();
        jLabelErrorOutput = new JLabel();
        FlowLayout error = new FlowLayout();
        jPanelErrorOutput.setLayout(error);
        //pane.add(jLabelErrorOutput);not worrying about this one
        //setContentPane(pane);
        pack();
        setVisible(true);
      }instead of
    if (TermAndRate.getSelectedItem() == "7 years at 5.35%") ;
    Term = 7;
    IntRate = 5.35;
    you would be better off setting up arrays
    int[] term = {7,15,30};
    double[] rate = {5.35,5.50,5.75};
    then using getSelectedIndex()
    int loan = TermAndRate.getSelectedIndex()
    Term = term[loan];
    IntRate = rate[loan];

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

Maybe you are looking for