2

每次按下按钮时,我都会尝试在运行时将新面板插入另一个面板。我的问题是原始面板空间不足,我看不到我正在添加的新面板。

到目前为止我已经尝试过:

  • 使用滚动窗格进行垂直滚动没有成功。
  • 使用 flowlayout - 不走运。尝试禁用水平滚动 - 继续将新面板向右推(因为没有滚动,所以无法到达它)。
  • 尝试使用borderlayout - 没有运气。

testpanel t = new testpanel();
t.setVisible(true);
this.jPanel15.add(t);   
this.jPanel15.validate();
this.jPanel15.repaint();

此代码假设将t面板插入jpanel15. 使用 flowlayout,它会t像我想要的那样向下推动面板,但没有垂直滚动。

PS:我正在使用 netbeans 来创建我的 GUI。

4

2 回答 2

1

我的问题是原始面板空间不足,我看不到我正在添加的新面板。尝试使用滚动窗格进行垂直滚动,但没有成功。

FlowLayout 水平添加组件,而不是垂直添加组件,因此您永远不会看到垂直滚动条。相反,您可以尝试Wrap Layout

创建滚动窗格的基本代码是:

JPanel main = new JPanel( new WrapLayout() );
JScrollPane scrollPane = new JScrollPane( main );
frame.add(scrollPane);

然后,当您将组件动态添加到主面板时,您将执行以下操作:

main.add(...);
main.revalidate();
main.repaint(); // sometimes needed
于 2013-06-03T15:05:03.257 回答
0
  1. 使用JScrollPane代替(外)JPanel
  2. 或者有一个BorderLayoutfor the JPanel,把一个JScrollPaneatBorderLayout.CENTER作为唯一的控制。以JScrollPane常规JPanel为视图。

在任何情况下,您都会将控件添加到JScrollPane. 假设您的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( );
于 2013-06-03T11:32:18.803 回答