我想在此代码中仅使用GrigBagLayout创建此设计,而不使用swing和panel。
为了完成我的作业问题,我只是为这个设计准备了代码,但它没有完美的安排。
import java.awt.*;
class GridBagLayout {
public static void main(String args[]) {
Frame f = new Frame();
f.setSize(400,600);
f.setLayout(new GridLayout());
GridBagConstraints gbc = new GridBagConstraints();
Label l = new Label("Name ");
gbc.gridx=1;
gbc.gridy=1;
f.add(l,gbc);
TextField t = new TextField();
gbc.gridx=1;
gbc.gridy=0;
f.add(t,gbc);
Label l2 = new Label("Password ");
gbc.gridx=0;
gbc.gridy=1;
f.add(l2,gbc);
TextField t2 = new TextField();
gbc.gridx=1;
gbc.gridy=1;
f.add(t2,gbc);
Button b = new Button("OK");
gbc.gridx=1;
gbc.gridy=1;
f.add(b,gbc);
f.setVisible(true);
}
}
所以任何人都可以告诉我我的代码缺乏完美安排。
我希望你的作业工作应该基于GridBagLayout
GridBagLayout的
那你为什么要用
f.setLayout(new GridBagLayout);
import java.awt.*;
class GridBagLayout
{
public static void main(String[] args) {
Frame f=new Frame();
f.setSize(300,200);
GridBagLayout gl = new GridBagLayout();
f.setLayout(gl);
GridBagConstraints g=new GridBagConstraints();
g.gridx=0;
g.gridy=0;
f.add(new Label("Name") , g);
g.gridy=1;
f.add(new Label("Password") , g);
g.gridx=1;
g.gridy=0;
f.add(new TextField(15) , g);
g.gridy=1;
g.gridx=1;
f.add(new TextField(15) , g);
g.gridx=0;
g.gridy=2;
g.gridwidth=2;
g.insets = new Insets(30,0,0,0);
f.add(new Button("OK"),g);
f.setVisible(true);
}
}
由于GridBagLayout将容器划分为同等sizwd单元格的网格,并且需要大量信息才能知道放置组件的位置,这就是为什么我使用gridx / y,insets等来正确安排标签和texfields。
[让你的基础知识强大的java awt概念] [1]
[1]:https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html