简体   繁体   English

动态将JPanel实例添加到JScrollPane

[英]Dynamically add JPanel instances to a JScrollPane

I'm trying to add precreated JPanel instances into a bigger JPanel into a JScrollPane, but I can't get it to work. 我正在尝试将预先创建的JPanel实例添加到更大的JPanel中,并添加到JScrollPane中,但是我无法使其正常工作。

I'm using NetBeans to create the container, then using the context menu to include it into a scroll panel. 我正在使用NetBeans创建容器,然后使用上下文菜单将其包含在滚动面板中。

To add the JPanel at runtime I'm doing this: 要在运行时添加JPanel,我需要这样做:

ActivityPanel actPanel;

for(Reservation r: mainFrame.getKiosko().getReservations()) {
    if( r.getUser().equals(user)) {
        actPanel = new ActivityPanel(r.getActivity(),mainFrame);
        actPanel.setHour(r.getHour());
        Dimension actDim = new Dimension(600, 100);
        actPanel.setPreferredSize(actDim);
        actPanel.setMaximumSize(actDim);
        actPanel.setMinimumSize(actDim);

        pnlReservations.add(actPanel);                
    }
}

But it just is not working. 但这是行不通的。 Should I create the ScrollPanel at runtime? 我应该在运行时创建ScrollPanel吗? If so How should I do it? 如果是这样,我该怎么办?

pnlReservation has a BoxLayout by page axis. pnlReservation具有按页面轴的BoxLayout。

actPanel.setPreferredSize(actDim);

Don't try to manually control the preferred size of a component. 不要尝试手动控制组件的首选大小。 The size of the panel should be determined by the components you add to the panel. 面板的大小应由添加到面板中的组件确定。

Same with your pnlReservation , don't hardcode a preferred size. 与您的pnlReservation相同,请勿对首选大小进行硬编码。 The layout manager will determine its preferred size based on the preferred size of the components added to it. 布局管理器将根据添加到其中的组件的首选大小来确定其首选大小。

Then the scrollbars will appear automatically as the preferred size of the pnlReservation dynamically changes when you add components to it. 然后,随着pnlReservation的首选大小在pnlReservation添加组件时动态变化,滚动条将自动出现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM