我正在尝试使用MigLayout设置某些元素的高度以使用表达式“height 100%”占据其父容器的整个高度,但是在MigLayout中存在某种反馈循环导致高度加载时跳转到最大值。只有当MiGPanel嵌入到JScrollPane中时才会出现此问题,如果我删除处理JScrollPane的代码行并将MiGPanel添加到我的JFrame中,那么程序将按预期运行。我在那里添加了布尔语句以使这个eaiser看到。
注意: 我已经看过这个修复但是我想使用一个解决方案,我的程序底部没有余量。 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);
}
}
答案 0 :(得分:0)
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"方法。