我是GridBagLayout的新手,但我尝试使用我能找到的标准约定,即在一张网格纸上绘制我的想法,然后尝试将网格值转换为gridbag ...
我的目标是制作如下所示的布局:
它目前看起来像这样:
任何想法为什么?
如果你想到一个左上角为0,0的网格,我正在寻找的确切尺寸
-
目标图片中面板中的红色:从第0列开始,跨越10列,高度为1行
-
为黑色面板:从第0列开始,第1行,跨10列,高度为20行
-
为蓝色面板:从第0列开始,第21行,跨越10列,高度为1
-
表示绿色列:从第10列开始,第0行,第16行,第7列,高度为7
-
为紫色列:从第10列开始,第7行, Span 16列,高度为16
这是我的源代码:
GBC是一个扩展GridBagConstraints的辅助类,使用的构造函数是
GBC(int startingX,int startingY,int width,int height)
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.Rectangle;
import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Demo extends JApplet
{
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
public void init()
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
initComponents();
}
});
}
public void initComponents()
{
//set the layout of the content pane to gridbag layout
GridBagLayout gridBag = new GridBagLayout();
getContentPane().setLayout(gridBag);
Rectangle rect = getContentPane().getBounds();
panel1.setBackground(Color.green);
panel2.setBackground(Color.black);
panel3.setBackground(Color.red);
panel4.setBackground(Color.orange);
panel5.setBackground(Color.yellow);
add(panel4, new GBC(10, 0, 16, 7).setFill(GBC.BOTH).setWeight(1.0, 1.0));
add(panel1, new GBC(0, 0, 10, 1).setFill(GBC.BOTH).setWeight(1.0, 1.0));
add(panel3, new GBC(0, 21, 10, 1).setFill(GBC.BOTH).setWeight(1.0, 1.0));
add(panel2, new GBC(0, 1, 10, 20).setFill(GBC.BOTH).setWeight(1.0, 1.0));
add(panel5, new GBC(10, 7, 16, 16).setFill(GBC.BOTH).setWeight(1.0, 1.0));
}
}
任何帮助将不胜感激(但请解释你的逻辑)
1 回答
那么你可以通过使用
GridBagLayout
轻松完成此任务 .考虑
contentPane
并将GridBagLayout
作为其布局,您现在可以将JPanel
分为三个部分 . 单个左侧JPanel
(带有GridBagLayout,其中包含RED
,BLACK
和BLUE
JPanel
s),右侧包含两个JPanel
,即GREEN
和MAGENTA
.现在左边
JPanel
将RED
,BLACK
和BLUE
JPanel
放在其自身上,GridBagLayout
为Layout Manager
,RED and BLUE
为weighty = 0.1
,BLACK
为weighty = 0.8
请参阅此示例代码:
这是相同的输出: