java中网格包布局代码哪里出错?

来源:百度知道 编辑:UC知道 时间:2024/06/29 01:27:10
package ab;
import javax.swing.*;
import java.awt.*;
public class GridBagLayoutDemo extends JFrame{
private GridBagLayout gbLayout =new GridBagLayout();
private GridBagConstraints constraints=new GridBagConstraints();
private JLabel lbUser,lbPassword;
private JTextField tfUser,tfPassword;
private JButton btnLog;
private Container container;
public GridBagLayoutDemo(){
super("网格包布局");
this.setSize(300,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void setConstraints(GridBagConstraints gbc,int row,int column,int numRows,int numColumns,int Weightx,int Weighty){
gbc.gridx=row;
gbc.gridy=column;
gbc.gridwidth=numRows;
gbc.gridheight=numColumns;
gbc.weightx=Weightx;
gbc.weighty=Weighty;
}
public void setLyaout(){
container=this.getContentPane();
container.setLayout(gbLayout);
//添加用户名标签
con

写的时候仔细点,setLyaout方法里面有错
lbUser=new JLabel("用户名");
gbLayout.setConstraints(tfUser,constraints);
container.add(tfUser);

你这里把 lbUser 指向了对象,此是的tfUser还没有,而你加的时候确是加的tfUser, 你把 tfUser改过来就好了

import javax.swing.*;
import java.awt.*;

public class GridBagLayoutDemo extends JFrame {
private GridBagLayout gbLayout = new GridBagLayout();

private GridBagConstraints constraints = new GridBagConstraints();

private JLabel lbUser, lbPassword;

private JTextField tfUser, tfPassword;

private JButton btnLog;

private Container container;

public GridBagLayoutDemo() {
super("网格包布局");
this.setSize(300, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

private void setConstraints(GridBagConstraints gbc, int row, int column,
int numRows, int numColumns, int Weightx, int Weighty) {
gbc.gridx = row