2

I have created a GUI in Java which looks as shown below -

'panel_mid' is the white panel in the middle. I have added it to a scrollpane called 'panel_mid_scrollpane'.

Apart from 'panel_mid' there are more panels -

  • panel_left (containing 'back' button)
  • panel_right (visible on right hand side)

enter image description here

Revelant code for this gui is -

    panel_mid.setBorder(grayborder);
    panel_mid.setBounds(0, 0, 1100, 1060);
    panel_mid.setBackground(Color.white);
    panel_mid.add(obj.create_test_add_section);

    panel_mid_scrollpane = new JScrollPane(panel_mid);
    panel_mid_scrollpane.setLocation(150, 20);
    panel_mid_scrollpane.setSize(1000, 660);
    panel_mid_scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

The Add Section button shown in panel_mid, adds a section to the middle panel, every time it is clicked. When this button is clicked multiple times, the gui looks like -

enter image description here

As you could see, the scrollbar does not appear automatically as panels are added, the last panel is thus only half visible. What could be causing this problem ?

Thanks !

4

2 回答 2

3

当添加到滚动窗格的组件的首选大小大于滚动窗格的大小时,滚动条会自动出现。

您似乎正在使用空布局。

//panel_mid.setBounds(0, 0, 1100, 1060);
panel_mid.setBackground(Color.white);
panel_mid.add(obj.create_test_add_section);

panel_mid_scrollpane = new JScrollPane(panel_mid);
//panel_mid_scrollpane.setLocation(150, 20);
//panel_mid_scrollpane.setSize(1000, 660);

不要在 setSize() 和 setLocation 中使用空布局。Swing 旨在与布局管理器一起使用。如果您使用布局管理器,那么滚动条将自动工作,并且会自动为您计算大小和位置。

阅读关于Layout Mangers的 Swing 教程。

于 2013-05-24T14:57:12.687 回答
1

您必须告诉 GUI 刷新,以便重新布置容器。这将向容器显示它还必须显示滚动条。

因此,在 ActionListener 或您用来添加部分的任何内容中,添加如下代码:

     container_with_sections.validate();
     container_with_sections.repaint();

其中 container_with_sections 是包含 JScrollPane 的容器 (JContainer),或者是包含包含 JScrollPane 的容器的容器,依此类推。

于 2013-05-24T14:54:19.903 回答