JViewport + JTextArea

I am writing some code that will display a JTextArea in a JViewport just above a progress bar. The idea is for the last several lines of the progress to be visible on the screen. However, once I fill up the current JTextArea, I have not been able to scroll down as I add new information. I would like this to happen programmatically, so that the latest message is always displayed. I have tried using:
textarea.scrollRectToVisible( rectangle );
and this doesn't seem to work. When I use:
viewport.viewport.setViewPosition( point );
I cause the application to crash even when I am passing a point where there should be just enough component left to fill the viewport from that point. Would someone point me in the right direction on this issue?
-Benjamin

I think I may have discovered something else that is related to why I can't get this to work correctly. The screen that this update is taking place on is a JWindow with none of the standard borders, titlebars, or window controls of a standard JFrame. (It is a splash screen) When I try the following code:
Point p = new Point(viewport.getViewPosition());
p.y = textArea.getHeight();
viewport.setViewPosition(p);
I get this exception:
java.lang.ClassCastException: java.awt.Window at
javax.swing.JViewport.setViewPosition(JViewPort.java:1031)
Is there some incompatibility between using this call in a JWindow?
-Benjamin

Similar Messages

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

  • Size of ScrollPane (JViewport)

    I have a JScrollPane that contains a JTextArea.
    When I write more text to the text area the scroll bar appears and that's fine.
    But if I pack() the window the text area gets bigger so that all the text is visible and that's my problem.
    What can I do?
    I tryed setting the size of the JViewport but it didn't work...

    Don't pack() then, it will attempt to resize the components "optimally" which is obiviously not what you're wanting.

  • Anchoring view to bottom of JTextArea within JScrollPane

    I've got a JTextArea that will be updated asynchronously with text of unknown length. I want the view to move to the bottom every time text is added. I've read through the API for JScrollPane, JScrollBar, JViewports etc. but haven't been able to figure out how to do it. I assume that I have to update the view each time text is added. Here is a summary of the code I've got:
    private JScrollPane historyScroll;
    private JTextArea historyBox;
    public void init(){
        // code removed
        historyBox = new JTextArea();
        historyBox.setLineWrap(true);
        historyBox.setWrapStyleWord(true);
        historyBox.setEditable(false);
        historyScroll = new JScrollPane(historyBox);
        historyScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        // code removed
    // add a message to the bottom of the history box
    public synchronized void putMessage(String message){
        historyBox.append(message);
    }

    First, make sure the appending of the text is happening on the swing thread or bad things could result. If it isn't, then use SwingUtilities.invokeLater() when you call the putMessage() method.public void putMessage( String message ) {
         historyBox.append( message );
         // Scroll to the new message
         int height = historyBox.getHeight();
         historyBox.scrollRectToVisible( new Rectangle(0, height, 1, 1) );
    }I'm doing this from memory, so hopefully it is correct. :-)

  • JTextArea with freeze pane functionality

    Greetings. I am trying to implement a plain text viewer that has some sort of "freeze pane" functionality (like that found in MS Excel)
    I took the approach of using 4 JTextArea and put them into a JScrollPane, its row header, column header and upper-left corner. All these text areas share the same document.
    Everything works as expected. When I scroll the lower-right pane, the row and column headers scroll correspondingly. The problem I have is that the document in the lower-right pane now shows duplicate portion of the document that is already showing in the row and column headers.
    Knowing that this should merely be a matter of shifting the Viewport on the document, I went through the documentation and java source, and just couldn't find a way to translate the view. SetViewPosition() works to a certain extent, but the scrollbars allow users to scroll back to the origin and reveal the duplicate data, which is undesirable.
    Your help with find out a way to relocate the view to the desired location is much appreciated.
    khsu

    some sample code attached (with a quick hack in attempt to making it work, at least presentation-wise)
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.plaf.*;
    import javax.swing.plaf.basic.*;
    import javax.swing.text.*;
    public class SplitViewFrame extends JFrame {
        int splitX = 100;
        int splitY = 100;
        public static void main(String[] args) {
            // Create application frame.
            SplitViewFrame frame = new SplitViewFrame();
            // Show frame
            frame.setVisible(true);
         * The constructor.
         public SplitViewFrame() {
            JMenuBar menuBar = new JMenuBar();
            JMenu menuFile = new JMenu();
            JMenuItem menuFileExit = new JMenuItem();
            menuFile.setLabel("File");
            menuFileExit.setLabel("Exit");
            // Add action listener.for the menu button
            menuFileExit.addActionListener
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        SplitViewFrame.this.windowClosed();
            menuFile.add(menuFileExit);
            menuBar.add(menuFile);
            setTitle("SplitView");
            setJMenuBar(menuBar);
            setSize(new Dimension(640, 480));
            // Add window listener.
            this.addWindowListener
                new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        SplitViewFrame.this.windowClosed();
            makeFreezePane();
        void makeFreezePane() {
            Container cp = getContentPane();
            Font font = new Font("monospaced", Font.PLAIN, 14);
            OffsetTextArea ta = new OffsetTextArea();
            ta.setSplit(splitX, splitY);
            ta.setOpaque(false);
            ta.setFont(font);
            // read doc
            readDocIntoTextArea(ta, "..\\afscheck.txt");
            JScrollPane jsp = new JScrollPane(ta);
            jsp.getViewport().setBackground(Color.white);
            Document doc = ta.getDocument();
            // dump doc
            //dumpDocument(doc);
            JViewport ulVP = makeViewport(doc, font, 0, 0, splitX, splitY);
            JViewport urVP = makeViewport(doc, font, splitX, 0, 20, splitY);
            JViewport llVP = makeViewport(doc, font, 0, splitY, splitX, 20);
            jsp.setRowHeader(llVP);
            jsp.setColumnHeader(urVP);
            jsp.setCorner(JScrollPane.UPPER_LEFT_CORNER, ulVP);
            jsp.setCorner(JScrollPane.UPPER_RIGHT_CORNER, new Corner());
            jsp.setCorner(JScrollPane.LOWER_LEFT_CORNER, new Corner());
            jsp.setCorner(JScrollPane.LOWER_RIGHT_CORNER, new Corner());
            cp.setLayout(new BorderLayout());
            cp.add(jsp, BorderLayout.CENTER);
        void readDocIntoTextArea(JTextArea ta, String filename) {
            try {
                File f = new File(filename);
                FileInputStream fis = new FileInputStream(f);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int br = 0;
                byte[] buf = new byte[1024000];
                while ((br = fis.read(buf, 0, buf.length)) != -1) {
                    baos.write(buf, 0, br);
                fis.close();
                ta.setText(baos.toString());
            } catch (Exception e) {
                e.printStackTrace();
                ta.setText("Failed to load text.");
        protected void windowClosed() {
            System.exit(0);
        JViewport makeViewport(Document doc, Font f, int splitX, int splitY, int width, int height) {
            JViewport vp = new JViewport();
            OffsetTextArea ta = new OffsetTextArea();
            ta.setSplit(splitX, splitY);
            ta.setDocument(doc);
            ta.setFont(f);
            ta.setBackground(Color.gray);
            vp.setView(ta);
            vp.setBackground(Color.gray);
            vp.setPreferredSize(new Dimension(width, height));
            return vp;
        static void dumpDocument(Document doc) {
            Element[] elms = doc.getRootElements();
            for (int i = 0; i < elms.length; i++) {
                dumpElement(elms, 0);
    static void dumpElement(Element elm, int level) {
    for (int i = 0; i < level; i++) System.out.print(" ");
    System.out.print(elm.getName());
    if ( elm.isLeaf() && elm.getName().equals("content")) {
    try {
    int s = elm.getStartOffset();
    int e = elm.getEndOffset();
    System.out.println(elm.getDocument().getText(
    s, e-s));
    } catch (Exception e) {
    System.out.println(e.getLocalizedMessage());
    return;
    System.out.println();
    for (int i = 0; i < elm.getElementCount(); i++) {
    dumpElement(elm.getElement(i), level+1);
    class OffsetTextArea extends JTextArea {
    int splitX = 0;
    int splitY = 0;
    public void setSplit(int x, int y) {
    splitX = x;
    splitY = y;
    public void paint(Graphics g) {
    g.translate(-splitX, -splitY);
    super.paint(g);
    g.translate( splitX, splitY);
    /* Corner.java is used by ScrollDemo.java. */
    class Corner extends JComponent {
    protected void paintComponent(Graphics g) {
    // Fill me with dirty brown/orange.
    g.setColor(new Color(230, 163, 4));
    g.fillRect(0, 0, getWidth(), getHeight());

  • Problem in scrolling a JTextArea

    hi,
    I am using a JTextArea to display files. I could scroll smoothly without interruptions when I tested with a 1 kb file. But when I loaded a 300 kb file, the scrolling beacame halted and slow. It was not continuous. Can this be fixed?
    Also I am thinking of displaying files of larger sizes( 1Mb- 5 Mb). In such cases, I thought it would be better to display only parts of the document as i scroll. Could someone please help me with this?
    Thanks,
    ramya

    Hello,
    I hope you would be able to recall my problem - smooth scrolling of loads of text.(Please see my problem -right at the top, as the first post)
    I worked out a way to display only the required text as i scroll. I could not go in for a scrollpane because I would need to deal with MBs of textual data. :(
    Now, I am trying to perform a word search on the text displayed. I do not know how to do this.
    Please help with your suggestions and pointers.
    I have posted the code below.
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.text.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import javax.swing.text.*;
    public class paint_frame extends JFrame implements AdjustmentListener
    JTextArea text; PlainDocument doc = new PlainDocument();Font f;FontMetrics fm; int ivisible,ivalue;JScrollBar hscroll;
    JViewport view; int width;  columnpanel cp; JScrollBar vscroll;
    paintpanel pp; int ivisible_v; int ivalue_v; VPanel vp; JPanel mp;
    JPanel mmp=new JPanel(new BorderLayout());
        public static void main(String[] args)
            paint_frame pf = new paint_frame();
            pf.setSize(new Dimension(900,900));
            pf.pack();
            pf.setVisible(true);
            pf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public paint_frame()
           try
           doc.insertString(doc.getLength(),"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"67890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234*",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"89012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456*",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"02345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
            doc.insertString(doc.getLength(),"\n",null);
            doc.insertString(doc.getLength(),"67890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234*",null);
            doc.insertString(doc.getLength(),"\n",null);
            doc.insertString(doc.getLength(),"89012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456*",null);
            doc.insertString(doc.getLength(),"\n",null);
            doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
            doc.insertString(doc.getLength(),"\n",null);
            doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
            doc.insertString(doc.getLength(),"\n",null);
            doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
            doc.insertString(doc.getLength(),"\n",null);
            doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
            doc.insertString(doc.getLength(),"\n",null);
            doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
            doc.insertString(doc.getLength(),"\n",null);
            doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
            doc.insertString(doc.getLength(),"\n",null);
            doc.insertString(doc.getLength(),"00345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
           }catch(Exception e){}
            hscroll = new JScrollBar(JScrollBar.HORIZONTAL,0,0,0,0); // set the max value to be the length of the longest seq. in the alignment.
            vscroll = new JScrollBar(JScrollBar.VERTICAL,0,0,0,0);
            pp = new paintpanel();
            view = new JViewport();
            view.setPreferredSize(new Dimension(600,600));
            view.setMaximumSize(new Dimension(600,600));
             vp = new VPanel();
             text = new JTextArea(); view.setView(text);
                      f = new Font("Monospaced",Font.PLAIN,20);
            text.setFont(f);fm = text.getFontMetrics(f); //text.setEditable(false);
           mp = new JPanel(new BorderLayout());
           cp = new columnpanel();
           hscroll.addAdjustmentListener(this);
           vscroll.addAdjustmentListener(this);
           pp.add(view,BorderLayout.CENTER);
           pp.add(hscroll,BorderLayout.SOUTH);
           pp.add(cp, BorderLayout.NORTH);
           view.setView(text);
           JMenuBar bar = new JMenuBar();
           JMenu format = new JMenu("format");
           JMenuItem font = new JMenuItem("font");
           JMenu search = new JMenu("search");
           JMenuItem find = new JMenuItem("find");
           font.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                 f = new Font("Monospaced",Font.PLAIN,18);
                 text.setFont(f);
                 fm=text.getFontMetrics(f);
                 //paintframe3.this.revalidate();
                 paint_frame.this.repaint();      // causes the panel to be repainted
           format.add(font);
           bar.add(format);
           mp.add(pp,BorderLayout.CENTER);
           mp.add(vp,BorderLayout.EAST);
          mmp.add(mp,BorderLayout.CENTER);
          //mmp.add(headerview,BorderLayout.WEST);
           getContentPane().add(mmp,BorderLayout.CENTER);
           setJMenuBar(bar);
           System.out.println("\n jpanel added");
        public void adjustmentValueChanged(AdjustmentEvent ae)
        try
           paint_frame.this.repaint();
        }catch(Exception e){}
    class columnpanel extends JPanel
        int alignment_width;
        int window_width;
        int hvalue;int j;String s=""; int v1,v;
      columnpanel()
         setOpaque(true);
         setPreferredSize(new Dimension(view.getSize().width,50));
      public void doLayout()
      public void paintComponent(Graphics g)
         window_width = width;
         g.setColor(Color.white);
         System.out.println(" COLUMN PANEL COLUMN PANEL/*//*" + getSize());System.out.println(" preferred column panel" + getPreferredSize());
         g.fillRect(0,0,getSize().width,getSize().height);
         g.setColor(Color.black);
         g.setFont(f);
          j = fm.charWidth('M');
          v = hscroll.getValue()/fm.charWidth('M');
    for(int i=1;i<=15;i=i+1)
              if(v==0)
                     s=new Integer((i)*10).toString();
                //g.drawString("|", i*j*10-(j+j*v),0+10);
               g.drawString(s, i*j*10-(j+j*v),40);
           else
           if(v!=0)
                s=new Integer((i)*10).toString();
                //g.drawString("|", i*j*10-(j+j*v)+view.getSize().width%j,0+10);
                           g.drawString(s, i*j*10-(j+j*v)+view.getSize().width%j,40);
    }// end of column panel class
    class paintpanel extends JPanel
        paintpanel()
            setSize(new Dimension(800,800));
            setLayout(new BorderLayout());
        public void paintComponent(Graphics g)
            try
              int testwidth = view.getSize().width/fm.charWidth('M');
              int testheight = view.getSize().height/fm.getHeight();
              hscroll.setMaximum(150*fm.charWidth('M'));
              vscroll.setMaximum(30*fm.getHeight());
              hscroll.setVisibleAmount(testwidth*fm.charWidth('M'));
              vscroll.setVisibleAmount(testheight*fm.getHeight());
              hscroll.setUnitIncrement(fm.charWidth('M'));
              vscroll.setUnitIncrement(fm.getHeight());
             hscroll.setBlockIncrement(testwidth*fm.charWidth('M'));
              //hvisibleamount = hscroll.getVisibleAmount();
                text.setText("");
                         text.setText(doc.getText(0,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
                         text.append("\n");
                    text.append(doc.getText((151),testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
                text.append(doc.getText(302,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
               text.append(doc.getText(453,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(604,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(755,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(906,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(1057,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(1208,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(1359,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(1510,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(1661,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(1812,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(1963,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(2114,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(2265,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(2416,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(2567,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(2718,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(2869,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              /*text.append("\n");
              text.append(doc.getText(3020,ivalue+ivisible+hscroll.getValue()));
                          text.append("\n");
                          text.append(doc.getText(3171,ivalue+ivisible+hscroll.getValue()));
                          text.append("\n");
                          text.append(doc.getText(3322,ivalue+ivisible+hscroll.getValue()));
                          text.append("\n");
                          text.append(doc.getText(3473,ivalue+ivisible+hscroll.getValue()));
                          text.append("\n");
                          text.append(doc.getText(3624,ivalue+ivisible+hscroll.getValue()));
                          text.append("\n");
                          text.append(doc.getText(3775,ivalue+ivisible+hscroll.getValue()));
                          text.append("\n");
                          text.append(doc.getText(3926,ivalue+ivisible+hscroll.getValue()));
                          text.append("\n");
                          text.append(doc.getText(4077,ivalue+ivisible+hscroll.getValue()));
                          text.append("\n");
                          text.append(doc.getText(4228,ivalue+ivisible+hscroll.getValue()));
                          text.append("\n");
                          text.append(doc.getText(1379,ivalue+ivisible+hscroll.getValue()));*/
            }catch(Exception e){}
    }// end of paint panel class
    class VPanel extends JPanel
         VPanel()
              //setLayout(null);
              setSize(new Dimension(17,pp.getSize().height));
              setBackground(Color.white);
              add(vscroll);
    public void doLayout()
         vscroll.setBounds(0,view.getBounds().y,getSize().width,view.getSize().height);
         //vscroll.setPreferredSize(new Dimension(getSize().width,view.getSize().height));
    public void paintComponent(Graphics g)
         super.paintComponent(g);
              System.out.println("\n vertical panel size" + getSize());
    } // end of VPanel class
    }// end of piant_frame classThank you very much for the time,
    ramya

  • Exception While Limiting the Size of JTextArea

    Im using a JTextArea for logging. For that i ve limitted the size/length of JTextArea by overriding the insertString method to avoid OutOfMemoryError.
    Here is the code:-
    public void insertString(int aOffset, String aStr, AttributeSet aAttr)
    throws BadLocationException
    if (availableSpace() < aStr.length())
    remove(0, aStr.length() > getLength() ? getLength() : aStr.length());
    theDocument.insertString(getLength(), aStr, aAttr);
    Everything seems to be working except that sometimes i get the following exception:- (Anybody any idea about this. its urgent i m stuck)
    java.lang.ArrayIndexOutOfBoundsException
    at javax.swing.text.BoxView.getOffset(BoxView.java:1022)
    at javax.swing.text.BoxView.paint(BoxView.java:402)
    at javax.swing.text.WrappedPlainView.paint(WrappedPlainView.java:349)
    at javax.swing.plaf.basic.BasicTextUI$RootView.paint(BasicTextUI.java:1248)
    at javax.swing.plaf.basic.BasicTextUI.paintSafely(BasicTextUI.java:565)
    at javax.swing.plaf.basic.BasicTextUI.paint(BasicTextUI.java:699)
    at javax.swing.plaf.basic.BasicTextUI.update(BasicTextUI.java:678)
    at javax.swing.JComponent.paintComponent(JComponent.java:537)
    at javax.swing.JComponent.paint(JComponent.java:804)
    at javax.swing.JComponent.paintChildren(JComponent.java:643)
    at javax.swing.JComponent.paint(JComponent.java:813)
    at javax.swing.JViewport.paint(JViewport.java:707)
    at javax.swing.JComponent.paintChildren(JComponent.java:643)
    at javax.swing.JComponent.paint(JComponent.java:813)
    at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4735)
    at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4688)
    at javax.swing.JComponent._paintImmediately(JComponent.java:4632)
    at javax.swing.JComponent.paintImmediately(JComponent.java:4464)
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:410)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:117)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:443)02:14:56:941 Thread-9 .DefaultBufferedDocument.--------- Full Removing---------
    02:14:56:943 Thread-9 .DefaultBufferedDocument.theSize = 4096
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:191)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:144)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)

    I am getting EXACTLY the same exception thrown from EXACTLY the same place. I am using a JEditorPane to display HTML text. Problem occurs randomly.
    Everything works fine on Java 1.3.x. Fails on 1.4.x.
    Here is the stack trace:
    java.lang.ArrayIndexOutOfBoundsException
    at javax.swing.text.BoxView.getOffset(BoxView.java:1022)
    at javax.swing.text.BoxView.childAllocation(BoxView.java:669)
    at javax.swing.text.CompositeView.getChildAllocation(CompositeView.java:215)
    at javax.swing.text.BoxView.getChildAllocation(BoxView.java:427)
    at javax.swing.plaf.basic.BasicTextUI$UpdateHandler.calculateViewPosition(BasicTextUI.java:1780)
    at javax.swing.plaf.basic.BasicTextUI$UpdateHandler.layoutContainer(BasicTextUI.java:1756)
    at java.awt.Container.layout(Container.java:835)
    at java.awt.Container.doLayout(Container.java:825)
    at java.awt.Container.validateTree(Container.java:903)
    at java.awt.Container.validateTree(Container.java:910)
    at java.awt.Container.validateTree(Container.java:910)
    at java.awt.Container.validateTree(Container.java:910)
    at java.awt.Container.validateTree(Container.java:910)
    at java.awt.Container.validateTree(Container.java:910)
    at java.awt.Container.validateTree(Container.java:910)
    at java.awt.Container.validateTree(Container.java:910)
    at java.awt.Container.validateTree(Container.java:910)
    at java.awt.Container.validateTree(Container.java:910)
    at java.awt.Container.validateTree(Container.java:910)
    at java.awt.Container.validateTree(Container.java:910)
    at java.awt.Container.validate(Container.java:878)
    at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:347)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:116)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:443)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:190)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:144)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)
    Darren.

  • 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 Capture New Line in JTextArea?

    I apologize if this is easy, but I've been searching here and the web for a few hours with no results.
    I have a JTextArea on a form. I want to save the text to a database, including any newline characters - /n or /r/n - that were entered.
    If I just do a .getText for the component, I can do a System.println and see the carriage return. However, when I store and then retrieve from the database, I get the lines concatenated.
    How to I search for the newline character and then - for lack of a better idea - replace it with a \n or something similar?
    TIA!

    PerfectReign wrote:
    Okay, nevermind. I got it.
    I don't "see" the \n but it is there.
    I added a replaceAll function to the string to replace \n with
    and that saves to the database correctly.
    String tmpNotes = txtNotes.getText().replaceAll("\n", "<br />");Oh, you're viewing the text as HTML? That would have been good to know. ;)
    I'll have to find a Wintendo machine to try this as well.Be careful not to get a machine that that says "Nii!"

  • 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 put a Jpanel always over a JtextArea ?

    I want to have a little Jpanel above a JTextArea.
    At the initialize section, I add first the Jpanel and after the JtextArea (both in a 'parent' Jpanel with null layout)
    When I run the program I see the Jpanel over the JtextArea, but when I write on it and it reaches the area when the Jpanel is placed, the JtexArea brings to front and the Jpanel is no longer visible.
    So, how can I have my Jpanel on top always ?
    And another question , is there a hierarchy that control that I Jpanel is always over a Jbutton (even if the initial z-order of the button is higher than the Jpanel's)
    Thanks
    ( I do not send any code because it is so simple as putting this two components into a Jpanel)

    tonnot wrote:
    And another question , is there a hierarchy that control that I Jpanel is always over a Jbutton (even if the initial z-order of the button is higher than the Jpanel's)JLayeredPane
    ( I do not send any code because it is so simple as putting this two components into a Jpanel)Try it with a JLayeredPane and if you still have problems, post a [SSCCE (Short, Self Contained, Compilable and Executable, Example Program)|http://mindprod.com/jgloss/sscce.html].
    db

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

  • Need help with JTextArea and Scrolling

    import java.awt.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import javax.swing.*;
    public class MORT_RETRY extends JFrame implements ActionListener
    private JPanel keypad;
    private JPanel buttons;
    private JTextField lcdLoanAmt;
    private JTextField lcdInterestRate;
    private JTextField lcdTerm;
    private JTextField lcdMonthlyPmt;
    private JTextArea displayArea;
    private JButton CalculateBtn;
    private JButton ClrBtn;
    private JButton CloseBtn;
    private JButton Amortize;
    private JScrollPane scroll;
    private DecimalFormat calcPattern = new DecimalFormat("$###,###.00");
    private String[] rateTerm = {"", "7years @ 5.35%", "15years @ 5.5%", "30years @ 5.75%"};
    private JComboBox rateTermList;
    double interest[] = {5.35, 5.5, 5.75};
    int term[] = {7, 15, 30};
    double balance, interestAmt, monthlyInterest, monthlyPayment, monPmtInt, monPmtPrin;
    int termInMonths, month, termLoop, monthLoop;
    public MORT_RETRY()
    Container pane = getContentPane();
    lcdLoanAmt = new JTextField();
    lcdMonthlyPmt = new JTextField();
    displayArea = new JTextArea();//DEFINE COMBOBOX AND SCROLL
    rateTermList = new JComboBox(rateTerm);
    scroll = new JScrollPane(displayArea);
    scroll.setSize(600,170);
    scroll.setLocation(150,270);//DEFINE BUTTONS
    CalculateBtn = new JButton("Calculate");
    ClrBtn = new JButton("Clear Fields");
    CloseBtn = new JButton("Close");
    Amortize = new JButton("Amortize");//DEFINE PANEL(S)
    keypad = new JPanel();
    buttons = new JPanel();//DEFINE KEYPAD PANEL LAYOUT
    keypad.setLayout(new GridLayout( 4, 2, 5, 5));//SET CONTROLS ON KEYPAD PANEL
    keypad.add(new JLabel("Loan Amount$ : "));
    keypad.add(lcdLoanAmt);
    keypad.add(new JLabel("Term of loan and Interest Rate: "));
    keypad.add(rateTermList);
    keypad.add(new JLabel("Monthly Payment : "));
    keypad.add(lcdMonthlyPmt);
    lcdMonthlyPmt.setEditable(false);
    keypad.add(new JLabel("Amortize Table:"));
    keypad.add(displayArea);
    displayArea.setEditable(false);//DEFINE BUTTONS PANEL LAYOUT
    buttons.setLayout(new GridLayout( 1, 3, 5, 5));//SET CONTROLS ON BUTTONS PANEL
    buttons.add(CalculateBtn);
    buttons.add(Amortize);
    buttons.add(ClrBtn);
    buttons.add(CloseBtn);//ADD ACTION LISTENER
    CalculateBtn.addActionListener(this);
    ClrBtn.addActionListener(this);
    CloseBtn.addActionListener(this);
    Amortize.addActionListener(this);
    rateTermList.addActionListener(this);//ADD PANELS
    pane.add(keypad, BorderLayout.NORTH);
    pane.add(buttons, BorderLayout.SOUTH);
    pane.add(scroll, BorderLayout.CENTER);
    addWindowListener( new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    public void actionPerformed(ActionEvent e)
    String arg = lcdLoanAmt.getText();
    int combined = Integer.parseInt(arg);
    if (e.getSource() == CalculateBtn)
    try
    JOptionPane.showMessageDialog(null, "Got try here", "Error", JOptionPane.ERROR_MESSAGE);
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Got here", "Error", JOptionPane.ERROR_MESSAGE);
    if ((e.getSource() == CalculateBtn) && (arg != null))
    try{
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 1))
    monthlyInterest = interest[0] / (12 * 100);
    termInMonths = term[0] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 2))
    monthlyInterest = interest[1] / (12 * 100);
    termInMonths = term[1] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 3))
    monthlyInterest = interest[2] / (12 * 100);
    termInMonths = term[2] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Invalid Entry!\nPlease Try Again", "Error", JOptionPane.ERROR_MESSAGE);
    }                    //IF STATEMENTS FOR AMORTIZATION
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 1))
    loopy(7, 5.35);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 2))
    loopy(15, 5.5);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 3))
    loopy(30, 5.75);
    if (e.getSource() == ClrBtn)
    rateTermList.setSelectedIndex(0);
    lcdLoanAmt.setText(null);
    lcdMonthlyPmt.setText(null);
    displayArea.setText(null);
    if (e.getSource() == CloseBtn)
    System.exit(0);
    private void loopy(int lTerm,double lInterest)
    double total, monthly, monthlyrate, monthint, monthprin, balance, lastint, paid;
    int amount, months, termloop, monthloop;
    String lcd2 = lcdLoanAmt.getText();
    amount = Integer.parseInt(lcd2);
    termloop = 1;
    paid = 0.00;
    monthlyrate = lInterest / (12 * 100);
    months = lTerm * 12;
    monthly = amount *(monthlyrate/(1-Math.pow(1+monthlyrate,-months)));
    total = months * monthly;
    balance = amount;
    while (termloop <= lTerm)
    displayArea.setCaretPosition(0);
    displayArea.append("\n");
    displayArea.append("Year " + termloop + " of " + lTerm + ": payments\n");
    displayArea.append("\n");
    displayArea.append("Month\tMonthly\tPrinciple\tInterest\tBalance\n");
    monthloop = 1;
    while (monthloop <= 12)
    monthint = balance * monthlyrate;
    monthprin = monthly - monthint;
    balance -= monthprin;
    paid += monthly;
    displayArea.setCaretPosition(0);
    displayArea.append(monthloop + "\t" + calcPattern.format(monthly) + "\t" + calcPattern.format(monthprin) + "\t");
    displayArea.append(calcPattern.format(monthint) + "\t" + calcPattern.format(balance) + "\n");
    monthloop ++;
    termloop ++;
    public static void main(String args[])
    MORT_RETRY f = new MORT_RETRY();
    f.setTitle("MORTGAGE PAYMENT CALCULATOR");
    f.setBounds(600, 600, 500, 500);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    }need help with displaying the textarea correctly and the scroll bar please.
    Message was edited by:
    new2this2020

    What's the problem you're having ???
    PS.

  • How to hide the Form Feed char in JTextArea

    We have reports (written in C) that are being displayed in a JTextArea.
    In our old app, the Form Feed character (ASCII 12) was invisible naturally without having to code around it. In a JTextArea, it appears as a "[]" character. Does anyone know how to make this character invisible to the JTextArea? Removing it is not an option, as it is needed for it's print routine.
    I've been searching these forums and the web all morning with no luck.

    Not sure how the Form Feed character worksIt lets the printer know that a new page is to be started at that point.
    Does it always appear with the New Line character?Usually but not always.
    Thanks for the reply. It's more involved than just printing standard lines of text, so perhaps I should have been more clear.
    The C report already has pagination built in from when it was run from our legacy GUI. In other words, each report knows how many chars wide and how many lines down each page will be. It is different for each report, but they all hover around 150 chars wide and 60 lines down per page, since they are all presented to the user (and printed) in landscape.
    In the C code: at the end of each report line a "\n" is appended. At the end of each page, an ASCII 12 character is appended. A header is at the top of each page (different for each report, but usually 2 or 3 lines) that shows the page # and other info.
    So, as you are viewing the report, you would see page 1 header, some report content, page 2 header, some more report content, page 3 header, etc. as you scroll down.
    So now if you view it in Java: if the user wishes to print, the report is sent to our ReportPrinter class, who tokenizes the report based on "\f" and makes a ReportPage object (implements Printable) for each token. Each ReportPage is then appened to a java.awt.print.Book object, who in turn is sent to the PrinterJob.
    Given that the report already has his pages figured out and has a form feed char at the end of each page, the report comes in to the JTextArea with [] chars preceding each page header (approximately every 60th line, depending on the report).
    I tried using a JTextPane, but no luck. It was also much slower reading in the report. I just want the textpane to not display the non-printable characters ("\f" in this case).

  • Display data from entity into a Jtextareaþ

    Hello everyone,
    How do I display data I am retrieving from the entity into a Jtextarea?
    Here is how I am doing it:
    in the main class of the application client, I set up a method
    which stores the remote interface so I can call the method
    anyway of my application.
    public class Main extends javax.swing.JFrame {
         @EJB
                private static  BRemote bRemote;
           //accessor method
           static BRemote getBRemote() {
                  return bRemote;
          // I can out the method to request data
          public void findB(String bal){
            Main.getBRemote().findbyDname(bal);
            searesttxta.setText(getBRemote().toString());
    } The searesttxta is the JTextArea.
    the data I get is
    folder._BRemote_Wrapper@3ce08241
    So, how do I get to display the entity in the textarea?
    thanks
    eve

    Hi,
    Thank you for your reply.
    Yes I do have sets and get methods but I also understand I can
    use the to string too. But to attach it to the JTextArea.
    eve

Maybe you are looking for

  • How to display the time 00:00:00 as blank?

    Dear Friends, I have created a new field GDF_9000_CREATED_AT in the normal screen (dynpro), the format is TIMS, however, when there is no value for it, is always display like "00:00:00" on the screen. So how to display the time 00:00:00 as blank in t

  • Westinghouse LCD Monitors?

    Hi: I have a 1st gen Dual 4gigs ram. all PCI slot full. Has anybody out there ever used one or know of someone who is using one on their MAC? I now have 3 19in. ViewSonic CRT monitors hanging off of the ATE Radeon 9600 Pro (64 MB Vram) in the AGP slo

  • What cameras work with the live wireless

    I have a Creative internet camera Live wirless and want to know what model cameras will work with them as it can support up to four cameras and since Creative has no direct email to contact them directly I'm asking it here

  • InDesign CC crash when clicking and dragging

    I've had a really huge issue the last two days with InDesign CC. Every file I open, or, new file I create, it crashes the program immediately when I attempt to click and drag -anything- I am able to use the type tool, access all the drop down menus a

  • 9i OCA to 11g OCA

    Hi, Is it possible to upgrade from 9i OCA to 11g OCA. Obtained the 9i OCA by completing 1Z0_007 & 1Z0_047 in early 2008. so it is basically a prometic ID, I just requested to merge it with an Oracle Testing ID. I see that 11g OCA needs the same set o