无法使基本的Java程序计算您的点击次数

时间:2013-11-16 21:07:13

标签: java

为什么这不能正常工作?我似乎无法找到问题 它假设每次单击按钮时将文本显示增加1

public class ClickerGame extends javax.swing.JFrame {

        public ClickerGame() {
            initComponents();
        }

        //declare
        int clicks;
        String clicksout = "" + clicks;

        //Swing GUI netbeans code is here, removed because it is irrelevant

    //click increments number by 1
        private void clickActionPerformed(java.awt.event.ActionEvent evt) {                                      
            clicks++;
            clickercounter.setText(clicksout);
        }                                     

        public static void main(String args[]) {

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

        // Variables declaration - do not modify                     
        private javax.swing.JButton click;
        private javax.swing.JTextField clickercounter;
        // End of variables declaration                   
    }

1 个答案:

答案 0 :(得分:2)

您只需设置clicksout一次:

String clicksout = "" + clicks;

如果clicks更改,则值不会动态重置。如果您从未更改过,那么您将始终获得相同的结果:

clickercounter.setText(clicksout);

请改为尝试:

clickercounter.setText("" + clicks);

您不需要clicksout作为单独的变量。