如何将局部变量的值传递给另一个方法

时间:2018-06-16 08:46:34

标签: java

我有如下的加载功能。

public void loadAppointment(String appointmentName)
    {
        int selectedRow = appointmentJTable.getSelectedRow();
        appointmentsJComboBox.setSelectedItem(tableModel.getValueAt(selectedRow, 0));
        String name = (String) tableModel.getValueAt(selectedRow, 1);
        nameJTextField.setText(name);
        rankJtextField.setText((String) tableModel.getValueAt(selectedRow, 2));
        notesJTextArea.setText((String) tableModel.getValueAt(selectedRow, 3));

        Appointment selectedAppointment = appointmentList.get(name);

        colorJpanel.setBackground(selectedAppointment.getColor());
        loadedData=getValueString();

    }

这里,'selectedAppointment'是一个局部变量。我想从同一个类中的另一个方法使用'selectedAppointment'的值。另一种方法是,

 private void PlaceJButtonActionPerformed(java.awt.event.ActionEvent evt)                                             
    {                                                 
        if (valid())
        {
            String gridReference = appointmentForesightGridSelecter.getGridDisplayString();
            gridReference = gridReference.replaceAll(" ", "");

            if(isLoadedDataChanged)
            {
                **replaceRow(selectedAppointment);**

            }
            createAppointment(gridReference);
            resetPanel();
        }
    }  

由于局部变量只在方法中可见,我可以在'PlaceJButtonActionPerformed()'中使用'selectedAppointment'的值。我是编程新手,如果有人能给我一个解释清楚的答案,那就更好了。

3 个答案:

答案 0 :(得分:1)

更改此

private void PlaceJButtonActionPerformed(java.awt.event.ActionEvent evt)

到这个

private void PlaceJButtonActionPerformed(java.awt.event.ActionEvent evt, Appointment appointment)

并在调用函数时传递该值。任何基础教程都应该向您展示。

答案 1 :(得分:1)

我只想创建一个Appointment类型的全局变量,并使其等于你的局部变量。

`Appointment example;
 public void loadAppointment(String appointmentName)
 {    ...
      Appointment selectedAppointment = appointmentList.get(name);
      example = selectedAppointment;
      ...
 }
 `

然后在您的其他方法中使用该“示例”。

答案 2 :(得分:1)

你有两个解决方案: 1:向'PlaceJButtonActionPerformed'添加一个参数,该参数将作为第二个参数'selectedAppointment' 2:或者将'selectedAppointment'声明为全局变量