1

I am a novice programmer in Java Swing. I am trying to make a JScrollPane with the JTextarea so that the text will scroll. But the scroll is not working. Please help me with this. I don't know what I am doing wrong. I am providing my code snippet here.

JTextArea ta = new JTextArea("Hello.\n \n \n \n \n There.", 5, 10);
ta.setBounds(250, 60, 120, 60);

JScrollPane jp = new JScrollPane(ta,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jp.setBounds(250, 60, 140, 80);
jp.setPreferredSize(new Dimension(150, 150));

//jp.setViewportView(ta);
ta.setLineWrap(true);
panel.add(ta);
panel.add(jp);
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Moha
  • 11
  • 4
  • 1
    1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete and Verifiable Example). 2) See [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/q/7229226/418556) (Yes.) .. – Andrew Thompson Jul 10 '14 at 20:01
  • 2
    .. 3) Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead [use layout managers](http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html), or [combinations of them](http://stackoverflow.com/a/5630271/418556), along with layout padding & borders for [white space](http://stackoverflow.com/q/17874717/418556). – Andrew Thompson Jul 10 '14 at 20:01
  • 4
    `..panel.add(ta); panel.add(jp);` should be `..panel.add(jp);`. `ta` will appear because it has been added to `jp`. – Andrew Thompson Jul 10 '14 at 20:03
  • 2
    This: `ta.setBounds(250, 60, 120, 60);` is going to mess you up bad. Never restrict the size of a component held by the a JScrollPane like this, since if you do this, it can't expand and the scrollbars will thus not work. Also it your use of null layout flags your code as newbie code, since it does not scale well at all. Learn the use of and then start using the layout managers. – Hovercraft Full Of Eels Jul 10 '14 at 23:46
  • Thank you so much for the valuable tips. I would remember those and implement while writing the codes. I appreciate your time and suggestions – Moha Jul 13 '14 at 16:31

1 Answers1

2

By removing the below line:

panel.add(ta);

This will solve your problem since you are already adding the JTextArea to the JScrollPane (Also the other comments are worth looking at :) )