gpt4 book ai didi

java - 从内部类引用的局部变量必须是最终的或有效最终的

转载 作者:行者123 更新时间:2023-12-01 18:22:56 26 4
gpt4 key购买 nike

请看下面的代码

private void displayInitialRevenue_Method() {
//Get the dates from the combo
String selectedCouple = revenueYearCombo.getSelectedItem().toString();
if (selectedCouple.equals("Select Year")) {
return;
}
String[] split = selectedCouple.split("/");
//Related to DB
double totalAmount = 0.0;
//Get data from the database
dbConnector = new DBHandler();
dbConnector.makeConnection();
DefaultTableModel model = (DefaultTableModel) initialRevenueTable.getModel();
model.setRowCount(0);
ResultSet selectAllDetails = dbConnector.selectAllDetails("SQL CODE ");
try {
if (selectAllDetails.isBeforeFirst() == false) {
JOptionPane.showMessageDialog(null, "This table is empty");
} else {
while (selectAllDetails.next()) {
String clientName = selectAllDetails.getString("Client Name");
String providerName = selectAllDetails.getString("Provider Name");
Double amountInvested = selectAllDetails.getDouble("Invest_Amount");
//Update the table
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Object[] row = {clientName, providerName, amountInvested};
model.addRow(row);
}
});
//Get the total
totalAmount = totalAmount + amountInvested;
}
//Add the sum
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Object[] blankRow = {null};
model.addRow(blankRow);
Object[] row = {totalAmount};
model.addRow(row);

}
});
}
} catch (SQLException sql) {
JOptionPane.showMessageDialog(null, sql.getLocalizedMessage());
}
}

整个方法在另一个线程内运行。 UI 更新在 SwingUtilities.InvokeLater() 内运行。不过请注意以下几点。

Object[]row = {totalAmount};
model.addRow(row);

变量totalAmount不是最终的,也不能是最终的,因为它需要在上面的while循环中计算。由于它不是 final 我无法在 SwingUtilities.InvokeLater() 中使用它,因为错误显示 从内部类引用的局部变量必须是最终的或有效的最终结果

最佳答案

您可以创建一个附加变量 Final,然后将计算的最终结果复制到其中。

while (selectAllDetails.next()) {
String clientName = selectAllDetails.getString("Client Name");
String providerName = selectAllDetails.getString("Provider Name");
Double amountInvested = selectAllDetails.getDouble("Invest_Amount");
//Update the table
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Object[] row = {clientName, providerName, amountInvested};
model.addRow(row);
}
});
//Get the total
totalAmount = totalAmount + amountInvested;
}
final Double totalAmountInvested = totalAmount; // and now use this one in the Inner

关于java - 从内部类引用的局部变量必须是最终的或有效最终的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27165006/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com