如何使用GridLayout使JScrollPane中的JPanel仅填充宽度但不填充填充高度?

时间:2014-05-01 14:16:30

标签: java swing layout

我尝试制作如下所示的布局。但我有一个添加新的MyPanels的poroblem。第一个MyPanel填充其所有父级(midPanel)。如何使MyPanel只采用所需的高度和填充宽度?

enter image description here

public class Main extends JFrame {

JPanel upPanel = new JPanel();
JPanel midPanel = new JPanel();
JPanel downPanel = new JPanel();
JButton button = new JButton("add new Panel");

Main() {
    this.setSize(800, 600);
    this.setLayout(new BorderLayout());

    this.add(upPanel, BorderLayout.PAGE_START);
    JScrollPane jsp = new JScrollPane(midPanel);
    this.add(jsp, BorderLayout.CENTER);
    this.add(downPanel, BorderLayout.PAGE_END);
    this.midPanel.setLayout(new GridLayout(0, 1, 3, 3));

    upPanel.add(button);

    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            midPanel.add(new MyPanel());
            midPanel.updateUI();

        }
    });

}

public static void main(String[] args) {
    new Main().setVisible(true);
}
}
class MyPanel extends JPanel {

    MyPanel() {
        this.setLayout(new GridLayout(2, 5, 5, 5));
        this.setBorder(BorderFactory.createRaisedBevelBorder());

        this.add(new JLabel("Nomo:"));
    }
}

1 个答案:

答案 0 :(得分:2)

问题是你在CENTER中添加了mid-Panel。中心使用完整的自由空间。将midPanel设置为BorderLayout并在North上添加另一个面板,然后添加可用的MyPanel。

public class Main extends JFrame {

JPanel upPanel = new JPanel();
JPanel newMidPanel = new JPanel();
JPanel downPanel = new JPanel();
JButton button = new JButton("add new Panel");

Main() {
    this.setSize(800, 600);
    this.setLayout(new BorderLayout());
    JPanel midPanel = new JPanel(new BorderLayout());
    this.add(upPanel, BorderLayout.PAGE_START);
    JScrollPane jsp = new JScrollPane(midPanel);
    this.add(jsp);
    this.add(downPanel, BorderLayout.PAGE_END);
    this.newMidPanel = new JPanel(new GridLayout(0, 1, 3, 3));
    upPanel.add(button);
    midPanel.add(newMidPanel, BorderLayout.NORTH);
    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            newMidPanel.add(new MyPanel());
            newMidPanel.updateUI();

        }
    });
}

public static void main(String[] args) {
    new Main().setVisible(true);
}
}

class MyPanel extends JPanel {

MyPanel() {
    this.setLayout(new GridLayout(2, 5, 5, 5));
    this.setBorder(BorderFactory.createRaisedBevelBorder());

    this.add(new JLabel("Nomo:"));
}
}