大家好,本人java初学者。
在做一个GUI界面的时候使用了GridBagLayout布局,代码如下。
我的理解是gridx 和gridy是将组件设置在 某一行某一列 上,所以我用不同的数值尝试性修改两个button的位置,但是不管怎么设置其位置都没有变化。
那么GridBagLayout中一行一列到底有几个单元格?gridxgridy 应该怎么用?
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class LoginPanel extends JFrame implements MouseListener{
public JLabel lb1,lb2,lb3;
public JTextField tf1;
public JPasswordField pw1;
public JPanel p1;
public JButton b1,b2;
public LoginPanel(){
lb1=new JLabel("请输入用户名:");
lb2=new JLabel("请输入密码:");
lb3=new JLabel(" ");
tf1=new JTextField (15);
pw1=new JPasswordField (15);
p1=new JPanel();
b1=new JButton("确定");
b2=new JButton("重置");
this.setSize(600,600);
p1.setBackground(Color.yellow);
GridBagLayout playout=new GridBagLayout();
GridBagConstraints s= new GridBagConstraints();
s.gridwidth=2;
s.weightx = 0;
s.weighty=0;
playout.setConstraints(lb1, s);
s.gridwidth=0;
s.weightx = 0;
s.weighty=0;
playout.setConstraints(tf1, s);
s.insets=new Insets(20,0,0,0);
s.gridwidth=2;
s.weightx = 0;
s.weighty=0;
playout.setConstraints(lb2, s);
s.gridwidth=0;
s.weightx = 0;
s.weighty=0;
playout.setConstraints(pw1, s);
/*********这里的gridxgridy似乎没有生效********************/
s.gridx=3;
s.gridy=8;
s.gridwidth=1;
s.weightx = 0;
s.weighty=0;
playout.setConstraints(b1, s);
s.gridx=6;
s.gridy=8;
s.gridwidth=0;
s.weightx = 0;
s.weighty=0;
playout.setConstraints(b2, s);
/*****************************/
this.setLayout(playout);
this.getContentPane().setBackground(Color.gray);
lb1.setPreferredSize(new Dimension(100,30));
lb2.setPreferredSize(new Dimension(100,30));
tf1.setPreferredSize(new Dimension(100,30));
pw1.setPreferredSize(new Dimension(100,30));
//this.setLayout(new BorderLayout());
add(lb1);
add(tf1);
add(lb2);
add(pw1);
add(b1);
add(b2);
//this.pack();
setVisible(true);
}
public static void main( String [] args){
new LoginPanel();
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
欢迎选择我的课程,让我们一起见证您的进步~~