Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

How to make JPanel scrollable in Java?

I have a class that extends JPanel, where I have overridden the paintComponent(Graphics g) method. However, I can't see the rectangles or the scroll bars I have drawn.

In the main function I have the following code below:

    MyClass mainPanel = new MyClass();
    mainPanel.setPreferredSize(new Dimension(1000, 1000));
    mainPanel.setLayout(new BorderLayout());

    JPanel scrollPanel = new JPanel();
    scrollPanel.setSize(new Dimension(2000, 2000));       
    JScrollPane scrollPane = new JScrollPane(scrollPanel,  JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  //Let all scrollPanel has scroll bars
    scrollPane.setViewportView(scrollPanel);
    scrollPane.setOpaque(true);

    scrollPanel.revalidate();
    mainPanel.add(scrollPane);


    JFrame frame = new JFrame("Scrollable Panel");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(mainPanel);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have solved this issue. MyClass extends JPanel. And I have overwritten paintComponent(Graphics g) method in which I draw rectangles through Graphics.

MyClass mainPanel = new MyClass()
mainPanel.setPreferredSize(new Dimension(7000, 1000));
mainPanel.setLayout(new BorderLayout());

JScrollPane scrollPane = new JScrollPane(mainPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  //Let all scrollPanel has scroll bars
scrollPane.setPreferredSize(new Dimension(1000, 900));


JFrame frame = new JFrame("Scrollable JPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane);
frame.setSize(1000, 900);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...