This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes JPanel & JScrollPane problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JPanel & JScrollPane problem" Watch "JPanel & JScrollPane problem" New topic

JPanel & JScrollPane problem

Sree Nivas
Ranch Hand

Joined: Jul 24, 2003
Posts: 95
I need a small solution or clue for my current project. If you have any idea pls share with me.
I included a JPanel (which has some graph) in to JScrollPane, and it doesn't display the scrollbars. Why? Can you tell me what could be the reason?
Can we add a container(for ex. JPanel) into JScrollPane?

Here's the code. Anything wrong in this code?

import java.awt.*;
import javax.swing.*;

public class Test2 extends JFrame{
public Test2() {
JInternalFrame jInternalFrame = new JInternalFrame("Test",true,true,true,true);
JPanel jPanel = new PanelTest();
JScrollPane jScrollPane = new JScrollPane(jPanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

public static void main(String[] args) {
new Test2();

class PanelTest extends JPanel {

public PanelTest(){}

public void paintComponent(Graphics g) {
g.drawString("Main Time(us)",30,99);

Craig Wood
Ranch Hand

Joined: Jan 14, 2004
Posts: 1535
The first clue comes from adding this inspection line in your Test2 constructor

It gets the actual size of your component (jPanel) after the gui is realized.
In Swing a scrollpane asks its viewport child (the view, here, jPanel) for its preferred size as it gathers information to layout its viewports view. If you want your component to be shown at a size other than the scrollpanes viewport view size you must provide the size information to the scrollpane. You can do this by calling setPreferredSize on the component or by overriding getPreferredSize in the component and returning the desired size. With the code you posted the first option would be the obvious choice:
Sree Nivas
Ranch Hand

Joined: Jul 24, 2003
Posts: 95
Thanks a lot. It's working fine.

Reyna Estrella

Joined: Oct 20, 2009
Posts: 1
thks !!! it was that i needed
I agree. Here's the link:
subject: JPanel & JScrollPane problem
It's not a secret anymore!