如何使JPanel在Java中可滚动? [英] How to make JPanel scrollable in Java?

查看:89
本文介绍了如何使JPanel在Java中可滚动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扩展JPanel的类,在这里我重写了paintComponent(Graphics g)方法.但是,我看不到绘制的矩形或滚动条.

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);  

推荐答案

我已经解决了这个问题. MyClass扩展了JPanel.而且我已经覆盖了paintComponent(Graphics g)方法,该方法通过Graphics绘制矩形.

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);

这篇关于如何使JPanel在Java中可滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆