[英]How to add JPanel into another JPanel with vertical scrollpane at runtime?
I'm trying to insert a new panel into another panel in runtime everytime I press a button. 我试图在每次按下按钮时在运行时将新面板插入另一个面板。 My problem is the original panel runs out of space and I can't see the new panels I'm adding.
我的问题是原始面板空间不足,看不到我要添加的新面板。
What I've tried so far: 到目前为止,我已经尝试过:
testpanel t = new testpanel();
t.setVisible(true);
this.jPanel15.add(t);
this.jPanel15.validate();
this.jPanel15.repaint();
This code suppose to insert the t
panel into jpanel15
. 该代码假定将
t
面板插入jpanel15
。 With flowlayout it pushes the t
panel downwards just like I want it to but with no vertical scroll. 有了flowlayout,它像我想要的那样将
t
面板向下推,但没有垂直滚动。
PS: I'm using netbeans in order to create my GUI. PS:我正在使用netbeans来创建我的GUI。
My problem is the original panel runs out of space and I cant see the new panels i'm adding.
我的问题是原始面板空间不足,我看不到我要添加的新面板。 Tried using scrollpane for vertical scrolling with no success.
尝试使用滚动窗格进行垂直滚动,但没有成功。
A FlowLayout adds components horizontally, not vertically so you will never see vertical scrollbars. FlowLayout水平添加组件,而不是垂直添加组件,因此您永远不会看到垂直滚动条。 Instead you can try the Wrap Layout .
相反,您可以尝试Wrap Layout 。
The basic code to create the scrollpane would be: 创建滚动窗格的基本代码为:
JPanel main = new JPanel( new WrapLayout() );
JScrollPane scrollPane = new JScrollPane( main );
frame.add(scrollPane);
Then when you dynamically add components to the main panel you would do: 然后,当您将组件动态添加到主面板时,您将执行以下操作:
main.add(...);
main.revalidate();
main.repaint(); // sometimes needed
JScrollPane
instead of the (outer) JPanel
JScrollPane
代替(外部) JPanel
BorderLayout
for the JPanel
, put in a JScrollPane
at BorderLayout.CENTER
as the only control. JPanel
提供BorderLayout
,将其放在BorderLayout.CENTER
的JScrollPane
中作为唯一控件。 The JScrollPane
takes a regular JPanel
as view. JScrollPane
将常规的JPanel
作为视图。 In any case you will then add the control to the JScrollPane
. 无论如何,您都将控件添加到
JScrollPane
。 Suppose your JScrollPane
variable is spn
, your control to add is ctrl: 假设您的
JScrollPane
变量是spn
,要添加的控件是ctrl:
// Creation of the JScrollPane: Make the view a panel, having a BoxLayout manager for the Y-axis
JPanel view = new JPanel( );
view.setLayout( new BoxLayout( view, BoxLayout.Y_AXIS ) );
JScrollPane spn = new JScrollPane( view );
// The component you wish to add to the JScrollPane
Component ctrl = ...;
// Set the alignment (there's also RIGHT_ALIGNMENT and CENTER_ALIGNMENT)
ctrl.setAlignmentX( Component.LEFT_ALIGNMENT );
// Adding the component to the JScrollPane
JPanel pnl = (JPanel) spn.getViewport( ).getView( );
pnl.add( ctrl );
pnl.revalidate( );
pnl.repaint( );
spn.revalidate( );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.