Skip to main content

How can I make scrollbars appear around a JPanel when using the paintComponent() method?

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
1 reply [Last post]
keksi
Offline
Joined: 2010-08-17

Hello all

How can I make scrollbars appear around a JPanel I use to draw "things" in? These "things" are graphical objects that are surely bigger than the current viewport, but nevertheless no scrollbars appear, even though I put a JScrollPane around.

Many thanx in advance

Keksi

Here is a simple demo to show the effect:

import java.awt.*;

import javax.swing.*;
public class GraphicsDemo extends JPanel
{
static public void main(String[] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(new GraphicsDemo()), BorderLayout.CENTER);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
@Override
protected void paintComponent(Graphics g)
{
g.setColor(Color.GRAY);
g.fillRect(10, 10, 300, 50);
g.setColor(Color.BLACK);
g.drawRect(10, 10, 300, 50);
g.setColor(Color.GRAY);
g.fillRect(10, 60, 50, 300);
g.setColor(Color.BLACK);
g.drawRect(10, 60, 50, 300);
}
}

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
keksi
Offline
Joined: 2010-08-17

I found the answer by myself: this implementation of the paintComponent() method works fine:

@Override
protected void paintComponent(Graphics g)
{
this.setPreferredSize(new Dimension(320, 370)); // Needed for the scroll bars to appear
g.setColor(Color.GRAY);
g.fillRect(10, 10, 300, 50);
g.setColor(Color.BLACK);
g.drawRect(10, 10, 300, 50);
g.setColor(Color.GRAY);
g.fillRect(10, 60, 50, 300);
g.setColor(Color.BLACK);
g.drawRect(10, 60, 50, 300);
this.revalidate(); // Needed to recalc the scroll bars
this.repaint(); // Needed to show the correct content
}