![](/img/trans.png)
[英]How to pass values of variables that I got from one method, To another method
[英]How to pass values of local variables to another method
我有加載功能如下。
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'的值。 我是編程新手,如果有人能給我一個解釋清楚的答案,那就更好了。
改變這個
private void PlaceJButtonActionPerformed(java.awt.event.ActionEvent evt)
對此
private void PlaceJButtonActionPerformed(java.awt.event.ActionEvent evt, Appointment appointment)
並在調用函數時傳遞該值。 任何基礎教程都應該向您展示。
我只是創建一個類型為Appointment的全局變量,並使其等於您的局部變量。
`Appointment example;
public void loadAppointment(String appointmentName)
{ ...
Appointment selectedAppointment = appointmentList.get(name);
example = selectedAppointment;
...
}
`
然后在您的其他方法中使用該“示例”。
你有兩個解決方案:1:向'PlaceJButtonActionPerformed'添加一個參數,它將作為第二個參數'selectedAppointment'2:或者你將'selectedAppointment'聲明為全局變量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.