简体   繁体   English

基于它的paintComponent的可滚动JPanel

[英]Scrollable JPanel based on it's paintComponent

I am using java-2d to visualize my application. 我正在使用java-2d可视化我的应用程序。 I've created the panel with extending of JPanel to draw a simple rectangle. 我创建了带有扩展的JPanel的面板以绘制一个简单的矩形。 I've named this MyPanel . 我已将此MyPanel命名为MyPanel

So, the width and height of panel dynamically changed by rectangle definition. 因此,面板的宽度和高度会随矩形的定义而动态变化。 I use JScrollPane to add scroll ability to my panel like below: 我使用JScrollPane向面板添加滚动功能,如下所示:

JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

I use below code to add my panel to window: 我使用以下代码将面板添加到窗口:

JFrame frame = new JFrame();
frame.setLayout(new GridLayout(1,1));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setResizable(false);

MyPanel panel = new MyPanel();

JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

frame.add(scrollPane);
frame.setVisible(true);

Now, in paintComponents of MyPanel, I want to paint the rectangle with the width and height that are more than container (frame) width and height. 现在,在MyPanel的paintComponents中,我要绘制宽度和高度大于容器(框架)宽度和高度的矩形。 But the scroll is not working. 但是滚动不起作用。

What is wrong? 怎么了? Could any one help me? 有人可以帮我吗?

Thanks in advance :) 提前致谢 :)

The scroll pane uses the components preferred size to determine how big it should be and provides scrolling when the components size is larger then size of the scroll pane... 滚动窗格使用组件的首选大小来确定其大小,并在组件的大小大于滚动窗格的大小时提供滚动。

Try overriding the getPreferredSize method of the custom component and return the size you want 尝试覆盖自定义组件的getPreferredSize方法,并返回所需的大小

If the size of MyPanel changes over the runtime of your program, use a reference to a Dimension (returned by getPreferredSize) and call revalidate when you change it 如果MyPanel的大小在程序的运行时发生变化,请使用对Dimension的引用(由getPreferredSize返回),并在更改时调用revalidate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM