public Lab7(File file) {
List<Item> items = null;
try {
items = InventoryReader.read(file);
} catch (ApplicationException e) {
LOG.error(e.getMessage());
return;
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, use the default.
}
try {
MainFrame frame = new MainFrame(items); // THIS IS WHERE I HAVE TROUBLE
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
背景:我将 MainFrame 的构造函数设置为接受列表。如何在应用程序的 main() 中执行此操作?
我收到错误:
不能引用不同方法中定义的内部类中的非最终变量“items”
错误出现在 MainFrame frame = new MainFrame(items)
我似乎无法将 items 变量传递给 MainFrame 类...为什么会这样?
如何将此变量传递到 MainFrame 框架中?
最佳答案
你有两个选择......
选择一个...
将items
列表设为最终列表,以便可以从Runnable
上下文中访问它...
public Lab7(File file) {
final List<Item> items = null; // Make the items final...
try {
items = InventoryReader.read(file);
} catch (ApplicationException e) {
LOG.error(e.getMessage());
return;
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, use the default.
}
try {
MainFrame frame = new MainFrame(items); // THIS IS WHERE I HAVE TROUBLE
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
选择二...
将items
列表移动到Runnable
上下文中
public Lab7(File file) {
EventQueue.invokeLater(new Runnable() {
public void run() {
// Load the items within the content of the runnable...
List<Item> items = null;
try {
items = InventoryReader.read(file);
} catch (ApplicationException e) {
LOG.error(e.getMessage());
return;
}
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, use the default.
}
try {
MainFrame frame = new MainFrame(items); // THIS IS WHERE I HAVE TROUBLE
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
关于java - 如何将列表传递到 Swing 中的初始框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13354429/