Reputation: 385
I have a JFrame which holds and JScrollPane. The JScrollPane itself holds a class derived from JPanel. I use the JPanel class to draw an Image and some other primitives on it. Unfortunately the scrollbars of the JScrollPane do not occur even though the JPanel extends over the JSrollPane size.
I created some test code which runs:
This is the main class:
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
class ScrolledPane extends JFrame{
private JScrollPane scrollPane;
public ScrolledPane()
{
setTitle( "Scrolling Pane Application" );
setSize( 300, 200 );
setBackground( Color.gray );
TestPanel testPanel = new TestPanel();
testPanel.setLayout( new BorderLayout() );
scrollPane = new JScrollPane(testPanel);
this.getContentPane().add(scrollPane, BorderLayout.CENTER);
}
public static void main( String args[] )
{
// Create an instance of the test application
ScrolledPane mainFrame = new ScrolledPane();
mainFrame.setVisible( true );
}
}
And here is the code of the class derived from JPanel:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JPanel;
public class TestPanel extends JPanel {
private Image groundPlan;
public TestPanel(){
super();
this.setBackground(Color.green);
this.setLayout(new BorderLayout());
this.groundPlan = Toolkit.getDefaultToolkit().getImage("D:\\EclipseWorkspace\\img.png");
}
public void paint(Graphics graphics) {
super.paint(graphics);
if(groundPlan != null) {
graphics.drawImage(groundPlan, 0, 0, this);
}
}
}
Interestingly the Scrollbars appear if I just insert a JLabel with and Image into the JScrollpane instead of the JPanel. Here the code for this option:
public ScrolledPane() //Frame <- Scrollpane <- label <- image
{
setTitle( "Scrolling Pane Application" );
setSize( 300, 200 );
setBackground( Color.gray );
JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
Icon image = new ImageIcon("D:\\EclipseWorkspace\\img.png");
JLabel label = new JLabel( image );
scrollPane = new JScrollPane();
scrollPane.getViewport().add( label );
this.getContentPane().add(scrollPane, BorderLayout.CENTER);
}
I would appriciate if you could tell how I can make the scrollbars occur if I use the JPanel in the JScrollPane.
Regards & Thanks Marc
Upvotes: 2
Views: 2609