1

I'm trying to create a screen that will allow me to scroll to different areas of the JPanel. i.e. I want a JPanel for drawing on which has a bigger size than the JFrame it is in, I am trying to use JScrollPane to view the different areas of the JPanel.

JFrame mainFrame = new JFrame("My Frame");        
mainFrame.setSize(700, 700);

clickScreen = new ClickPanel();   
clickScreen.setPreferredSize(new Dimension(2000, 2000));

JScrollPane scrollArea = new JScrollPane(clickScreen,
                                         JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
                                         JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);


mainFrame.getContentPane().add(scrollArea, BorderLayout.CENTER);

Where ClickPanel is a class I created which extends JPanel and is used for drawing.

My problem is: when I scroll using the scroll bars the view point moves, but the drawing from my paintComponent says in the same place. I want to be able to scroll to a new area below it so that I can draw there.

James Walker
  • 43
  • 1
  • 4

2 Answers2

2

You can try this:

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;


public class ScrollingView extends JFrame {

    private static final long serialVersionUID = -866635590539200791L;

    private JScrollPane scrollPane;
    private JPanel panel;

    public ScrollingView() {
        panel = new JPanel();
        panel.setPreferredSize(new Dimension(2000, 2000));
        panel.setLayout(new BorderLayout());

        panel.add(new JLabel("Label 1 Set to West"), BorderLayout.WEST);
        panel.add(new JLabel("Label 2 Set to East"), BorderLayout.EAST);

        scrollPane = new JScrollPane(panel);

        setPreferredSize(new Dimension(700, 700));
        setContentPane(scrollPane);
        pack();
        setVisible(true);
    }

    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new ScrollingView();
            }
        });
    }
}
Tapas Bose
  • 28,796
  • 74
  • 215
  • 331
  • 1
    Note _ad hoc_ use of `setPreferredSize()` for illustration only. If used for drawing only, OP's `ClickPanel` should determine its own preferred size. – trashgod Mar 04 '12 at 22:17
0

to know more about jscrollpane you can refer Jscrollpane oracle docs

Rak
  • 341
  • 6
  • 12