[英]Getting error using nested ActionListener class for a JButton Object?
這是我第一次嘗試使用動作偵聽器和事件處理。 我正在嘗試創建一個具有3個按鈕的簡單GUI: home
, about
和tag
。 我為每個JButton
添加了一個偵聽器對象,並為該偵聽器對象創建了一個嵌套類。
public class interfacetest {
public static void main(String[] args) {
JFrame window = new JFrame("GUI Test");
window.setSize(250, 100);
window.setLocation(100, 100);
final JButton home = new JButton("Home");
final JButton about = new JButton("About");
final JButton tag = new JButton("Tag");
JMenuBar menu = new JMenuBar();
menu.add(home);
menu.add(about);
menu.add(tag);
menu.setVisible(true);
window.setJMenuBar(menu);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thehandler handler = new thehandler();
home.addActionListener(handler);
about.addActionListener(handler);
tag.addActionListener(handler);
window.setVisible(true);
}
// Here is my nested class.
private class thehandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
String string = "";
if (event.getSource()==home)
string = string.format("home: %s, event.getActionCommand()");
else if (event.getSource()==about)
string = string.format("about: %s, event.getActionCommand()");
else if (event.getSource()==tag) string = string.format("tag: %s, event.getActionCommand()");
JOptionPane.showMessageDialog(null, string);
}
}
}
創建新的thehandler
對象時出現錯誤: “沒有接口test類型的封閉實例可以訪問。必須使用接口test類型的封閉實例(egxnew A()來限定分配,其中x是interfacetest的實例)“。
您有兩種簡單的方法可以解決此問題:
private static class thehandler
。 (new interfacetest()).new thehandler()
(您可能需要重組代碼,並且可能希望保留對interfacetest
實例的引用。 像這樣:
interfacetest iner = new interfacetest();
// Do things...
thehandler handler = iner.new thehandler(); // (e.g. x.new A() where x is an instance of interfacetest.)
說明:您的嵌套類是非靜態的,但是您嘗試像訪問它一樣訪問它。
classInstance.nonStaticMember
(上面的選項2)來訪問它。 ClassType.staticMember
(上面的選項1)。 在您的情況下,您正在執行ClassType.nonStaticMember
或this.nonStaticMember
之類的操作(“無法訪問類型為this.nonStaticMember
封閉實例”)。
您可能還會發現此術語(來自教程 )很有用:
嵌套類分為兩類:靜態和非靜態。 聲明為靜態的嵌套類稱為靜態嵌套類 。 非靜態嵌套類稱為內部類 。
筆記:
JFrame
上調用pack()
,而不是手動setSize(...)
。 setVisible(true)
。 actionPerformed
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.