1
votes

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.

2
try setting the size also by panel.setSize(2000,2000); - Pragalathan M
Don't use setPreferredSize() this way; see also this Q&A. - trashgod

2 Answers

2
votes

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();
            }
        });
    }
}
0
votes

to know more about jscrollpane you can refer Jscrollpane oracle docs