写的时候仔细点,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;
gbc.gridy = column;
gbc.gridwidth = numRows;
gbc.gridheight = numColumns;
gbc.weightx = Weightx;
gbc.weighty = Weighty;
}
public void setLyaout() {
container = this.getContentPane();
container.setLayout(gbLayout);
// 添加用户名标签
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.CENTER;
setConstraints(constraints, 0, 0, 1, 1, 0, 0);
lbUser = new JLabel("用户名");
gbLayout.setConstraints(lbUser, constraints);
container.add(lbUser);
// 添加用户名文本框
constraints.fill = GridBagConstraints.HORIZONTAL;
setConstraints(constraints, 1, 0, 1, 1, 100, 100);
tfUser = new JTextField();
gbLayout.setConstraints(tfUser, constraints);
container.add(tfUser);
// 添加密码标签
constraints.fill = GridBagConstraints.NONE;
setConstraints(constraints, 0, 1, 1, 1, 0, 0);
lbPassword = new JLabel("密码");
gbLayout.setConstraints(lbPassword, constraints);
container.add(lbPassword);
// 添加密码文本框
constraints.fill = GridBagConstraints.HORIZONTAL;
setConstraints(constraints, 1, 1, 1, 1, 100, 100);
tfPassword = new JTextField();
gbLayout.setConstraints(tfPassword, constraints);
container.add(tfPassword);
// 添加登录按钮
constraints.fill = GridBagConstraints.CENTER;
setConstraints(constraints, 0, 2, 2, 1, 0, 0);
btnLog = new JButton("登录");
gbLayout.setConstraints(btnLog, constraints);
container.add(btnLog);
}
public static void main(String[] args) {
GridBagLayoutDemo frame = new GridBagLayoutDemo();
frame.setLyaout();
frame.show();
}
}
之前有人做过用Table来实现一个表单的效果,其中也有跨多行和多列,是用纯java代码实现的,没有使用XML。用网格布局GridView也可以实现
共有6中布局
FlowLayout(流式布局) Panel的默认布局
BorderLayout(边界布局)window的默认布局 Frame和Dialog
GridLayo(网格布局)
CardLayout(卡片布局)
BoxLayout(盒式布局)
null布局GridLayo(网格布局)
java学习交流群 194252842 137104136 你可以加一下
售后响应及时
7×24小时客服热线数据备份
更安全、更高效、更稳定价格公道精准
项目经理精准报价不弄虚作假合作无风险
重合同讲信誉,无效全额退款