简体   繁体   English

Java变量不会更改JLabel的文本(NullPointerException),但会显示在JOptionDialog框中吗?

[英]Java Variable won't change text of JLabel (NullPointerException), but shows up in JOptionDialog box?

I'm trying to do a coin counter for a Vending Machine simulator, and I am trying to put the number of coins into a JLabel. 我正在尝试为自动售货机模拟器做一个硬币计数器,并且试图将硬币数量放入JLabel中。 I'm relatively new to Java, but i've got different JLabels in other classes to change; 我是Java的新手,但是在其他类别中我有不同的JLabel可以更改。 however this one seems to just refuse to change! 但是,这似乎只是拒绝更改! The strange thing is that the correct value shows up in the JOptionPane message, but doesn't change the JLabel. 奇怪的是,正确的值显示在JOptionPane消息中,但不会更改JLabel。 This would surely mean that the correct value from the other class is being used. 这肯定意味着正在使用其他类的正确值。 (The coins200Lbl is public - if that makes any difference). (coins200Lbl是公开的,如果有区别的话)。

(Ignore the countless unnamed variables, I thought i'd try and make one work first before naming the rest properly :) ) (忽略无数的未命名变量,我想我会先尝试做一个工作,然后再正确命名其余的:))

May be a stupid mistake that i've missed, but i've been trying to figure it out for days with no success. 可能是我错过的一个愚蠢的错误,但是我已经尝试了好几天,但都没有成功。

Thanks in advance! 提前致谢!

package vendingmachine;

import javax.swing.*;

public class adminMenu extends javax.swing.JFrame {
int coins;
int[] coinCount;

public adminMenu() {
    initComponents();

}
public adminMenu(int[] c) {
    coinCount = c;
    int amount200p = coinCount[7]/200;
    JOptionPane.showMessageDialog(null, amount200p);
    coin200.setText("£2: " + Integer.toString(amount200p) + " coins");
}



public int calcCoins() {
    return coins; 
}


@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jLabel6 = new javax.swing.JLabel();
    jLabel8 = new javax.swing.JLabel();
    jLabel13 = new javax.swing.JLabel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    fundsLbl = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();
    jLabel5 = new javax.swing.JLabel();
    jLabel7 = new javax.swing.JLabel();
    jLabel9 = new javax.swing.JLabel();
    jLabel10 = new javax.swing.JLabel();
    jLabel11 = new javax.swing.JLabel();
    homeBtn = new javax.swing.JButton();
    coin200 = new javax.swing.JLabel();

    jLabel6.setText("£2:");

    jLabel8.setText("£2:");

    jLabel13.setText("0");

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jButton1.setText("Withdraw Funds");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jButton2.setText("Insert Funds");

    fundsLbl.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    fundsLbl.setText("Current funds:");

    jLabel3.setText("£1:");

    jLabel4.setText("50p:");

    jLabel5.setText("20p:");

    jLabel7.setText("10p:");

    jLabel9.setText("5p:");

    jLabel10.setText("2p:");

    jLabel11.setText("1p:");

    homeBtn.setText("Home");
    homeBtn.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            homeBtnActionPerformed(evt);
        }
    });

    coin200.setText("£2:");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(22, 22, 22)
            .addComponent(fundsLbl)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(44, 44, 44)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jLabel3)
                        .addComponent(jLabel4)
                        .addComponent(jLabel5))
                    .addGap(112, 112, 112))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(coin200, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(27, 27, 27)))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel7)
                .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(jLabel10, javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(jLabel11, javax.swing.GroupLayout.Alignment.TRAILING))
            .addContainerGap(137, Short.MAX_VALUE))
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jButton2)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(homeBtn)
            .addGap(81, 81, 81))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel7)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel9)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel10)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel11)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(fundsLbl)
                        .addComponent(coin200))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel3)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel4)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel5)
                    .addGap(18, 18, 18)))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton1)
                .addComponent(jButton2)
                .addComponent(homeBtn))
            .addContainerGap())
    );

    pack();
}// </editor-fold>                        


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
}                                        

private void homeBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
    this.setVisible(false);
    new VendingMachineGUI().setVisible(true);
}                                       

public static void main(String args[]) {
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(adminMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(adminMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(adminMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(adminMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new adminMenu().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
public javax.swing.JLabel coin200;
private javax.swing.JLabel fundsLbl;
private javax.swing.JButton homeBtn;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
// End of variables declaration                   

} }

The NullPointerException is: NullPointerException是:

run:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at vendingmachine.adminMenu.<init>(adminMenu.java:17)
at vendingmachine.VendingMachineGUI.adminBtnActionPerformed(VendingMachineGUI.java:551)
at vendingmachine.VendingMachineGUI.access$1800(VendingMachineGUI.java:5)
at vendingmachine.VendingMachineGUI$19.actionPerformed(VendingMachineGUI.java:213)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6525)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6290)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4881)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:751)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:702)
at java.awt.EventQueue$3.run(EventQueue.java:696)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:724)
at java.awt.EventQueue$4.run(EventQueue.java:722)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:721)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

BUILD SUCCESSFUL (total time: 11 seconds) ` 建立成功(总时间:11秒)`

Okay James, the real problem is the JLabel coin200 is not initialized, but you'd attempted to call the setText() method of the JLabel. 好的,詹姆斯,真正的问题是JLabel coin200没有初始化,但是您试图调用JLabel的setText()方法。 So you are attempting to call the setText() method of nothing ( null ). 因此,您尝试不调用setText()方法( null )。 The solution is, call the initComponents() method at the beginning of the addMenu(int [] c) method. 解决方法是,在addMenu(int [] c)方法的开头调用initComponents() addMenu(int [] c)方法。 Just like this 像这样

public adminMenu(int[] c) {

    initComponents();
    coinCount = c;
    int amount200p = coinCount[7]/200;
    JOptionPane.showMessageDialog(null, amount200p);
    coin200.setText("£2: " + Integer.toString(amount200p) + " coins");
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM