Search code examples
javaswingjscrollpane

Java : Why doesn't this scrollpane scroll?


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


Solution

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