我不能在事件方法之外初始化我的对象数组

时间:2015-08-09 20:48:31

标签: java arrays swing

我想制作一个程序,它将创建一个对象数组,用于存储用户点击按钮的次数。 我问用户他们的id号是什么,然后访问他们的数组元素并更新他们的按钮点击。 问题是它不会让我设置 surveyor [0] =新测量员(); surveyor [1] =新测量员();除非我将代码放在我的attemptUpdateActionPerformed方法中,但是我需要在方法之外设置它,这样每次单击按钮时它都不会自动重置。这里有很多额外的东西,但我认为主要问题在于方法。抱歉邋。不错。

package guildquality;


import java.util.Scanner;
public class NewJFrame extends javax.swing.JFrame {

    Surveyors [] surveyor = new Surveyors[10];
    Scanner scan = new Scanner(System.in);
    public int id;

     /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
   surveyor[0] = new Surveyors();
   surveyor[1] = new Surveyors();
    id = 0;

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        attemptUpdate = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        attemptUpdate.setText("Attempt");
        attemptUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                attemptUpdateActionPerformed(evt);
            }
        });

        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(21, 21, 21)
                .addComponent(attemptUpdate)
                .addContainerGap(308, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(173, Short.MAX_VALUE)
                .addComponent(attemptUpdate)
                .addGap(104, 104, 104))
        );

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

    private void attemptUpdateActionPerformed(java.awt.event.ActionEvent evt) {                                              
     System.out.print("what is your id?");
      id = scan.nextInt();
      surveyor[id].setAttempts();
      System.out.print(surveyor[id].getAttempts());
          // TODO add your handling code here:
    }                                             

    /**
     * @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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
            }
        });
    }

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


at sun.awt.Win32GraphicsConfig.getBounds(Native Method)
at sun.awt.Win32GraphicsConfig.getBounds(Win32GraphicsConfig.java:222)
at java.awt.Window.init(Window.java:497)
at java.awt.Window.<init>(Window.java:536)
at java.awt.Frame.<init>(Frame.java:420)
at java.awt.Frame.<init>(Frame.java:385)
at javax.swing.JFrame.<init>(JFrame.java:180)
at guildquality.NewJFrame.<init>(NewJFrame.java:19)
at guildquality.Surveyors.<init>(Surveyors.java:17)
at guildquality.NewJFrame.<init>(NewJFrame.java:20)

2 个答案:

答案 0 :(得分:0)

将它放在main方法中。它将在事件处理程序运行之前运行一次。

答案 1 :(得分:0)

您应该在构造函数中放置一些想要初始化非静态类变量的代码。

例如

public NewJFrame() {
    initComponents();

    // More initialization here.
    surveyor[0] = new Surveyors();
    surveyor[1] = new Surveyors();
}