[英]Java: Access a variable which is inside an actionlistener
我已經嘗試了一段時間來訪問我的主類中的變量:
public class Results extends JFrame {
public static void main(String[] args)
{
System.out.println(doble);
}}
像這樣在動作監聽器中
public Results ()
{
// Create a JPanel for the buttons DOUBLE AND NOT DOUBLE
JPanel duplicate = new JPanel(
new FlowLayout(FlowLayout.CENTER));
JButton doblebutton = new JButton("DOUBLE");
doblebutton.addActionListener(new ActionListener(){
private int doble;
public void actionPerformed(ActionEvent ae){
doble++;
System.out.println("Doubles: " + doble);
}
});
}
我已經嘗試了5種方法來做到這一點,但這似乎是不可能的。 有什么想法嗎?
嘗試將doble聲明移到構造函數之外,以使其成為字段,如下所示:
public class Results extends JFrame {
private int doble;
public Results() {
// Create a JPanel for the buttons DOUBLE AND NOT DOUBLE
JPanel duplicate = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton doblebutton = new JButton("DOUBLE");
doblebutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
doble++;
System.out.println("Doubles: " + doble);
}
});
}
public static void main(String[] args) {
Results results = new Results();
System.out.println(results.doble);
}
}
一些評論:
希望這可以幫助。
當前doble
是在構造函數中聲明的局部變量 ,因此它的作用域 confined to constructor
,在insatnce level
聲明它以在其他地方訪問它。
public class Results extends JFrame {
private int doble;
//cons code
public static void main(String[] args)
{
System.out.println(new Results().doble);
}}
main()
是靜態的, doble
是實例變量。 您必須實例化或將變量設為靜態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.