如何创建一个可用于在Java GUI中存储整数数据的变量

时间:2015-10-16 11:28:02

标签: java swing

我是使用java语言编程的新手。所以我要求你帮助我的项目。我有一个名为“Color Blitz!”的游戏。游戏的机制是点击标签中随机化的正确颜色。点击每个正确的颜色将增加1分,但我的代码似乎只停留在1点,它不再添加..任何想法?这是我的代码:

package jHighlow;


import java.util.Random;

public class JavaHighlow extends javax.swing.JFrame {

    public JavaHighlow() {
        initComponents();
    }

    int scoreadd;

    final String [] colorList = {
        "Red!",
        "Blue!",
        "Green!",
        "Yellow!",
        "White!",
        "Black!",
        "Violet!",
        "Pink!"};
    int [] colorval = new int[]{0,1,2,3,4,5,6,7};

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

        jPanel1 = new javax.swing.JPanel();
        btnRed = new javax.swing.JButton();
        btnBlue = new javax.swing.JButton();
        btnGreen = new javax.swing.JButton();
        btnYellow = new javax.swing.JButton();
        btnWhite = new javax.swing.JButton();
        btnBlack = new javax.swing.JButton();
        btnViolet = new javax.swing.JButton();
        btnPink = new javax.swing.JButton();
        btnStart = new javax.swing.JButton();
        coloutlab1 = new javax.swing.JLabel();
        Color1 = new javax.swing.JLabel();
        Scorelbl = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Color Blitz!");

        btnRed.setBackground(new java.awt.Color(255, 0, 0));
        btnRed.setText("Red");
        btnRed.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRedActionPerformed(evt);
            }
        });

        btnBlue.setBackground(new java.awt.Color(0, 0, 255));
        btnBlue.setText("Blue");
        btnBlue.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBlueActionPerformed(evt);
            }
        });

        btnGreen.setBackground(new java.awt.Color(51, 255, 51));
        btnGreen.setText("Green");
        btnGreen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGreenActionPerformed(evt);
            }
        });

        btnYellow.setBackground(new java.awt.Color(255, 255, 0));
        btnYellow.setText("Yellow");
        btnYellow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnYellowActionPerformed(evt);
            }
        });

        btnWhite.setBackground(new java.awt.Color(255, 255, 255));
        btnWhite.setText("White");
        btnWhite.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnWhiteActionPerformed(evt);
            }
        });

        btnBlack.setBackground(new java.awt.Color(0, 0, 0));
        btnBlack.setForeground(new java.awt.Color(255, 255, 255));
        btnBlack.setText("Black");
        btnBlack.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBlackActionPerformed(evt);
            }
        });

        btnViolet.setBackground(new java.awt.Color(204, 0, 204));
        btnViolet.setForeground(new java.awt.Color(255, 255, 255));
        btnViolet.setText("Violet");
        btnViolet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVioletActionPerformed(evt);
            }
        });

        btnPink.setBackground(new java.awt.Color(255, 204, 204));
        btnPink.setText("Pink");
        btnPink.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPinkActionPerformed(evt);
            }
        });

        btnStart.setText("Start GAME!");
        btnStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStartActionPerformed(evt);
            }
        });

        coloutlab1.setText("Press Start GAME!  to Start COLOR BLITZ!");

        Color1.setText("START");

        Scorelbl.setText("0");

        jLabel1.setText("Score!");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(btnBlue, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnRed, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnGreen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnYellow, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(btnViolet, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnBlack, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnWhite, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE)
                            .addComponent(btnPink, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(60, 60, 60)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(coloutlab1)
                            .addComponent(btnStart))
                        .addGap(18, 18, 18)
                        .addComponent(Color1)
                        .addGap(68, 68, 68)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(Scorelbl)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(0, 8, Short.MAX_VALUE)))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnRed, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnWhite, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnBlack, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnBlue, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnGreen, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnViolet, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnPink, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnYellow, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(coloutlab1)
                        .addComponent(Color1)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Scorelbl)
                    .addComponent(btnStart))
                .addContainerGap(25, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(74, 74, 74)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(55, Short.MAX_VALUE))
        );

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


    public void scoreadd(){
        int add = 1;

        int b =0;
    int finalsc= 0+add;
    for(int i=0;i<b;i++){
        finalsc=b+1;
        i++;

    }
    Scorelbl.setText(String.valueOf(finalsc));

    }
    private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {                                         

        Roll();
    }                                        

    public void Roll() {
        // TODO add your handling code here:

        coloutlab1.setText("The color is:");
        int index = new Random().nextInt(colorList.length);
        Color1.setText(colorList[index]);
        btnStart.setVisible(false);
    }

    private void btnPinkActionPerformed(java.awt.event.ActionEvent evt) {                                        
        String pink;
        pink = Color1.getText();
       if(pink.equals("Pink!")){
           scoreadd();
          Roll();

       } else{
        Roll();}
    }                                       

    private void btnVioletActionPerformed(java.awt.event.ActionEvent evt) {                                          
        String vio;
        vio = Color1.getText();
       if(vio.equals("Violet!")){
           scoreadd();
           Roll();
       } 
       else{
        Roll();}
    }                                         

    private void btnBlackActionPerformed(java.awt.event.ActionEvent evt) {                                         
       String black;
        black = Color1.getText();
       if(black.equals("Black!")){

            scoreadd();
      Roll();
       } else{
        Roll();}
    }                                        

    private void btnWhiteActionPerformed(java.awt.event.ActionEvent evt) {                                         
       String white;
        white = Color1.getText();
       if(white.equals("White!")){

            scoreadd();
         Roll();
       } 
       else{Roll();}
    }                                        

    private void btnYellowActionPerformed(java.awt.event.ActionEvent evt) {                                          
       String yell;
        yell = Color1.getText();
       if(yell.equals("Yellow!")){

           scoreadd();
         Roll();
       } 
       else{Roll();}
    }                                         

    private void btnGreenActionPerformed(java.awt.event.ActionEvent evt) {                                         
        String green;
        green = Color1.getText();
       if(green.equals("Green!")){

           scoreadd();    
           Roll();
       } 
       else{ Roll();}
    }                                        

    private void btnRedActionPerformed(java.awt.event.ActionEvent evt) {                                       
       String red;
        red = Color1.getText();
       if(red.equals("Red!")){
        scoreadd();
            Roll();
       } 

       else{  Roll();}
    }                                      

    private void btnBlueActionPerformed(java.awt.event.ActionEvent evt) {                                        
       String blue;
        blue = Color1.getText();
       if(blue.equals("Blue!")){
           scoreadd();
          Roll();
       } 
       else{
        Roll();}
    }                                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        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(JavaHighlow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JavaHighlow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JavaHighlow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JavaHighlow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JavaHighlow().setVisible(true);

            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel Color1;
    private javax.swing.JLabel Scorelbl;
    private javax.swing.JButton btnBlack;
    private javax.swing.JButton btnBlue;
    private javax.swing.JButton btnGreen;
    private javax.swing.JButton btnPink;
    private javax.swing.JButton btnRed;
    private javax.swing.JButton btnStart;
    private javax.swing.JButton btnViolet;
    private javax.swing.JButton btnWhite;
    private javax.swing.JButton btnYellow;
    private javax.swing.JLabel coloutlab1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   
}

3 个答案:

答案 0 :(得分:1)

您应该用此替换scoreadd方法:

public void scoreadd(){
    Scorelbl.setText(String.valueOf(++scoreadd));
}

属性scoreadd已存在。 ++scoreadd操作将其值增加1.然后,更新标签。

答案 1 :(得分:0)

在你的scoreadd方法中,你将 finalsc 的值始终设为0,然后加1.你需要有一个保存finalsc的实例变量,然后才能正确求和

private int finalsc = 0;

public void scoreadd(){
    int add = 1;

    int b =0;
    fininalsc=+add;
for(int i=0;i<b;i++){
    finalsc=b+1;
    i++;

}
Scorelbl.setText(String.valueOf(finalsc));
}

不确定scoreadd方法的逻辑。循环没有任何意义。但是,你需要一个实例变量

答案 2 :(得分:0)

这是问题所在:

public void scoreadd(){
    int add = 1;

    int b =0;
int finalsc= 0+add;
for(int i=0;i<b;i++){
    finalsc=b+1;
    i++;

}
Scorelbl.setText(String.valueOf(finalsc));

finalsc将以0 + 1开始(这是'add''评估的值。 然后我们通过循环并将finalsc的值设置为等于b + 1。 b总是从0开始。无论你经历多少次循环,它仍然是0 + 1.

关于您的代码的几个总体评论;  1.使用类来分离逻辑(单独的用户界面逻辑与实际的游戏机制)  2.要保持风格一致,例如'scoreadd'应该是'scoreAdd'  3.想一想。通过循环使用循环将1添加到变量中可以用简单的乘法替换。没有理由让事情复杂化  4.在向这样的论坛发布问题时,请尝试将示例包含在其基本要素中  5.调试你的代码

亲切的问候, 里斯