简体   繁体   中英

How to pass values of local variables to another method

I have load function as below.

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();

    }

Here, 'selectedAppointment ' is a local variable. I want to use the value of 'selectedAppointment ' from another method in same class. The other method is,

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

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

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

As local variables are visible only within the method can I use the value of' selectedAppointment' in 'PlaceJButtonActionPerformed()'. I am new to programming and it is better if anyone can give me a well explained answer.

Change this

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

to this

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

and pass the value when calling functions. Any basic tutorial should show you this.

I would just make a global variable of type Appointment and make it equal to your local variable.

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

Then use that "example" in your other method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM