我有一個問題。我想使用位于按鈕外部的物件,但收到一條錯誤訊息:在封閉范圍內定義的區域變數必須是最終的或有效的最終
File inputfile = new File("./input.txt");
testobject to = null;
try
{
Scanner inputscan = new Scanner(inputfile);
String text1 = inputscan.nextLine();
String text2 = inputscan.nextLine();
to = new testobject(text1,text2);
inputscan.close();
}
catch (Exception e)
{
System.err.println(e);
}
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
to.setSomething("test");
}
});
顯然,我有一個帶有建構式等的類……但是我遇到了無法到達按鈕內的物件的問題。
uj5u.com熱心網友回復:
你想在匿名類中使用的變數,比如你ActionListener需要成為 final。您正在使用 null 初始化變數并將其更改為稍后從文本輸入創建的物件。
您可以改為使用 no args 建構式創建物件,并使用 setter 在您的testobject.
// Class names should start with a uppercase
testobject to = new testobject();
// Use try-with-resources to close them automatically.
try(Scanner inputscan = new Scanner(inputfile)){
to.setText1(inputscan.nextLine());
to.setText2(inputs can.neytLine());
} catch (Exception e) {
System.err.println(e)
}
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
to.setSomething("test");
}
});
或者在你的actionPerfromed方法中初始化變數。缺點是您無法在方法之外訪問測驗物件。
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try(Scanner inputscan = new Scanner(inputfile)){
testobject to = new testobject(inputscan.nextLine(), inputscan.nextLine());
to.setSomething("test");
} catch (Exception e) {
System.err.println(e)
}
}
});
uj5u.com熱心網友回復:
我嘗試了第一種方法,也許我做了一些舊的但沒有用。第二種方法有效,但這會在按鈕中創建一個新物件,因此如果我想在按鈕外使用,則需要重新設定所有內容。在我的程式中它非常復雜等等......
所以我創建了一個 Arraylist 的解決方案,我也可以在按鈕內部和外部使用它。
ArrayList<testobject> list = new ArrayList<testobject>();
在此之后,我將第一個 (0) 元素設定為我的資料
list.add(new eselyek(text1,text2));
在此之后,我可以輕松地使用類的方法
lista.get(0).setSomething("test");
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/363441.html
上一篇:如何在沒有物件宣告的情況下在C 中呼叫類函式?[復制]
下一篇:減少PyQt應用程式的冗余代碼
