在运行时添加的Java scrollPane不会滚动

时间:2015-04-21 09:56:57

标签: java swing jscrollpane

The GUI we're building 我们正在尝试创建一个包含多个scrollpanes的应用程序。第一个或多或少都好。我们无法调整它必须在运行时滚动的面板。因此,要解决此问题,我们在GUI构建器中设置大小:

The hacky fix

只有通过这种hacky修复,滚动面板才能正确调整大小。因为代码不起作用:

    PanelGraph.setPreferredSize(PanelGraph.getPreferredSize());
    PanelGraph.validate();
    TopPanel.setSize(locationX, (panelDatabase.length * 15));
    TopPanel.setPreferredSize(TopPanel.getPreferredSize());
    TopPanel.validate();
    TopScrollPanel.setViewportView(TopPanel);
    TopScrollPanel.getVerticalScrollBar().setUnitIncrement(15);
    TopScrollPanel.validate();

TopPanel是TopScrollPanel中的Panel,我们尝试使用历史数组的长度乘以一行像素(15)来设置大小。此代码不会调整TopPanel或viewportview的大小。这部分目前有效,但我们仍然想知道如何解决这个问题?

对于第二个scrollPanel,我们每次更新面板时都必须调整它,因为列表会增长。无论我们尝试使用什么代码:滚动窗格都不会滚动。当我们点击这个函数时调用:

public void actionPerformed(ActionEvent e) {
    history = SensorValuesHistory();
    javax.swing.JScrollPane HistoryLogPane = new javax.swing.JScrollPane();
    HistoryLogPane.setLayout(new ScrollPaneLayout()); // edit @kiheru
    HistoryLogPane.setBackground(Color.WHITE);
    HistoryLogPane.setBorder(BorderFactory.createEmptyBorder());
    HistoryLogPane.setLocation(0, 0);
    HistoryLogPane.add(history);
    HistoryLogPane.setSize(new Dimension(history.getSize()));
    history.setPreferredSize(history.getSize());//and we tried: history.setPreferredSize(history.getPreferredSize());
    System.out.println("SIZE: " + HistoryLogPane.getSize());
    HistoryLocationPanel.removeAll();
    HistoryLocationPanel.add(HistoryLogPane);
    HistoryLocationPanel.repaint();
    HistoryLogPane.repaint();
}

由于第一个问题,我们删除旧的滚动窗格并生成一个新的滚动窗格。我们该做什么让这个scrollPane滚动?

1 个答案:

答案 0 :(得分:0)

@kiheru,感谢您的建议和指示!通过重新验证历史记录面板而不是滚动窗格,功能现在正常工作!这是工作代码:

    public void actionPerformed(ActionEvent e) {
    HistoryLogPane.setLayout(new ScrollPaneLayout());//<<<
    history = (JPanel)HistoryLogPane.getViewport().getView();//<<<
    javax.swing.JScrollPane HistoryLogPane = new javax.swing.JScrollPane();
    HistoryLogPane.setLayout(new ScrollPaneLayout()); // edit @kiheru
    HistoryLogPane.setBackground(Color.WHITE);
    HistoryLogPane.setBorder(BorderFactory.createEmptyBorder());
    HistoryLogPane.setLocation(0, 0);
    HistoryLogPane.add(history);
    HistoryLogPane.setSize(new Dimension(history.getSize()));
    history.setPreferredSize(history.getSize());//and we tried: history.setPreferredSize(history.getPreferredSize());
    history.revalidate();//<<<
    System.out.println("SIZE: " + HistoryLogPane.getSize());
    HistoryLocationPanel.removeAll();
    HistoryLocationPanel.add(HistoryLogPane);
    HistoryLocationPanel.repaint();
    HistoryLogPane.repaint();
}
在我们添加的每一行之后

我们放了一个'//&lt;&lt;&lt;&lt;&lt;指出来。

相关问题