简体   繁体   English

当我尝试从getter获取数据时,为什么会出现NullPointerException?

[英]Why am I getting a NullPointerException when I try to get data from a getter?

EDIT: ok here is my full code since you guys are asking for it : 编辑:好的,这是我的完整代码,因为你们要求它:

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

public class Panel extends JPanel {

private JTextField username_field;
private JTextField skype_field;
private JTextField raidcall_field;
private JTextField teamspeak_field;
private JComboBox server_combobox;
private JComboBox levels_combobox;
private JComboBox mytier_combobox;
private JComboBox mydiv_combobox;
private JComboBox partner_tier_combobox;
private JComboBox partner_div_combobox;
private JComboBox myrole_combobox;
private JComboBox partner_role_combobox;
private JRadioButton normal,ranked;
private String region;
private String tier;
private String division;
private String skype;
private String raidcall;
private String teamspeak;
private String partner_role;
private int mode;

public Panel(AppUI.Panels panel){

    String star = "<span style='color:#ff0000;'>*</span>";

    switch (panel) {

        case NORTHPANEL :
            setBackground(Color.getHSBColor(20,20,20));
            JLabel title = new JLabel();
            title.setText("<html>fields marked with " + star + " are required to be filled.</html>");
            title.setFont(new Font("Tahoma", Font.BOLD, 10));
            add(title);

            break;

        case CENTERPANEL :

            setLayout(new GridBagLayout());
            setBackground(Color.LIGHT_GRAY);
            username_field = new JTextField(10);
            username_field.setToolTipText("Enter your Summoner name here");

            String[] servers = { "NA", "EUW", "EUNE", "TR", "BR", "LAN", "LAS", "RU", "OCE" };
            server_combobox = new JComboBox<String>(servers);
            server_combobox.setToolTipText("Select the region your account is in");

            String[] levels = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"
                    ,"17","18","19","20","21","22","23","24","25","26","27","28","29","30"};
            levels_combobox = new JComboBox<String>(levels);
            levels_combobox.setToolTipText("Select the level your summoner is");

            addItem(this, new JLabel("<html>Summoner name :" + star + "</html>") , 0, 0, 1, 1);
            addItem(this, username_field ,1,0,1,1);
            addItem(this, new JLabel("<html>Summoner level :" + star + "</html>"), 0,1,1,1);
            addItem(this, levels_combobox, 1,1,1,1);
            addItem(this, new JLabel("<html>Server :" + star + " </html>"), 0,2,1,1);
            addItem(this, server_combobox, 1, 2, 1, 1);

            break;

        case SOUTHPANEL :

            JLabel require = new JLabel();
            JLabel require1 = new JLabel();
            JLabel require2 = new JLabel();


            setLayout(new GridBagLayout());
            setBackground(Color.getHSBColor(20,20,20));
            ButtonGroup bg = new ButtonGroup();
            normal = new JRadioButton("Normal game");
            ranked = new JRadioButton("Solo/Duo Ranked game");
            bg.add(normal);
            bg.add(ranked);

            Box queue = Box.createHorizontalBox();
            queue.add(new JLabel("<html>I want to play a :" + star + "</html>"));
            queue.add(Box.createHorizontalStrut(5));
            queue.add(normal);
            queue.add(ranked);

            String[] tiers = {"Bronze", "Silver" , "Gold", "Platinum", "Diamond"};
            String[] divs = {"I", "II", "III", "IV", "V"};

            mytier_combobox = new JComboBox<>(tiers);
            mydiv_combobox = new JComboBox<>(divs);

            Box myRank = Box.createHorizontalBox();
            myRank.add(new JLabel("<html>My Solo Queue rank is : "));
            myRank.add(require);
            myRank.add(Box.createHorizontalStrut(15));
            myRank.add(mytier_combobox);
            myRank.add(Box.createHorizontalStrut(15));
            myRank.add(mydiv_combobox);

            String[] myroles = {"Jungler", "Top laner", "Mid laner", "ADC", "Support"};
            String[] partner_roles = {"Jungler", "Top laner", "Mid laner", "ADC", "Support"};

            myrole_combobox = new JComboBox<>(myroles);
            partner_role_combobox = new JComboBox<>(partner_roles);

            Box roles = Box.createHorizontalBox();
            roles.add(new JLabel("I am a "));
            roles.add(Box.createHorizontalStrut(5));
            roles.add(myrole_combobox);
            roles.add(Box.createHorizontalStrut(5));
            roles.add(new JLabel("<html>" + star + " Looking for a </html>"));
            roles.add(Box.createHorizontalStrut(5));
            roles.add(partner_role_combobox);
            roles.add(require1);

            partner_tier_combobox = new JComboBox<>(tiers);
            partner_div_combobox = new JComboBox<>(divs);

            Box partner_min_rank = Box.createHorizontalBox();
            partner_min_rank.add(new JLabel("Looking for a partner with a minimum rank of "));
            partner_min_rank.add(require2);
            partner_min_rank.add(Box.createHorizontalStrut(5));
            partner_min_rank.add(partner_tier_combobox);
            partner_min_rank.add(Box.createHorizontalStrut(5));
            partner_min_rank.add(partner_div_combobox);

            JButton button = new JButton("Results");
            button.addActionListener(e -> {
                System.out.println("[TEST] Your summoner level is : " + getLevel());
            });
            addItem(this, queue, 0, 0, 1, 1);
            addItem(this, myRank , 0, 1, 1, 1);
            addItem(this, roles, 0, 2, 1, 1);
            addItem(this, partner_min_rank, 0, 3, 1, 1);
            addItem(this, button, 0, 4, 1,1);

            ranked.addActionListener(e -> {
                if (ranked.isSelected()){

                    require.setText("<html>"+ star + "</html>");
                    require1.setText("<html>" + star + "</html>");
                    require2.setText("<html>"+ star + "</html>");
                }
            });

            normal.addActionListener(e -> {
                if (normal.isSelected()){

                    require.setText("");
                    require1.setText("");
                    require2.setText("");
                }
            });

            break;

        case EASTPANEL :

            setLayout(new GridBagLayout());

            skype_field = new JTextField(5);
            raidcall_field = new JTextField(5);
            teamspeak_field = new JTextField(5);

            Box skype= Box.createHorizontalBox();
            skype.add(new JLabel(" Username :"));
            skype.add(Box.createHorizontalStrut(5));
            skype.add(skype_field);
            skype.setBorder(BorderFactory.createTitledBorder("Skype"));

            Box raidcall = Box.createHorizontalBox();
            raidcall.add(new JLabel("Username :"));
            raidcall.add(Box.createHorizontalStrut(5));
            raidcall.add(raidcall_field);
            raidcall.setBorder(BorderFactory.createTitledBorder("Raidcall"));

            Box teamspeak = Box.createHorizontalBox();
            teamspeak.add(new JLabel("Username :"));
            teamspeak.add(Box.createHorizontalStrut(5));
            teamspeak.add(teamspeak_field);
            teamspeak.setBorder(BorderFactory.createTitledBorder("Teamspeak"));

            addItem(this, skype, 0, 0, 1, 1);
            addItem(this, raidcall, 0, 1, 1, 1);
            addItem(this, teamspeak, 0, 2, 1, 1);
            break;

        default :
            System.out.println("Panel not found!");
    }

}

public String getSummonerName(){

    return username_field.getText();
}

public int getLevel(){

    return this.levels_combobox.getSelectedIndex() + 1;
}

public String getTier() {

    switch (mytier_combobox.getSelectedIndex()) {
        case 0 :
            tier = "Bronze";
            break;
        case 1 :
            tier = "Silver";
            break;
        case 2 :
            tier = "Gold";
            break;
        case 3 :
            tier = "Platinum";
            break;
        case 4 :
            tier = "Diamond";
            break;

        default :
            System.out.println("Tier not found!");

    }

    return tier;
}

public String getDivision(){

    switch (mydiv_combobox.getSelectedIndex()){
        case 0 :
            division = "I";
            break;
        case 1 :
            division = "II";
            break;
        case 2 :
            division = "III";
            break;
        case 3 :
            division = "IV";
            break;
        case 4 :
            division = "V";
            break;

        default :
            System.out.println("Division not found!");
    }

    return division;
}

public String getRegion(){

    switch (server_combobox.getSelectedIndex()) {
        case 0 :
            region = "North America";
            break;
        case 1 :
            region = "Europe West";
            break;
        case 2 :
            region = "Europe Nordic & East";
            break;
        case 3 :
            region = "Turkey";
            break;
        case 4 :
            region = "Brazil";
            break;
        case 5 :
            region = "Latin America North";
            break;
        case 6 :
            region = "Latin America South";
            break;
        case 7 :
            region = "Russia";
            break;
        case 8 :
            region = "Oceania";
            break;

        default :
            System.out.println("Region not found!");
    }

    return region;
}

public int getGameMode(){

    if (normal.isSelected()){

        mode = 0;

    } else {

        mode = 1;

    }

    return mode;
}

public String getSkype() {

    if (skype_field.getText().isEmpty())
        skype = "Not specified";
    else
        skype = skype_field.getText();

    return skype;
}

public String getRaidcall(){

    if (raidcall_field.getText().isEmpty())
        raidcall = "Not specified";
    else
        raidcall = raidcall_field.getText();

    return raidcall;

}

public String getTeamspeak(){

    if (teamspeak_field.getText().isEmpty())
        teamspeak = "Not specified";
    else
        teamspeak = teamspeak_field.getText();

    return teamspeak;
}

public String getMyRole(){

    String myrole = "";

    switch (myrole_combobox.getSelectedIndex()){

        case 0 :
            myrole = "Jungler";
            break;
        case 1 :
            myrole = "Top laner";
            break;
        case 2 :
            myrole = "Mid laner";
            break;
        case 3 :
            myrole = "ADC";
            break;
        case 4 :
            myrole = "Support";
            break;
        default :
            System.out.println("Role not found!");

    }

    return myrole;
}

public String getPartnerRole(){
    switch (partner_role_combobox.getSelectedIndex()){

        case 0 :
            partner_role = "Jungler";
            break;
        case 1 :
            partner_role = "Top laner";
            break;
        case 2 :
            partner_role = "Mid laner";
            break;
        case 3 :
            partner_role = "ADC";
            break;
        case 4 :
            partner_role = "Support";
            break;
        default :
            System.out.println("Role not found!");
    }

    return partner_role;
}

public String getPartnerMinTier(){
    String tier = "";

    switch(partner_tier_combobox.getSelectedIndex()){
        case 0 :
            tier = "Bronze";
            break;
        case 1 :
            tier = "Silver";
            break;
        case 2 :
            tier = "Gold";
            break;
        case 3 :
            tier = "Platinum";
            break;
        case 4 :
            tier = "Diamond";
            break;
        default :

            System.out.println("Tier not found!");
    }

    return tier;
}

public String getPartnerMinDiv(){
    String div = "";

    switch (partner_div_combobox.getSelectedIndex()){
        case 0 :
            div = "I";
            break;
        case 1 :
            div = "II";
            break;
        case 2 :
            div = "III";
            break;
        case 3 :
            div = "IV";
            break;
        case 4 :
            div = "V";
            break;
        default :
            System.out.println("Division not found!");
    }

    return div;
}

public void addItem(JPanel p, JComponent c, int x, int y, int width, int height){

    GridBagConstraints gc = new GridBagConstraints();
    gc.gridx = x;
    gc.gridy = y;
    gc.gridwidth = width;
    gc.gridheight = height;
    gc.insets = new Insets(5,5,5,5);
    gc.fill = GridBagConstraints.NONE;
    p.add(c, gc);
}

} }

Well I have this getter : 好吧,我有这个吸气剂:

public int getLevel(){
    return levels_combobox.getSelectedIndex() + 1;
}

This is my variable levels_combobox : 这是我的变量levels_combobox:

private JComboBox levels_combobox;

and yes it is instantiated in a method : 是的,它在一个方法中实例化:

String[] levels = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"
                    ,"17","18","19","20","21","22","23","24","25","26","27","28","29","30"};
levels_combobox = new JComboBox<String>(levels);

Why am I getting a NullPointerException, when I try to test the output with this : 当我尝试使用以下方法测试输出时,为什么会出现NullPointerException:

System.out.println("[TEST] Your summoner level is : " + getLevel());

You're initializing the JComboBox inside the case block of a switch statement, one with no guarantee of being called before the offending method is called. 您正在初始化switch语句的case块内的JComboBox,在调用有问题的方法之前无法保证被调用。

Solution: you've got a bad code design, and so you must fix it. 解决方案:您的代码设计很糟糕,因此您必须修复它。 Initialize all critical components in the constructor and not dependent on a switch/case block. 初始化构造函数中的所有关键组件,而不依赖于switch / case块。

I'm not really sure why you've got such a switch statement in the constructor as it looks odd and dangerous, and I suggest you consider re-designing your constructor so that this isn't even needed. 我不确定为什么你在构造函数中有这样的switch语句,因为它看起来很奇怪和危险,我建议你考虑重新设计你的构造函数,这样就不需要了。 Perhaps you really want to instead create a factory of some sort. 也许你真的想要创建某种工厂。


Edit 编辑
Your Panel code is trying to do too much and is disobeying the Single responsibility principle , 您的Panel代码试图做太多,并且不遵守Single责任原则

that every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. 每个班级都应该承担一项责任,而且责任应该完全由班级封装。 All its services should be narrowly aligned with that responsibility. 其所有服务应与该责任严格一致。

As an aside, I would re-name the Panel class so that the name doesn't clash with the core Java class of the same name, the java.awt.Panel class. 顺便说一下,我会重新命名Panel类,以便该名称不会与同名的核心Java类java.awt.Panel类冲突。 If you fix this, your switch/case statement will no longer be needed, and your error will likely go away. 如果您解决了这个问题,将不再需要您的switch / case语句,并且您的错误可能会消失。


As a second aside, I'll bet that you're using an enum that looks like this: 作为第二个,我敢打赌你使用的枚举看起来像这样:

class AppUI {
   enum Panels {
      NORTHPANEL, CENTERPANEL, SOUTHPANEL, EASTPANEL
   }
}

You're not assigning levels_combobox unless you passed CENTERPANEL. 除非你通过了CENTERPANEL,否则你不会指定levels_combobox。 You should give it some default value at the beginning of the constructor. 您应该在构造函数的开头给它一些默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试保存图像时为什么会出现NullPointerException? - Why am i getting NullPointerException when i try to save image? 当我尝试在Studio中切换活动时,为什么会收到java.lang.NullPointerException错误? - Why am I getting a java.lang.NullPointerException error when I try to switch activities in studio? 尝试在Android中打开对话框时,为什么会出现NullPointerException? - Why am I getting NullPointerException when I try to open a dialog in Android? 尝试运行JFrame时为什么会出现NullPointerException? - Why am I getting a NullPointerException when I try to run my JFrame? 当我尝试使用 BufferedReader 读取输入时,为什么会出现 NullPointerException? - Why am I getting a NullPointerException when I try to read input using BufferedReader? 为什么从 Futures 获取值时会收到 NullPointerException? - Why am I getting a NullPointerException when fetching values from Futures? 当我尝试从Jframe中的表中获取字符串时,为什么会出现错误? - Why am I getting an error when I try to get a string from my table in a Jframe? 为什么我在尝试读取 excel 文件时收到数据提供程序不匹配错误? - Why I am getting Data Provider MisMatch error when I try to read from excel file? 为什么我得到nullPointerException - why am I getting nullPointerException 为什么我没有收到NullPointerException - Why am I NOT getting a NullPointerException
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM