【问题标题】:Child expands past the bounds of its parent when height or width set to 100% using MigLayout in Java使用 Java 中的 MigLayout 将高度或宽度设置为 100% 时,子级扩展超出其父级的边界
【发布时间】:2014-04-24 05:33:31
【问题描述】:

我正在尝试使用 MigLayout 设置某些元素的高度,以使用表达式“height 100%”来占据其父容器的整个高度,但是 MigLayout 中有某种反馈循环会导致高度加载时跳转到最大值。此问题仅在 MiGPanel 嵌入 JScrollPane 时发生,如果我删除处理 JScrollPane 的代码行并将 MiGPanel 添加到我的 JFrame 中,则程序按预期运行。我在那里添加了布尔语句,以使这个更容易看到。

注意: 我已经看到了这个修复,但我想使用一个解决方案,我的程序底部没有边距。 How to prevent MigLayout from exceeding a container's bounds

代码如下:

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import net.miginfocom.swing.MigLayout;

public class StackOverFlowQuestion {
    public static void main(String[] args) {

        JPanel MiGPanel = new JPanel();
        MiGPanel.setBackground(Color.red);
        MiGPanel.setLayout(new MigLayout());  

        JPanel greenPanel = new JPanel();
        greenPanel.setBackground(Color.green);
        MiGPanel.add(greenPanel, "pos 0 0, width 33%, height 100%");

        JPanel yellowPanel = new JPanel();
        yellowPanel.setBackground(Color.yellow);
        MiGPanel.add(yellowPanel, "pos 33% 0, width 33%, height 100%");

        JPanel bluePanel = new JPanel();
        bluePanel.setBackground(Color.blue);
        MiGPanel.add(bluePanel, "pos 66% 0, width 34%, height 100%");


        JFrame mainFrame = new JFrame();
        mainFrame.setLayout(new BorderLayout());

        boolean scroll = true;
        if(scroll){
            JScrollPane scrollPane = new JScrollPane();
            scrollPane.add(MiGPanel);
            scrollPane.setViewportView(MiGPanel);
            mainFrame.add(scrollPane);  
        }else{
            mainFrame.add(MiGPanel);
        }

        mainFrame.add(scrollPane);  
        mainFrame.pack();
        mainFrame.setSize(900, 600); 
        mainFrame.setVisible(true);
        mainFrame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    }
}

【问题讨论】:

  • 只有我一个人有这个问题?

标签: java swing jscrollpane miglayout


【解决方案1】:

经过无数个不眠之夜,我想出了一个解决办法:

    greenPanel.setLayout(new BorderLayout());
    greenPanel.add(new JLabel("test"));
    MiGPanel.add(greenPanel, "pos 0 0 33% 100%");

    JPanel yellowPanel = new JPanel();
    yellowPanel.setBackground(Color.yellow);
    MiGPanel.add(yellowPanel, "pos 33% 0 66% 100%");

    JPanel bluePanel = new JPanel();
    bluePanel.setBackground(Color.blue);
    MiGPanel.add(bluePanel, "pos 66% 0 100% 100%");

绝对定位元素不应使用 with 和 height 属性,而应使用“pos x y x1 y1”方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-17
    • 2013-02-25
    • 1970-01-01
    • 2020-01-05
    • 2013-01-22
    • 1970-01-01
    • 2017-11-08
    相关资源
    最近更新 更多