0

I have this class as an example of my problem. The scrollpane doesn't scroll, and I can't see a good reason why:

    import java.awt.Dimension;

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;


public class DoesNotScroll{ 

    public static void main(String[] args){
        String str = "this\n\nshould\n\n\n\nscroll\n\n\nthis is the bottom";
        message("test", str, JOptionPane.INFORMATION_MESSAGE);
    }

    public final static void message(String title, String message, int messageType){
        JTextArea messageArea = new JTextArea();
        messageArea.setMinimumSize(new Dimension(300, 100));
        messageArea.setMaximumSize(new Dimension(300, 100));
        messageArea.setPreferredSize(new Dimension(300, 100));
        messageArea.setEditable(false);
        JScrollPane scroller = new JScrollPane(messageArea);
        scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        messageArea.setText(message);
        messageArea.revalidate();
        messageArea.repaint();
        JOptionPane.showMessageDialog(null, scroller, title, messageType);
    }
}

Any help is appreciated,

-C

Chris Drappier
  • 5,280
  • 10
  • 40
  • 64

2 Answers2

4

The problem with my setup here was that I was calling messageArea.setPreferredSize() instead of scroller.setPreferredSize()

Needing to call either indicates a problem in this case. Set the 'preferred size' of the text area by providing column/row size in the constructor. Add it the the scroll-pane. Job done.

import javax.swing.*;

public class DoesScroll {

    public static void main(String[] args){
        String str = "this\n\nshould\n\n\n\nscroll\n\n\nthis is the bottom";
        message("test", str, JOptionPane.INFORMATION_MESSAGE);
    }

    public final static void message(String title, String message, int messageType){
        JTextArea messageArea = new JTextArea(3,20);
        messageArea.setEditable(false);
        JScrollPane scroller = new JScrollPane(messageArea,
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        messageArea.setText(message);
        JOptionPane.showMessageDialog(null, scroller, title, messageType);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
3

The problem with my setup here was that I was calling messageArea.setPreferredSize() instead of scroller.setPreferredSize(). Once i took the sizing method calls off of messageArea and added them to scroller, the scrollbars were visible. I am not sure why this works the way it does, but if I figure it out, I'll update this answer. If anyone else knows, a comment here would be appreciated.

Chris Drappier
  • 5,280
  • 10
  • 40
  • 64