我想仅使用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);
}
}
所以任何人都可以告诉我有关我的代码缺少哪些地方,以使其完美地排列。
答案 0 :(得分:0)
我希望您的分配工作应基于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将容器划分为等大小单元格的网格,因此需要大量信息才能知道将容器放置在何处 这就是为什么我使用gridx / y,insets等正确的组件 标签和texfield的排列。
[使您的Java awt概念的基础知识更强] [1]
[1]: https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html