JPanel panel = new JPanel(new GridLayout(0,1));
JScrollPane contentpane = new JScrollPane(panel);
JButton add = new JButton("ADD");
add.actionListener(new ActionListener() {
public void actionPerformed(){
MyPanel newpanel = new MyPanel("title","Button"); //MyPanel is a class which extends JPanel and contains constructor MyPanel(String TitleToSet ,String ButtonTitleTOAdd)
panel.add(newpanel);
panel.repaint();
}) ;
我使用此代码认为它会动态地将MyPanel添加到网格布局中,如果添加更多“MyPanel”,“panel”将可滚动。然而,情况并非如此,第一个“MyPanel”填满了整个“面板”,并且在添加第二个“MyPanel”(通过单击“添加”按钮)时,第一个“MyPanel”被缩小以便为第二个添加空间。并且在添加更多内容时,所有“MyPanel”都适合视口而不是使“面板”可滚动。如何动态添加这些“MyPanel”并使“面板”可以滚动添加更多?任何帮助将不胜感激。
答案 0 :(得分:1)
http://docs.oracle.com/javase/7/docs/api/javax/swing/JScrollPane.html:
默认情况下,JScrollPane使用ScrollPaneLayout来处理布局 它的子组件。 ScrollPaneLayout确定要制作的大小 视口视图有两种方式之一:
- [...]
- 使用了getPreferredSize。
醇>
您应该添加
行panel.setPreferredSize(new Dimension(0, panel.getComponents().size() * SUB_PANEL_HEIGHT));
到你的ActionListener。
完整示例:
package main;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Timer;
class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(400, 400));
frame.setSize(400, 400);
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(new JLabel("BOO"));
panel.add(new JButton("BBBB"));
JScrollPane contentpane = new JScrollPane(panel);
frame.add(contentpane);
new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JPanel newpanel = new JPanel();
newpanel.add(new JLabel("LOL"));
panel.add(newpanel);
System.out.println(100 * panel.getComponents().length);
panel.setPreferredSize(new Dimension(0, 100 * panel.getComponents().length));
contentpane.validate();
}
}).start();
frame.setVisible(true);
}
}