我试图得到一个有两个面板的窗口,一个面板在右边(红色),宽度为100像素,另一个占据剩余空间(蓝色)。
这是结果,这显然不是预期的输出,我预计只能看到红色和蓝色,在右边取红色100像素的宽度,其余窗口为蓝色。
这就是我尝试过的:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Insets;
import java.awt.Panel;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
// -------------------------------
// marginTop
// -------------------------------
// | | | | |
// | | | s | |
// |m| | u |m|
// |a| | b |a|
// |r| | P |r|
// |g| | a |g|
// |i| subPanelCenter | n |i|
// |n| | e |n|
// |L| | l |R|
// |e| | R |i|
// |f| | i |g|
// |t| | g |h|
// | | | h |t|
// | | | t | |
// | |\_______________________/| |
// | | panelCenter | |
// -------------------------------
// marginBottom
// -------------------------------
public class Test3 extends Frame {
Insets windowInsets;
// Main Panels
Panel panelCenter = new Panel();
Panel subPanelCenter = new Panel();
Panel subPanelRight = new Panel();
// Margin Panels
Panel marginTop = new Panel();
Panel marginBottom = new Panel();
Panel marginLeft = new Panel();
Panel marginRight = new Panel();
public Test3() {
setSize(660,540);
setUndecorated(false);
setVisible(true);
windowInsets = getInsets();
marginTop.setBackground(Color.PINK);
marginRight.setBackground(Color.GREEN);
marginLeft.setBackground(Color.BLACK);
marginBottom.setBackground(Color.YELLOW);
subPanelCenter.setBackground(Color.BLUE);
subPanelRight.setBackground(Color.RED);
panelCenter.setLayout(new FlowLayout());
panelCenter.add(subPanelCenter);
panelCenter.add(subPanelRight);
// Add Panels
add("North", marginTop);
add("South", marginBottom);
add("West", marginLeft);
add("East", marginRight);
add("Center", panelCenter);
// Resize Panels
layoutResize();
// Close Button Listener
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
public void layoutResize() {
subPanelRight.setPreferredSize( new Dimension(100, getSize().height));
marginTop.setPreferredSize( new Dimension(getSize().width, windowInsets.top) );
marginBottom.setPreferredSize( new Dimension(getSize().width, windowInsets.bottom) );
marginLeft.setPreferredSize( new Dimension(windowInsets.left, getSize().height) );
marginRight.setPreferredSize( new Dimension(windowInsets.right, getSize().height) );
}
public static void main( String[] args ) {
Test3 window = new Test3();
}
}