2013-05-28 17 views
0

actionPerformed中,似乎根據Eclipse,所有變量(submit,msg,input)「無法解析」。根據我的經驗(其中我很少),這意味着我沒有定義變量。但是,正如你在代碼中看到的那樣,我已經定義了它們。 Submit是一個JButton,msg是一個字符串,輸入是一個JTextField。Java將無法識別已定義的變量?

package levels; 

import java.awt.BorderLayout; 
import java.awt.FlowLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.*; 

import java.util.*; 

public class LevelOne extends JFrame implements ActionListener{ 

    private Object msg; 

    public void one(){ 

     setTitle("Conjugator"); 
     setSize(400,400); 
     setLocationRelativeTo(null); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     setVisible(true); 

     setLayout(new BorderLayout()); 
     setContentPane(new JLabel(new ImageIcon("images/LevelOneBG.gif"))); 
     setLayout(new FlowLayout()); 

     JTextArea area = new JTextArea("You enter a castle. A Goblin demands you correct his sentences!"); 
     add(area); 
     setVisible(true); 

     //these aren't being called to actionPerformed 
     JButton submit = new JButton("Check sentence"); 
     submit.addActionListener(this); 
     setVisible(true); 
     JTextField input = new JTextField("Ich spielen Golf."); 
     input.setActionCommand("input"); 
     add(input); 
     input.addActionListener(this); 
     setVisible(true); 

     String msg = ("Test successful"); 
    } 

    //this should be successfully locating and utilizing "submit", "input" and "msg", but it won't 
    public void actionPerformed(ActionEvent e) { 
     if (e.getSource() == submit) { 
      msg = submit.getText(); 

      //!! Display msg only **after** the user has pressed enter. 
      input.setText(msg); 
     } 

    } 
} 

我知道我的一些進口是不必要的。

附言:我正在做一個小的文字冒險遊戲,我的德國類

+3

縮進你的代碼三立,請,這是很難說的事情的範圍應該是。 – millimoose

+0

對不起。我將來會記住這一點。同時,你有解決我的問題嗎? – user2426434

+0

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html。您應該閱讀本教程,注意實例變量(字段)和局部變量(方法中定義的變量)之間的差異。特別是讀取部分:「*局部變量只對聲明它們的方法可見;它們不能從其他類訪問*」 –

回答

3

您定義的變量作爲方法one()當地變量。根據定義,局部變量是...本地的。它們只在它們定義的塊中可見。要在one()actionPerformed()中可見,應將它們定義爲類的字段。

另一種方法是使用one()方法中定義的匿名內部類來定義動作偵聽器,但考慮到您尚未掌握變量,最好稍後留下匿名類。 Swing是一個複雜的框架,你應該在做Swing之前做一些更基本的編程練習。

+0

謝謝。愚蠢的錯誤。 – user2426434

0

這是因爲和submit變量在actionPerformed方法中不可訪問。

充分利用inputsubmit變量類成員,例如:

pubilc class LevelOne { 
    private JTextField input = new JTextField("Ich spielen Golf."); 
    private Object msg; 
    private JButton submit = new JButton("Check sentence"); 


    public void one() { ... } 

    public void actionPerformed(ActionEvent e) { ... } 
} 
+0

謝謝。我應該看到這一點。 – user2426434

0

那些變量的範圍僅一個()方法。如果你想讓全班同學把它們放在msg旁邊的頂部。

0

變量submit被定義爲方法one()中的局部變量。

它在方法actionPerformed()中不可用。

0

您需要聲明類似方法「一號」之外的變量:

private JButton submit = new JButton("Check sentence"); 

public void one(){ 
    // whatever goes there 
} 

public void actionPerformed(ActionEvent e) { 
    // submit is now working 
    if (e.getSource() == submit) { 
    } 
}