问题描述
我尝试使用以下方法将JPanel添加到JScrollPane:
I'm tried to add a JPanel to a JScrollPane using:
panel1 Panel1 = new panel1();
jScrollPane1.setViewportView(Panel1);
,它奏效了.但是问题在于,即使Panel1较大,scrollPane也不显示滚动条. (我正在使用NetBeans,而panel1是jpanel形式)
and it worked. But the problem is scrollPane doesn't show scroll bars even the Panel1 is bigger. (I'm working with NetBeans & panel1 is a jpanel form)
推荐答案
覆盖,方法,您可能可以看到滚动条.或者,您可以简单地调用 setPreferredSize(),尽管如API中所述
Override, getPreferredSize() method for the said JScrollPane
, you might be able to see the Scroll Bar. Or one can simply call setPreferredSize(), though as stated in the API
覆盖将是有益的,因为它倾向于为所述JComponent
定义一些适当的尺寸.
overriding will be beneficial, as it tends to define some appropriate dimensions to the said JComponent
.
类似这样的东西:
JScrollPane scroller = new JScrollPane() {
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
};
scroller.setViewportView(panelWithScroll);
一个例子:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PanelScroller {
private void displayGUI() {
JFrame frame = new JFrame("Swing Worker Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
JPanel panelWithScroll = new JPanel();
panelWithScroll.setLayout(new GridLayout(0, 1, 5, 5));
JScrollPane scroller = new JScrollPane() {
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
};
scroller.setViewportView(panelWithScroll);
//scroller.setPreferredSize(new Dimension(300, 200));
for (int i = 0; i < 20; i++) {
panelWithScroll.add(new JLabel(Integer.toString(i + 1), JLabel.CENTER));
}
contentPane.add(scroller);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
new PanelScroller().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
这篇关于添加JPanel时,JScrollPane不显示滚动条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!