从java中的另一个类访问类中的变量

时间:2017-05-18 09:26:27

标签: java

我正在尝试从Class02类访问Class01类中的值。我整晚都在看书,但我无法让它上​​班。任何帮助将不胜感激。如果这看起来像一个愚蠢的问题,我很抱歉,但我对java完全不熟悉。谢谢: - )

public class Class01 
{
    private JFrame frame;

    private RecordValue recAction = new RecordValue();

    private JButton btnAdd;
    private JButton btnEdit;

    //  Launch the application
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Class01 window = new Class01();
                    window.frame.setVisible(true);
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //  Create the application
    public Class01() {
        initialize();
    }

    //  Initialize the contents of the frame
    private void initialize()
    {       
        frame = new JFrame();
        frame.getContentPane().setBackground(new Color(255, 228, 196));
        frame.setBounds(100, 100, 197, 89);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        btnAdd = new JButton("Add");
        btnAdd.setBounds(25, 11, 60, 23);
        frame.getContentPane().add(btnAdd);

        btnEdit = new JButton("Edit");
        btnEdit.setBounds(95, 11, 60, 23);
        frame.getContentPane().add(btnEdit);

        btnAdd.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) 
            {
                recAction.setRecordValue(0);    // 0 = New, 1 = Edit                
                Class02 ar = new Class02(recAction);
                ar.recordForm();
            }
        }); 

        btnEdit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) 
            {
                recAction.setRecordValue(1);    // 0 = New, 1 = Edit                
                Class02 er = new Class02(recAction);
                er.recordForm();
            }
        });
    }   

    public int getNewEditAction() 
    {
        System.out.println("getNewEditAction = " + this.recAction.getRecordValue());
        return this.recAction.getRecordValue();
    }       
}
//*************************************************************************************************
public class Class02{

    private JFrame frame;

    RecordValue _recordValue;
    Class01 c01 = new Class01();

    //  Launch the application
    public void recordForm() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {                   
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //  Create the application
    public Class02(RecordValue recordValue) 
    {
        _recordValue = recordValue;
        initialize();
    }

    //  Initialize contents of frame
    private void initialize() 
    {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(100, 100, 230, 95);
        frame.getContentPane().setLayout(null);

        JButton btnShowAction = new JButton("Show Action Value");
        btnShowAction.setFont(new Font("Tahoma", Font.BOLD, 12));
        btnShowAction.setBounds(28, 11, 163, 23);
        frame.getContentPane().add(btnShowAction);

        btnShowAction.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                System.out.println("Rec Value = " + _recordValue);

            }
        });     
    }
}
//*************************************************************************************************
public class RecordValue 
{   
    public int _recordValue = 0;

    public int getRecordValue()
    {
        return _recordValue;
    }

    public void setRecordValue(int val)
    {
        _recordValue = val;
    }
}

1 个答案:

答案 0 :(得分:1)

为什么不起作用? 您的代码存在一些问题,但是它无法正常工作的主要原因是因为范围。除非将变量标记为 static ,否则它是包含在其中的类的成员,这意味着每个类都有自己的变量版本。可以把它想象成一支简单的笔 - 笔内的墨水是笔的一部分,没有两支笔共享墨水。如果用一支笔书写,它不会影响另一支笔中的墨水量。

如何使其发挥作用 有一种简单但不正确的方法来解决这个问题,以及一种稍微复杂但正确的方法:

  • 简单:将 neweditAction 设为静态,以便 HealthTracker 的所有实例共享相同的变量实例,类似于共享相同墨迹的所有笔。
  • 正确:创建另一个包含值的类,并通过类更改值。将类的实例传递给需要它的人。

我不打算向你展示简单的解决方案,因为a)它是微不足道的,而b)从编程的角度解决你的问题是错误的方法。我逐字复制了所有代码并注释掉了我没有其余代码的部分,然后进行了更改以向您显示正确的解决方案。我专注于修复你在这里描述的问题而忽略了我看到的其他问题:

public class RecordValue {
    private int _recordValue = 0;

    public int getRecordValue(){
        return _recordValue;
    }

    public void setRecordValue(int val){
        _recordValue = val;
    }
}

public class HealthTracker {
    private JFrame frame;
    private JButton btnNew;
    private JLabel lblHealthTrackerSystem;
    private JButton btnSearch;

    public JTable tblMain;
    // use an object type so we can pass it around and change the value(s)
    private RecordValue newEditAction = new RecordValue();
    //private int neweditAction;  // 0 = New, 1 = Edit
    public String servId;

    //  Public items
    //StoredProcedures sp = new StoredProcedures();
    String[] inputFlds = new String[3];
    private JButton btnDelete;

    //  Launch the application
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try{
                    HealthTracker window = new HealthTracker();
                    window.frame.setVisible(true);
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    //  Create the application
    public HealthTracker() 
    {
        initialize();
    }

    //  Initialize the contents of the frame
    private void initialize()
    {
        btnNew = new JButton("Add New Record");
        btnNew.setFont(new Font("Tahoma", Font.BOLD, 11));
        btnNew.setBounds(306, 276, 125, 23);
        frame.getContentPane().add(btnNew);

        JButton btnUpdate = new JButton("Update Record");
        btnUpdate.setFont(new Font("Tahoma", Font.BOLD, 11));
        btnUpdate.setBounds(576, 276, 125, 23);
        frame.getContentPane().add(btnUpdate);      

        //  Add a New Record Button        
        btnNew.addActionListener( new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                newEditAction.setRecordValue(0);// = 0; // 0 = New, 1 = Edit

                // WE ALREADY HAVE ONE. DON'T MAKE ANOTHER ONE.
                NewEditRecord nr = new NewEditRecord(newEditAction);
                nr.recordForm();
            }
        });


        //  Update a Record Button
        btnUpdate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                servId = JOptionPane.showInputDialog(frame, "Which ServiceID Record You Want to Update?");
                newEditAction.setRecordValue(1);// = 1; // 0 = New, 1 = Edit 

                NewEditRecord ur = new NewEditRecord(newEditAction);
                ur.recordForm();
            }
        });
    }

    public int getNewEditAction() 
    {
        System.out.println("getNewEditAction = " + this.newEditAction.getRecordValue());
        return this.newEditAction.getRecordValue();
    }
}

public class NewEditRecord {
    private JFrame frame;

    // we don't need an entire tracker to do anything in here
    //HealthTracker ht = new HealthTracker();
    RecordValue _recordValue;
    //int recAction = ht.getNewEditAction();

    //  Launch the application
    // there is no reason for this to be static
    public /*static*/ void recordForm() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {                   
                    // don't make ANOTHER instance, we're in one already!!!!!!
                    //NewEditRecord window = new NewEditRecord();
                    /*window.*/frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //  Create the application
    public NewEditRecord(RecordValue recordValue) {
        _recordValue = recordValue;
        initialize();
    }

    //  Initialize contents of frame
    private void initialize() {
//        frame = new JFrame();
//        frame.setBounds(100, 100, 706, 390);
//        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//        frame.getContentPane().setLayout(null);
//
//        txtInstitution = new JTextField();
//        txtInstitution.setBounds(100, 47, 540, 20);
//        lblInstitution.setLabelFor(txtInstitution);
//        frame.getContentPane().add(txtInstitution);
//        txtInstitution.setColumns(10);
//
//        //  If Updating, Load Fields w/Record Data      
//        if (recAction == 1){
//            String qry = "SELECT ServiceID, Institution, Doctor, CONCAT(Street,', ',City, ', ', State, ' ', ZipCode) AS Address, Date, Cost"
//                        + ", Caption AS ServiceType, Comments FROM Services s INNER JOIN ServiceTypes st ON s.ServiceTypeID = st.ServiceTypeID"
//                        + " WHERE (ServiceID = '"+ recServID + "')";
//
//            try{
//                Connection dbconn = StoredProcedures.dbConn();
//                Statement stmt = dbconn.createStatement();
//                ResultSet rs = stmt.executeQuery(qry);
//
//                while (rs != null && rs.next()){
//                    txtInstitution.setText(rs.getString("ServiceID"));
//                }   
//            }
//            catch (Exception e){
//                e.printStackTrace();
//            }           
//        }
//
//        //  Close Form
//        btnCancel.addActionListener(new ActionListener(){
//            public void actionPerformed(ActionEvent e){
//                frame.dispose();
//            }
//        });
    }
}

我们将一个对象的单个实例传递给每个 NewEditRecord HealthTracker 中包含的整数值(对于每个实例都是不同的)。 >。这意味着所有 NewEditRecord 对象都指向相同的 RecordValue 对象,因此如果其中一个 NewEditRecord 对象更改 RecordValue的值它将反映在其他 NewEditRecord 对象中,因为它们必须转到 RecordValue 并从那里获取整数。