I'm learning Java right now, and one of the projects I've been working on as practice lately is just a simple text editor (using Swing). The one thing, though, that I can't for the life of me figure out, is how to add scroll bars to the text box if the text overflows.

Here's some of my code (There's way more, I just simplified what I have right now that makes the frame and text box):

JTextArea t;
		JFrame f;
		JPanel c;
		JScrollPane b;
		b = new JScrollPane();
		b.setAutoscrolls(true);
		f = new JFrame("JNotepad");
		f.setBounds(300, 200, 500, 500);
		c = new JPanel();
		f.setContentPane(c);
		t = new JTextArea();
		t.setFont(Font.decode("Courier New-14"));
		b.add(t);
		c.add(b);
		f.setJMenuBar(/* Menu bar is "m". This works just fine. */m);
		f.setVisible(true);

A little sloppy, I know, but I had to copy and paste and reorganize it from the rest of my code. I can honestly say I don't even have a remote idea as to how you add scroll bars, what's there is just a guess. The notepad works, but the scrollbars don't.

I also have an anaonymous inner class designed to resize the textbox to the size of the form if the mouse is moved over it, because I didn't know how else to do it (there was no "onResizeForm" event, was there?), so if that's interfering, well, let me know and I'll figure something out.

There is no add method for JScrollPane so you can't use it but there is JScrollPane constructor JScrollPane(Component view), which "Creates a JScrollPane that displays the contents of the specified component, where both horizontal and vertical scrollbars appear whenever the component's contents are larger than the view." (taken fro JAVA API)
check Java API here

JTextArea t;
	JFrame f;
	JPanel c;
	JScrollPane b;
	//b = new JScrollPane();
	b.setAutoscrolls(true);
	f = new JFrame("JNotepad");
	f.setBounds(300, 200, 500, 500);
	c = new JPanel();
	f.setContentPane(c);
	t = new JTextArea();
	t.setFont(Font.decode("Courier New-14"));
	b = new JScrollPane(t);
	c.add(b);
	f.setJMenuBar(/* Menu bar is "m". This works just fine. */m);
	f.setVisible(true);

Sorry, that didn't work. In fact, nothing changed about the program. Any other ideas?

This article has been dead for over six months. Start a new discussion instead.