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

时间:2014-04-27 18:35:02

标签: java swing nullpointerexception

编辑:好的,这是我的完整代码,因为你们要求它:

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);
}

}

嗯,我有这个吸气剂:

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

这是我的变量levels_combobox:

private JComboBox levels_combobox;

是的,它在方法中实例化:

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);

当我尝试用这个测试输出时,为什么会出现NullPointerException:

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

2 个答案:

答案 0 :(得分:2)

你正在switch语句的case块中初始化JComboBox,不能保证在调用有问题的方法之前调用它。

解决方案:您的代码设计很糟糕,因此您必须修复它。初始化构造函数中的所有关键组件,而不依赖于switch / case块。

我不确定你为什么在构造函数中有这样的switch语句,因为它看起来很奇怪和危险,我建议你考虑重新设计你的构造函数,这样就不需要了。也许你真的想要创建某种工厂。


修改
您的Panel代码试图做太多而且不遵守Single responsibility principle

  

每个班级都应该承担一项责任,并且该责任应该由班级完全封装。它的所有服务都应该与这一责任保持一致。

顺便说一句,我会重新命名Panel类,以便该名称不会与同名的核心Java类java.awt.Panel类冲突。如果你解决这个问题,将不再需要你的switch / case语句,你的错误可能会消失。


作为第二个,我敢打赌你正在使用看起来像这样的枚举:

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

答案 1 :(得分:0)

除非您通过了CENTERPANEL,否则您不会指定levels_combobox。你应该在构造函数的开头给它一些默认值。