当文件存在时,JButton.setIcon会抛出空指针

时间:2014-06-24 04:35:52

标签: java swing nullpointerexception embedded-resource getresource

好的,所以我遇到了一个问题,我的图像在运行.jar文件时没有显示。

修正了使用强盗的修复方法,我认为他的标签是。

无论如何,一旦我通过从getResourceAsStream等获取图像来解决这个问题,它就可以了。因此,在创建背景图像时,带有图像的JLabel和带有图像作为新组件的JButton,这非常有用!

我现在遇到的问题是我有3个按钮需要在某些情况下更改其图标。我已对此进行了测试,但在我的测试类中没有NullPointerException,但是当我在我的项目课程中尝试此操作时,每次尝试NullPointerException时都会得到setIcon

这是我设置的更改图标的方法。 (我已经尝试了很多不同的方式,并且认为这是最容易看到的,因为无论我做什么都会发生。)这里是构造函数,createGUI以及更改方法的方法图标。请帮我弄清楚我做错了什么。

public class Addons {
// Setup any variables needed for this class to run
private JPanel addonsList;
private JLabel patchNotes;
private JProgressBar progressBar;
private JTable addonsTable;
private SaveSettings sav;
private Updater util;
private JButton instructions;
private JButton installButton;
private JButton finishedButton;
private boolean finishedAll;
private boolean upAvail;
private Task task;

// Setup the tables for use in the listings

    /**
*   Default constructor
*
*/
public Addons(Updater util) {
    // Load up the saved settings.
    sav = new SaveSettings();
    sav.loadSave();
    this.util = util;
    finishedAll = false;
    upAvail = false;
    createAddonsGUI();
}

/**
*   This method will create the gui for use in the constructor
*
*/
private void createAddonsGUI() {
    // create base panel
    addonsList = new JPanel();
    addonsList.setPreferredSize(new Dimension(800,435));
    addonsList.setOpaque(false);
    SpringLayout addonsListLO = new SpringLayout();
    addonsList.setLayout(addonsListLO);

    // Create and place scroll frame with patch notes panel in it.
    JScrollPane patchNotesPanel = createPatchNotesPanel();
    patchNotesPanel.setPreferredSize(new Dimension(370,300));
    addonsList.add(patchNotesPanel);

    // create and place progress bar
    //JLabel progressBarBackground = new JLabel(new ImageIcon(util.PROGBACK_IMAGE_PATH));
    JLabel progressBarBackground = new JLabel();
    try {           
        Image mypBarPic = ImageIO.read(getClass().getClassLoader().getResourceAsStream("com/dynastyaddons/updater/ProgressBackground.png"));
        progressBarBackground = new JLabel(new ImageIcon(mypBarPic));
    } catch (IOException ignore) {
        System.out.println("Error: " + ignore.getMessage());
    }
    addonsList.add(progressBarBackground);
    SpringLayout pBarLO = new SpringLayout();
    progressBarBackground.setLayout(pBarLO);
    progressBarBackground.setOpaque(false);
    progressBar = new JProgressBar(0, 100);
    progressBar.setValue(0);
    progressBar.setStringPainted(true);
    progressBarBackground.add(progressBar);
    pBarLO.putConstraint(SpringLayout.WEST, progressBar, 21, SpringLayout.WEST, progressBarBackground);
    pBarLO.putConstraint(SpringLayout.NORTH, progressBar, 15, SpringLayout.NORTH, progressBarBackground);
    pBarLO.putConstraint(SpringLayout.EAST, progressBar, -21, SpringLayout.EAST, progressBarBackground);
    pBarLO.putConstraint(SpringLayout.SOUTH, progressBar, -45, SpringLayout.SOUTH, progressBarBackground);

    // Create and place Finish button
    //finishedButton = new JButton(new ImageIcon(util.FINOFF_IMAGE_PATH));
    //public static final String FINOFF_IMAGE_PATH = "F:\\Java Programs\\Updater\\src\\com\\dynastyaddons\\updater\\images\\FinishedOff.png";
    JButton finishedButton = new JButton();
    try {           
        Image myfinishedButtonPic = ImageIO.read(getClass().getClassLoader().getResourceAsStream("com/dynastyaddons/updater/FinishedOff.png"));
        finishedButton = new JButton(new ImageIcon(myfinishedButtonPic));
    } catch (IOException ignore) {
        System.out.println("Error: " + ignore.getMessage());
    }
    finishedButton.setBorderPainted(false);
    finishedButton.setContentAreaFilled(false);
    finishedButton.setFocusPainted(false);
    finishedButton.setOpaque(false);
    finishedButton.setToolTipText("<html><font size=6>When button glows blue, you're all done and you can press this to close the udpater.</font></html>");
    finishedButton.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) { if(finishedAll) {System.exit(0);} }
    });
    addonsList.add(finishedButton);

    // Create and place Install Addons Button
    //installButton = new JButton(new ImageIcon(util.INSTOFF_IMAGE_PATH));
    //public static final String INSTOFF_IMAGE_PATH = "F:\\Java Programs\\Updater\\src\\com\\dynastyaddons\\updater\\images\\InstallUpdatesOFF.png";
    JButton installButton = new JButton();
    try {           
        Image myinstallButtonPic = ImageIO.read(getClass().getClassLoader().getResourceAsStream("com/dynastyaddons/updater/InstallUpdatesOFF.png"));
        installButton = new JButton(new ImageIcon(myinstallButtonPic));
    } catch (IOException ignore) {
        System.out.println("Error: " + ignore.getMessage());
    }
    installButton.setBorderPainted(false);
    installButton.setContentAreaFilled(false);
    installButton.setFocusPainted(false);
    installButton.setOpaque(false);
    installButton.setToolTipText("<html><center><font size=6>When arrows to the left of this button glow blue, you have updates to install.<br /> <br />Press this button to get the updated versions of your addons.</font></center></html>");
    installButton.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) { 
            // This will handle installing needed updates
            if(upAvail) { 
                JFrame root = util.getRootFrame();
                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                task = new Task();
                task.execute();
                root.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
            }
        }
    });
    addonsList.add(installButton);

    // Create and place scroll frame with the addons list table in it.
    JPanel addonListPanel = new JPanel();
    addonListPanel.setPreferredSize(new Dimension(388,245));
    addonsTable = new JTable(new DynastyTableModel());
    JTableHeader header = addonsTable.getTableHeader();
    ColumnHeaderToolTips tips = new ColumnHeaderToolTips();
    header.addMouseMotionListener(tips);
    addonListPanel.setLayout(new BorderLayout());
    addonListPanel.add(addonsTable.getTableHeader(), BorderLayout.PAGE_START);
    addonListPanel.add(new JScrollPane(addonsTable), BorderLayout.CENTER);
    // setup table settings
    addonsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    addonsTable.setRowSelectionAllowed(true);
    addonsTable.setColumnSelectionAllowed(false);
    addonsTable.setBackground(Color.BLACK);
    addonsTable.setForeground(Color.WHITE);
    //addonsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    addonsTable.setFillsViewportHeight(true);
    addonsTable.setPreferredScrollableViewportSize(addonListPanel.getPreferredSize());
    addonsTable.setRowHeight(31);
    // setup column width and editing
    fitToContentWidth(addonsTable, 0);
    fitToContentWidth(addonsTable, 1);
    fitToContentWidth(addonsTable, 2);
    fitToContentWidth(addonsTable, 3);
    fitToContentWidth(addonsTable, 4);
    // properly align text in cells
    DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
    centerRenderer.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
    addonsTable.getColumn("Version").setCellRenderer( centerRenderer );
    //addonsTable.getColumn("Purchase").setCellRenderer( centerRenderer );
    addonsTable.getColumn("Size").setCellRenderer( centerRenderer );
    //addonsTable.getColumn("Update").setCellRenderer( centerRenderer );
    addonsTable.getColumn("Name").setCellRenderer( centerRenderer );
    // setup list selector
    ListSelectionModel listSelectionModel = addonsTable.getSelectionModel();
    listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());
    addonsTable.setSelectionModel(listSelectionModel);

    addonListPanel.setOpaque(false);
    addonsList.add(addonListPanel);

    // Create and place the view instructions button.
    //instructions = new JButton(new ImageIcon(util.INSTRUCTIONS_BUTTON));
    //public static final String INSTRUCTIONS_BUTTON = "F:\\Java Programs\\Updater\\src\\com\\dynastyaddons\\updater\\images\\instructions.png";
    JButton instructions = new JButton();
    try {           
        Image myinstructionsPic = ImageIO.read(getClass().getClassLoader().getResourceAsStream("com/dynastyaddons/updater/instructions.png"));
        instructions = new JButton(new ImageIcon(myinstructionsPic));
    } catch (IOException ignore) {
        System.out.println("Error: " + ignore.getMessage());
    }
    instructions.setBorderPainted(false);
    instructions.setContentAreaFilled(false);
    instructions.setFocusPainted(false);
    instructions.setOpaque(false);
    instructions.setToolTipText("<html><center><font size=6>When this button shows purchase you can click it to go purchase the selected addon.<br /><br /> When it's showing Instructions you can click it to go see the manual for the selected addon.</font></center></html>");
    // Deal with nothing selected when clciking this.
    instructions.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            int row = addonsTable.getSelectedRow();
            String ad = "";             
            DynastyTableModel tm = (DynastyTableModel) addonsTable.getModel();
            if ( row == -1 ) { return; }
            if ( row == 1 || row == 0 || row == 2 ) { ad = "Booster"; }
            else {  
                ad = (String) tm.getValueAt(row,1);
                ad = ad.replaceAll("\\s+", "");
            }
            boolean purchased = (Boolean) tm.getValueAt(row,3);
            if (purchased) {
                sendTo(ad, 1);
            } else {
                sendTo(ad,0);
            }
        }
    });
    addonsList.add(instructions);

    // Constrain all items to the base panel
    addonsListLO.putConstraint(SpringLayout.EAST, patchNotesPanel, -18, SpringLayout.EAST, addonsList);
    addonsListLO.putConstraint(SpringLayout.NORTH, patchNotesPanel, 0, SpringLayout.NORTH, addonsList);
    addonsListLO.putConstraint(SpringLayout.SOUTH, progressBarBackground, -20, SpringLayout.SOUTH, addonsList);
    addonsListLO.putConstraint(SpringLayout.WEST, progressBarBackground, 100, SpringLayout.WEST, addonsList);
    addonsListLO.putConstraint(SpringLayout.EAST, finishedButton, 0, SpringLayout.EAST, addonsList);
    addonsListLO.putConstraint(SpringLayout.SOUTH, finishedButton, -20, SpringLayout.SOUTH, addonsList);
    addonsListLO.putConstraint(SpringLayout.SOUTH, installButton, -10, SpringLayout.NORTH, progressBarBackground);
    addonsListLO.putConstraint(SpringLayout.WEST, installButton, 190, SpringLayout.WEST, addonsList);
    addonsListLO.putConstraint(SpringLayout.WEST, addonListPanel, 18, SpringLayout.WEST, addonsList);
    addonsListLO.putConstraint(SpringLayout.NORTH, addonListPanel, 0, SpringLayout.NORTH, addonsList);
    addonsListLO.putConstraint(SpringLayout.NORTH, instructions, -180, SpringLayout.SOUTH, addonsList);
    addonsListLO.putConstraint(SpringLayout.WEST, instructions, 20, SpringLayout.WEST, addonsList);

}


/**
*   This will update the table with info from the users database entry.
*
*/
public void updateTable() {
    String totalIn = "";
    String s = "";
    String aName = "";
    String aVersion = "";
    String aFileSize = "";
    String aInfo = "";          
    DynastyTableModel tm = (DynastyTableModel) addonsTable.getModel();
    sav.loadSave();
    try {
        URL serverURL = new URL(Updater.URL_CONNECT + "action=get_addons&email=" + sav.getSetting("UserName") + "&PHPSESSID=" + util.getPHPSessionID());
        HttpURLConnection serverConnection = (HttpURLConnection) serverURL.openConnection();
        serverConnection.setRequestMethod("GET");
        BufferedReader in = new BufferedReader(new InputStreamReader(serverConnection.getInputStream()));
        while (( totalIn = in.readLine()) != null) {
            s += totalIn;
        }
        String[] splitOne = s.split("\\|-\\|");
        for ( int a = 0; a < splitOne.length; a++) {
            String[] splitTwo = splitOne[a].split("\\|");
            String addonName = splitTwo[0];
            for ( int b = 0; b < tm.getRowCount(); b++) {
                if ( addonName.equals( (String) tm.getValueAt(b,1) ) ) { // b is the correct place to place the table info into addons[][]
                    tm.setValueAt(splitTwo[1],b,2);
                    tm.setValueAt(true,b,3);
                    double byteSize = Double.parseDouble(splitTwo[2]);
                    double kbyteSize = (byteSize/1024.0);
                    DecimalFormat dec = new DecimalFormat("00.00");
                    tm.setValueAt(dec.format(kbyteSize),b,4);
                    pNotes[b][0] = splitTwo[3];
                }
            }
        }
    } catch (MalformedURLException e) {
        JOptionPane.showMessageDialog(null, "Please send this entire error to support@dyanstyaddons.com. Also you can close the updater and re-open it and that sometimes removes this issue.\n Error # 22", "Attention!",JOptionPane.ERROR_MESSAGE);           
    } catch (IOException e) {
        JOptionPane.showMessageDialog(null, "Please send this entire error to support@dynastyaddons.com. Also you can close the updater and re-open it and that sometimes removes this issue.\n Error # 23" + e.getMessage(), "Attention!",JOptionPane.ERROR_MESSAGE);      
    }
    checkLocalAddons();
}

/**
*   This method checks the version numbers to see what what needs updating
*   then updates the table to reflect this.
*
*/
private void needsUpdate() {
    DynastyTableModel tm = (DynastyTableModel)addonsTable.getModel();
    for ( int a = 0; a < tm.getRowCount(); a++) {
        String ver = (String) tm.getValueAt(a,2).toString();
        if(!ver.equals(localVersion[a][0])) { 
            boolean purch = (boolean) tm.getValueAt(a,3);
            System.out.println("Set value at " + a + " 0 to: " + purch);
            if(purch) {tm.setValueAt(true,a,0);}
        }else{
            tm.setValueAt(false,a,0);
        }
    }
    checkUpdatesAvail();
}

/**
*   This method will check if any of the udpate boxes are checked, and update the install button.
*
*
*/
private void checkUpdatesAvail() {
    DynastyTableModel tm = (DynastyTableModel) addonsTable.getModel();
    boolean update = false;
    for ( int a = 0; a < tm.getRowCount(); a++) {
        boolean u = (Boolean) tm.getValueAt(a,0);
        if (u) { update = u; }
    }
    if (update) {           
        setImageOnButton("instOn");
        upAvail = true;
    } else { finishedEverything(); }
}

/**
*   This method handles what happens when you click the Install Updates button.
*
*/
private void updateNeededAddons() {

    DynastyTableModel tm = (DynastyTableModel) addonsTable.getModel();
    boolean[] addUp = {false,false,false,false,false,false,false};
    for (int a = 0; a < tm.getRowCount(); a++) {
        boolean update = (Boolean) tm.getValueAt(a,0);
        int getResult = 2;
        if (update) {
            addUp[a] = true;
            try {

                URL dlAddon = new URL(util.URL_CONNECT + "action=download&addon=" + tm.getValueAt(a,1) + "&email=" + sav.getSetting("UserName") + "&PHPSESSID=" + util.getPHPSessionID());      
                String fileName = tm.getValueAt(a,1) + ".zip";
                String fileS = (String) tm.getValueAt(a,4);
                double fileSize = Double.parseDouble(fileS);
                getResult = getAddons(dlAddon, fileName, fileSize);
            } catch(MalformedURLException e) {
                JOptionPane.showMessageDialog(null, "We tried to create a query to download your addons, but got a malformedURLException. Please send this entire error to support@dyanstyaddons.com. Also you can close the updater and re-open it and that sometimes removes this issue.\n Error # 31", "Attention!",JOptionPane.ERROR_MESSAGE);      

            }
            if(getResult == 1) { 
                installAddon((String)tm.getValueAt(a,1)); 
            }
        }
    }
}

/**
*   This method will update the patch notes panel, 
*   it only allows updating from within this class.
*
*   @param txt      The new txt for the patch notes panel.
*
*/
private void setPatchNotes(String txt) {
    patchNotes.setText(txt);
    int prefSize = 370;
    boolean width = true;
    View view = (View) patchNotes.getClientProperty(javax.swing.plaf.basic.BasicHTML.propertyKey);
    view.setSize(width ? prefSize : 0, width ? 0 : prefSize);
    float w = view.getPreferredSpan(View.X_AXIS);
    float h = view.getPreferredSpan(View.Y_AXIS);
    patchNotes.setPreferredSize(new Dimension((int) Math.ceil(w) - 17, (int) Math.ceil(h) + 100));
}

/**
*   This will query the server for the updates to the addons
*   that are needed and download them as needed.
*
*/
private int getAddons(URL url, String localFilename, double len) {
    InputStream is = null;
    FileOutputStream fos = null;

    try {
        URLConnection urlConn = url.openConnection();
        HttpURLConnection resp = (HttpURLConnection) urlConn;
        int responseCode = resp.getResponseCode();
        is = urlConn.getInputStream();
        fos = new FileOutputStream(System.getenv("SystemDrive") + "\\DynastyAddons\\" + localFilename);

        byte[] buffer = new byte[4096];
        int leng = (int) len;

        while ((leng = is.read(buffer)) > 0) {
            fos.write(buffer,0,leng);
        }
        is.close();
        fos.close();
        return 1;
    } catch (MalformedURLException e) {
        JOptionPane.showMessageDialog(null, "We tried to download your addons, but got a malformedURLException. Please send this entire error to support@dyanstyaddons.com. Also you can close the updater and re-open it and that sometimes removes this issue.\n Error # 32", "Attention!",JOptionPane.ERROR_MESSAGE);            
        return 2;
    } catch (IOException e) {
        JOptionPane.showMessageDialog(null, "We tried to download your addons, but got an IOException. Please send this entire error to support@dynastyaddons.com. Also you can close the updater and re-open it and that sometimes removes this issue.\n Error # 33" + e, "Attention!",JOptionPane.ERROR_MESSAGE);         
        return 2;
    }
}



/**
*   This will update the finished button once all is done.
*
*/
private void finishedEverything() { 

        setImageOnButton("instOff");
        setImageOnButton("finOn");
        upAvail = false;
        finishedAll = true;

}

    public void setImageOnButton(String buttonName){
    ImageIcon icon;
    switch(buttonName) {
        case "purchase":    try {
                                System.out.println("Trying to setIcon on Instructions Button. File: com/dynastyaddons/updater/Purchase.png exists? " + new File("com/dynastyaddons/updater/Purchase.png").exists());
                                Image pic1 = ImageIO.read(Addons.class.getClassLoader().getResourceAsStream("com/dynastyaddons/updater/Purchase.png"));
                                icon = new ImageIcon(pic1);
                                instructions.setIcon(icon);
                            } catch (IOException e) { System.out.println("IO Exception setting icon to instructions: " + e.getMessage()); }
                            break;
        case "instructions":try {
                                System.out.println("Trying to setIcon on Instructions Button. File: com/dynastyaddons/updater/instructions.png exists? " + new File("com/dynastyaddons/updater/instructions.png").exists());
                                Image pic2 = ImageIO.read(Addons.class.getClassLoader().getResourceAsStream("com/dynastyaddons/updater/instructions.png"));
                                icon = new ImageIcon(pic2);
                                instructions.setIcon(icon);
                            } catch (IOException e) { System.out.println("IO Exception setting icon to instructions2: " + e.getMessage()); }
                            break;
        case "finOn":       try {
                                System.out.println("Trying to setIcon on Instructions Button. File: com/dynastyaddons/updater/FinishedOn.png exists? " + new File("com/dynastyaddons/updater/FinishedOn.png").exists());
                                Image pic3 = ImageIO.read(Addons.class.getClassLoader().getResourceAsStream("com/dynastyaddons/updater/FinishedOn.png"));   
                                icon = new ImageIcon(pic3);
                                finishedButton.setIcon(icon);                               
                            } catch (IOException e) { System.out.println("IO Exception setting icon to finished: " + e.getMessage()); }
                            break;
        case "finOff":      try {
                                System.out.println("Trying to setIcon on Instructions Button. File: com/dynastyaddons/updater/FinishedOff.png exists? " + new File("com/dynastyaddons/updater/FinishedOff.png").exists());
                                Image pic4 = ImageIO.read(Addons.class.getClassLoader().getResourceAsStream("com/dynastyaddons/updater/FinishedOff.png"));
                                icon = new ImageIcon(pic4);
                                finishedButton.setIcon(icon);
                            } catch (IOException e) { System.out.println("IO Exception setting icon to finished2: " + e.getMessage()); }
                            break;
        case "instOn":      try {
                                System.out.println("Trying to setIcon on Instructions Button. File: com/dynastyaddons/updater/InstallUpdatesON.png exists? " + new File("com/dynastyaddons/updater/InstallUpdatesON.png").exists());
                                Image pic5 = ImageIO.read(Addons.class.getClassLoader().getResourceAsStream("com/dynastyaddons/updater/InstallUpdatesON.png"));
                                icon = new ImageIcon(pic5);
                                installButton.setIcon(icon);
                            } catch (IOException e) { System.out.println("IO Exception setting icon to install: " + e.getMessage()); }
                            break;
        case "instOff":     try {
                                System.out.println("Trying to setIcon on Instructions Button. File: com/dynastyaddons/updater/InstallUpdatesOFF.png exists? " + new File("com/dynastyaddons/updater/InstallUpdatesOFF.png").exists());
                                Image pic6 = ImageIO.read(Addons.class.getClassLoader().getResourceAsStream("com/dynastyaddons/updater/InstallUpdatesOFF.png"));
                                icon = new ImageIcon(pic6);
                                installButton.setIcon(icon);
                            } catch (IOException e) { System.out.println("IO Exception setting icon to install2: " + e.getMessage()); }
                            break;
    }
}


// This internal class will handle the modle for the table used to show the addon list.
class DynastyTableModel extends AbstractTableModel {
    private String[] columnNames = {"Update",
                                    "Name",
                                    "Version",
                                    "Purchase",
                                    "Size"};
    private Object[][] initialData = {
        {new Boolean(false), "Booster", new Double(1.0), new Boolean(false), new Double(0)},
        {new Boolean(false), "BoosterAlliance", new Double(1.0), new Boolean(false), new Double(0)},
        {new Boolean(false), "BoosterHorde", new Double(1.0), new Boolean(false), new Double(0)},
        {new Boolean(false), "Edge", new Double(1.0), new Boolean(false), new Double(0)},
        {new Boolean(false), "Impulse", new Double(1.0), new Boolean(false), new Double(0)},
        {new Boolean(false), "Tycoon", new Double(1.0), new Boolean(false), new Double(0)},
        {new Boolean(false), "DynastyCore", new Double(1.0), new Boolean(false), new Double(0)},
    };

    public int getColumnCount() { return columnNames.length; }
    public int getRowCount() { return initialData.length; }
    public String getColumnName(int col) { return columnNames[col]; }
    public Object getValueAt(int row, int col) { return initialData[row][col]; }
    public Class getColumnClass(int c) { return getValueAt(0,c).getClass(); }
    @Override
    public void setValueAt(Object value, int row, int col) {
        initialData[row][col] = value;
        fireTableCellUpdated(row, col);
    }
}

// This internal class will help handle when a row is selected in the table. 
class SharedListSelectionHandler implements ListSelectionListener {
    public void valueChanged(ListSelectionEvent e) {
        if ( !e.getValueIsAdjusting() ) {
            ListSelectionModel lsm = (ListSelectionModel)e.getSource();
            int selected = lsm.getMinSelectionIndex();
            // if purchased addon display patch notes
            DynastyTableModel tm = (DynastyTableModel) addonsTable.getModel();
            boolean selectedValue = (Boolean) tm.getValueAt(selected,3);
            if ( selectedValue ) { 
                setPatchNotes(pNotes[selected][0]); 
                setImageOnButton("instructions");
            }
            else { // Otherwise update Install Instructions button to show Purchase instead. 
                // save currently selected addon name for use in the purchase button?
                String p = "";
                if (selected == 1 || selected == 2) {
                    p = "Booster";
                } else { p = (String) tm.getValueAt(selected,1); }
                setPatchNotes("<HTML>You have not purchased this addon, please go to http://dynastyaddons.com/" + p + " or click the Purchase button below the list of addons here to open the purchase page.</HTML>"); 
                setImageOnButton("purchase");

            }
        }
    }
}
}

从上面的代码中可以看出,使用createGUI等创建按钮的getResource()工作正常,它是底部的setImagesOnButton()方法&#39 ; s给我适合。

我还尝试包含调用方法的位置,以使其更清晰。此外,println中的setImagesOnButton打印出文件已找到并存在,然后在下一行中NullPointerException出现,说它不会存在?让我感到困惑。

1 个答案:

答案 0 :(得分:0)

好的,我弄明白发生了什么事。解决这个问题的三件事。首先,我意识到null问题不是我试图放在按钮上的图标,而是在CreateGUI方法的顶部错误放置了JButton调用。我删除了(因为我已经在构造函数中创建了它)并且它消失了。其次,我摆脱了愚蠢的方法,因为它让我感到困惑。 (setImageOnButton)最后我发现,如果我将images目录放在包的根目录中,那么使用新的ImageIcon(Image.read(getClass()。getClassLoader()。getResourceAsStream(&#34; images)调用图像/imagename.png")));我可以找到它,因为我把它与包而不是课程相关联,它就像一个魅力!我编辑,震撼了它,并在我的妻子身上进行了测试。电脑,它工作得很完美!谢谢大家的帮助,没有所有好消息就无法完成!至少可以说,我完全理解资源以及如何将它们放入应用程序并立即使用它们。 :)