如何使JPanel可滚动? [英] How to make JPanel scrollable?
问题描述
我正在为大学项目创建GUI,并且试图了解JScrollPane
的工作原理.
I'm creating GUI for my university project and I 'm trying to understand how JScrollPane
works.
我已经成功编写了一个简单的程序,该程序以可滚动的方式显示图片:
I have successfully written simple program which shows picture in a scrollable way:
public class ScrollPaneTest{
public static void main(String[] args){
JFrame testFrame = new JFrame("ramka testowa");
testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel picture = new JLabel(new ImageIcon("JavaSwingCompoentsList.PNG"));
JScrollPane scrollPane = new JScrollPane(picture);
testFrame.add(scrollPane, BorderLayout.CENTER);
testFrame.setSize(400, 400);
testFrame.setVisible(true);
}
}
尽管在我的最终GUI中,我只想将JScrollPane
应用于其中的一部分,例如单个JPanel
.为了验证这个想法,我编写了以下代码,不幸的是,该代码不起作用:
Although, in my final GUI, I would like to apply JScrollPane
only to a part of it, e.g. single JPanel
. To test this idea I have written following code, which unfortunately does not work:
public class ScrollPaneTest{
public static void main(String[] args){
JFrame testFrame = new JFrame("ramka testowa");
testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel picture = new JLabel(new ImageIcon("JavaSwingCompoentsList.PNG"));
JScrollPane scrollPane = new JScrollPane(picture);
JPanel insidePanel = new JPanel();
insidePanel.add(scrollPane);
testFrame.add(insidePanel, BorderLayout.CENTER);
testFrame.setSize(400, 400);
testFrame.setVisible(true);
}
}
我已经阅读了许多教程,以及Stack和CodeRanch的文章,但我仍然无法理解JScrollPane
的工作原理.我怀疑我的错误与指定JPanel
-to-scroll的尺寸有关,但是我尝试过的每一种方法都没有给我滚动条或图片.
I have read numerous tutorials, as well as Stack and CodeRanch articles and I still fail to grasp the idea of how the JScrollPane
work. I suspect, that my mistake has something to do with specifying the dimension of JPanel
-to-scroll, but every single approach I have tried gave me no scrollbars or no picture at all.
如果您能为我提供解决此问题的正确方法,最重要的是,告诉我我哪里错了,我将不胜感激.
If you could show me the right solution to this problem and most importantly, show me where I was wrong I would be very grateful.
推荐答案
- 使用图片初始化
JPanel
,而不是JScrollPane
-
要将
JPanel
添加到JScrollPane
,请执行以下操作:
- Initialize
JPanel
, notJScrollPane
with picture To add the
JPanel
toJScrollPane
, do:
scrollPane.setViewportView (panel)
将JScrollPane
而不是JPanel
添加到JFrame
Add the JScrollPane
, not JPanel
to the JFrame
这篇关于如何使JPanel可滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!