gpt4 book ai didi

java - 如何使用 GridLayout 使 JScrollPane 上的 JPanel 仅填充宽度而不填充高度?

转载 作者:行者123 更新时间:2023-12-02 05:52:43 25 4
gpt4 key购买 nike

我尝试制作如下所示的布局。但我在添加新的 MyPanels 时遇到了问题。第一个 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:"));
}
}

最佳答案

问题是您在 CENTER 中添加了中间面板。中心充分利用可用空间。将 midPanel 设置为 BorderLayout 并在 North 上添加另一个面板,然后添加可用的 MyPanels。

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

关于java - 如何使用 GridLayout 使 JScrollPane 上的 JPanel 仅填充宽度而不填充高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23409503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com