答案 0 :(得分:2)
首先看一下Laying Out Components Within a Container。虽然您可以使用GridBagLayout
,但您可以使用BorderLayouts
例如......
JPanel left = new JPanel(new BorderLayout());
left.add(new TestPane(), BorderLayout.NORTH);
left.add(new TestPane());
JPanel main = new JPanel(new BorderLayout());
main.add(left);
main.add(new TestPane(), BorderLayout.EAST);
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JPanel left = new JPanel(new BorderLayout());
left.add(new TestPane(), BorderLayout.NORTH);
left.add(new TestPane());
JPanel main = new JPanel(new BorderLayout());
main.add(left);
main.add(new TestPane(), BorderLayout.EAST);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(main);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBorder(new LineBorder(Color.RED));
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
答案 1 :(得分:0)
答案 2 :(得分:0)
我更喜欢使用BorderLayout
来安排我的面板。我设置了3个面板:东(宽100px),北(高100px)和中心:
public class Frame1 extends JFrame {
BorderLayout borderLayout1 = new BorderLayout();
JPanel jPanelEast = new JPanel();
JPanel jPanelCenter = new JPanel();
JPanel jPanelNorth = new JPanel();
BorderLayout borderLayout2 = new BorderLaout();
JPanel jPanelCentral = new JPanel();
public Frame1() {
try {
jbInit();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
void jbInit() throws Exception {
this.getContentPane().setLayout(borderLayout1);
jPanelEast.setBackground(Color.red);
jPanelEast.setForeground(Color.black);
jPanelEast.setMinimumSize(new Dimension(10, 10));
jPanelEast.setOpaque(true);
jPanelEast.setPreferredSize(new Dimension(100, 10));
jPanelCenter.setLayout(borderLayout2);
jPanelNorth.setBackground(Color.lightGray);
jPanelNorth.setMinimumSize(new Dimension(10, 10));
jPanelNorth.setOpaque(true);
jPanelNorth.setPreferredSize(new Dimension(10, 100));
this.getContentPane().add(jPanelEast, BorderLayout.EAST);
this.getContentPane().add(jPanelCenter, BorderLayout.CENTER);
jPanelCenter.add(jPanelNorth, BorderLayout.NORTH);
jPanelCenter.add(jPanelCentral, BorderLayout.CENTER);
}
public static void main(String[] args) {
Frame1 frame1 = new Frame1();
}
}