【问题标题】:Layout for displaying panels dynamically with scroll bar使用滚动条动态显示面板的布局
【发布时间】:2011-12-18 11:02:39
【问题描述】:

在java中,我一直在尝试创建一个可以接受其他带有滚动条的面板的面板。

我尝试使用 gridlayout,效果很好,除了如果我只添加几个面板,它会增大这些面板以适应父面板的大小。

我尝试使用 flowlayout,但这会使面板水平流动,因为有滚动条。

如何制作,以便我可以从顶部开始将面板添加到父面板,并使它们始终具有相同的尺寸(或它们的首选尺寸)。

此外,当我在事件后将面板添加到父面板时,它们直到我移动或调整表单大小后才会出现。我如何让它重新粉刷?对其调用 repaint() 不起作用。

【问题讨论】:

    标签: java swing jscrollpane layout-manager


    【解决方案1】:

    假设JScrollPane,请参阅Sizing a Scroll Pane。为方便起见,Scrollable 客户端(例如 JTable)提供 setPreferredScrollableViewportSize(),但您始终可以显式设置视口的大小。

    【讨论】:

      【解决方案2】:

      import java.awt.*;
      import java.awt.event.*;
      import javax.swing.*;
      import javax.swing.border.*;
      
      /** This lays out components in a column that is constrained to the
      top of an area, like the entries in a list or table.  It uses a GridLayout
      for the main components, thus ensuring they are each of the same size.
      For variable height components, a BoxLayout would be better. */
      class ConstrainedGrid {
      
          ConstrainedGrid() {
              final JPanel gui = new JPanel(new BorderLayout(5,5));
              gui.setBorder(new EmptyBorder(3,3,3,3));
              gui.setBackground(Color.red);
      
              JPanel scrollPanel = new JPanel(new BorderLayout(2,2));
              scrollPanel.setBackground(Color.green);
              scrollPanel.add(new JLabel("Center"), BorderLayout.CENTER);
              gui.add(new JScrollPane(scrollPanel), BorderLayout.CENTER);
      
              final JPanel componentPanel = new JPanel(new GridLayout(0,1,3,3));
              componentPanel.setBackground(Color.orange);
              scrollPanel.add(componentPanel, BorderLayout.NORTH);
      
              JButton add = new JButton("Add");
              gui.add(add, BorderLayout.NORTH);
              add.addActionListener( new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
                      componentPanel.add(new JTextField());
                      gui.validate();
                  }
              });
      
              Dimension d = gui.getPreferredSize();
              d = new Dimension(d.width, d.height+100);
              gui.setPreferredSize(d);
      
              JOptionPane.showMessageDialog(null, gui);
          }
      
          public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                  public void run() {
                      ConstrainedGrid cg = new ConstrainedGrid();
                  }
              });
          }
      }
      

      【讨论】:

      • +1 代表BoxLayout,代表example
      猜你喜欢
      • 2011-06-15
      • 2014-11-08
      • 1970-01-01
      • 2013-11-26
      • 2019-07-31
      • 2018-06-19
      • 2020-09-29
      • 1970-01-01
      • 2011-03-28
      相关资源
      最近更新 更多