繁体   English   中英

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

[英]How to make that JPanel on JScrollPanel with GridLayout fill only width but not fill height?

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

在此输入图像描述

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:"));
    }
}

问题是你在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:"));
}
}

暂无
暂无

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

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