2011-10-31 135 views
3

在java中,我一直在尝试创建一个可以接受带有滚动条的其他面板的面板。使用滚动条动态显示面板的布局

我尝试使用gridlayout,这工作正常,除了如果我只添加几个面板的事实,它增长这些面板,以适应父面板的大小。

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

我该如何做到这一点,所以我可以将面板添加到从顶部开始的父面板,并使其始终具有相同的尺寸(或其首选尺寸)。

另外,当我在事件发生后将面板添加到父面板时,直到我移动或调整窗体大小后才显示它们。我如何重画?调用repaint()就无法工作。

回答

5

Constrained Grid

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

1为'BoxLayout',对于[示例](http://stackoverflow.com/questions/3174765/variable-layout-in-swing/3175280#3175280)。 – trashgod