gpt4 book ai didi

java - 在 GridBagLayout 中调用 SetContraints 时出现 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 23:06:01 25 4
gpt4 key购买 nike

在正在创建的JDialog内部,我尝试将字段添加到GUI,但它返回时带有NullPointerException,示例如下:

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


public class Login extends JDialog{

//Constants
private final int WIDTH = 240;
private final int HEIGHT = 180;

//Attributes
private JPasswordField passwordField;
private JButton login;
private JLabel instruction;
private GridBagLayout aLayout;
GridBagConstraints aConstraint;

public Login(){
setTitle("Login Dialog");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

aConstraint = new GridBagConstraints();
int padding = 5;

instruction = new JLabel("Enter password: ");

passwordField = new JPasswordField();
passwordField.setPreferredSize(new Dimension(100, 20));
passwordField.setMinimumSize(new Dimension(100, 20));

login = new JButton("Login");

//Adding widgets to the GUI
addWidget(instruction, 1, 1, 1, 1);
addWidget(passwordField, 1, 1, 1, 1);
addWidget(login, 1, 2, 1, 1);


//Setting padding
aConstraint.insets = new Insets(padding, padding, padding, padding);
//Creating layout
aLayout = new GridBagLayout();
setLayout(aLayout);

//Making sure visibility is true.
setVisible(true);
}
public void addWidget(Component widget, int x, int y, int w, int h)
{
aConstraint.gridx = x;
aConstraint.gridy = y;
aConstraint.gridwidth = w;
aConstraint.gridheight = h;
aLayout.setConstraints(widget, aConstraint);
add(widget); // Calling method of super class.
}
}

这是我收到的错误:

Exception in thread "main" java.lang.NullPointerException
at Login.addWidget(Login.java:57)
at Login.<init>(Login.java:37)

我使用 JFrame 创建了一个类似的类,但没有遇到此问题。

最佳答案

aLayout = new GridBagLayout();

此初始化发生在从构造函数调用 addWidget() 方法之后,留下 aLayout null ,因此出现 NullPointerException

aLayout = new GridBagLayout();

在从构造函数调用addWidget()之前

关于java - 在 GridBagLayout 中调用 SetContraints 时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22739486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com