2013-12-08 85 views
0

我有這個代碼,我試圖修改,以添加一個菜單欄'文件'等 添加他們已沒有問題,添加他們的聽衆被證明是一個問題。每當我嘗試使用語法fileMenu1.addActionListener(this);時,我都會收到錯誤「無法在靜態上下文中使用它」。有什麼建議麼?我相信我接近完成這一點。 這是一個多類課程。如果需要,請將其他人如何爲此實現ActionListener?

import java.awt.Container; 
import java.awt.GridLayout; 
import javax.swing.*; 
import java.awt.event.*; 


public class BingoMain extends JFrame implements ActionListener { //I ADDED THE LISTENER HERE 

    private static final int ROWS = 5; 
    private static final int COLS = 5; 
    private static final int MAX_BINGO = 15 * COLS;  //15*5 = 75. Max number of bingo numbers 
    private static JMenuItem fileMenu1 = new JMenuItem("Play"); 
    private static JMenuItem fileMenu2 = new JMenuItem("Quit"); 
    /** 
    * @param args 
    * 
    */ 
    public static void main (String[] args) { 

     //Ask for how number of players, take the input, parse it, create that many bingo cards 
     String players = JOptionPane.showInputDialog(null, "How many players? (1 to 5 players)"); 
     int playerNums= Integer.parseInt(players); 

     JFrame myBingoGUI=new JFrame(); //frame 
     myBingoGUI.setSize(900, 400); 
     myBingoGUI.setLocation(100, 100); 
     myBingoGUI.setTitle("BINGO"); 
     myBingoGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     Container myContentPane = myBingoGUI.getContentPane(); 

     JMenuBar bar = new JMenuBar(); //create menu bar 
     JMenu fileMenu = new JMenu("File"); //create the file item in the bar 

     bar.add(fileMenu); 

     fileMenu.add(fileMenu1); 
     fileMenu.add(fileMenu2); 
     myBingoGUI.setJMenuBar(bar); 

     fileMenu1.addActionListener(this);  //ERROR! 
     fileMenu2.addActionListener(this);  //Same error 

     myContentPane.setLayout(new GridLayout(0, playerNums)); 

     BingoCard[] cards = new BingoCard[playerNums]; 
     for (int i = 0; i < cards.length; i++) { 
      cards[i] = new BingoCard("Card " + (i + 1), COLS, ROWS, MAX_BINGO/COLS); 
      BingoGUI bingoCard = new BingoGUI(); 
      cards[i].addListener(bingoCard); 
      myContentPane.add(bingoCard); 
     } 

     myBingoGUI.setVisible(true); 

     System.out.println(cards[0]); //print the cards on the console 
     System.out.println(); 
     /* 
     * Play the game: 
     */ 
     boolean winner = false;  //default false value for every player 
     while (!winner) { 
      String error = ""; 
      int calledValue = -1; 
      int calledColumn=-1; 
      do { 
       String calledNumber = JOptionPane.showInputDialog(null, error + " Enter a BINGO call:"); 
       error = ""; 
       calledColumn = -1; 
       calledValue = -1; 


       /* 
       * The first character of the input string is converted to a column number between 0 and 4 
       */ 
       if (Character.toUpperCase(calledNumber.charAt(0))=='B') calledColumn=0; 
       if (Character.toUpperCase(calledNumber.charAt(0))=='I') calledColumn=1; 
       if (Character.toUpperCase(calledNumber.charAt(0))=='N') calledColumn=2; 
       if (Character.toUpperCase(calledNumber.charAt(0))=='G') calledColumn=3; 
       if (Character.toUpperCase(calledNumber.charAt(0))=='O') calledColumn=4; 
       if (calledColumn < 0) { 
        error = "Called Column '" + Character.toUpperCase(calledNumber.charAt(0)) + "' must be on the BINGO card";  //if first character is not a B, I, N, G, O show message 
       } else { //error catching 
        /* 
        * The remainder of the input string is converted to an integer 
        */ 
        //try catch block to catch any illegal numerical values (A legal column with an illegal value within the range will still be accepted) 
        try { 
         calledValue = Integer.parseInt(calledNumber.substring(1,calledNumber.length())); 
         if (calledValue < 1 || calledValue > MAX_BINGO) { 
          error = "Value not legal " + calledValue + " (1 <= value <= " + MAX_BINGO + ")"; //error if <0 or >75 is input, values dont exist in Bingo 
         } 
        } catch (NumberFormatException nfe) { 
         error = "Illegal number " + calledNumber.substring(1,calledNumber.length()); //error if format is wrong (i.e B9g or N5t) cant mix letters with numbers 
        } 
       } 
      } while (error.length() != 0); 
      /* 
      * The array of called numbers is updated to show the number has been called. 
      */ 
      for (BingoCard card : cards) { 
       if (card.called(calledColumn, calledValue)) {  
        winner = true; 
       } 
      } 
      if (winner) { 
       for (BingoCard card : cards) { 
        JOptionPane.showInputDialog(null, "BINGO"); 
        card.gameOver(); 
       } 
      } 
      System.out.println(cards[0]); 
      System.out.println(); 

     } // while 

    } // main 

} 
+0

我沒有看到一個'的actionPerformed()'任何地方。 –

回答

1

基本上thisstatic方法中沒有上下文,因爲沒有「this」可用。

相反,您需要實現ActionListener的類的實例,奇怪的是,您從未創建該實例。

您使用創建一個類...

public class BingoMain extends JFrame implements ActionListener {... 

但你創建一個使用主框架...

JFrame myBingoGUI=new JFrame(); //frame 

這是一個更好的辦法,但擊敗從JFrame延長的目的。

相反,我會建議取下extends JFrame部分,並創建一個構造函數初始化主程序,然後將其添加到框架...

例如...

public class BingoMain implements ActionListener { //I ADDED THE LISTENER HERE 

    private static final int ROWS = 5; 
    private static final int COLS = 5; 
    private static final int MAX_BINGO = 15 * COLS;  //15*5 = 75. Max number of bingo numbers 
    private JMenuItem fileMenu1 = new JMenuItem("Play"); 
    private JMenuItem fileMenu2 = new JMenuItem("Quit"); 

    public BingoMain() { 

     //Ask for how number of players, take the input, parse it, create that many bingo cards 
     String players = JOptionPane.showInputDialog(null, "How many players? (1 to 5 players)"); 
     int playerNums= Integer.parseInt(players); 

     JFrame myBingoGUI=new JFrame(); //frame 
     myBingoGUI.setSize(900, 400); 
     myBingoGUI.setLocation(100, 100); 
     myBingoGUI.setTitle("BINGO"); 
     myBingoGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     Container myContentPane = myBingoGUI.getContentPane(); 

     JMenuBar bar = new JMenuBar(); //create menu bar 
     JMenu fileMenu = new JMenu("File"); //create the file item in the bar 

     bar.add(fileMenu); 

     fileMenu.add(fileMenu1); 
     fileMenu.add(fileMenu2); 
     myBingoGUI.setJMenuBar(bar); 

     fileMenu1.addActionListener(this);  //ERROR! 
     fileMenu2.addActionListener(this);  //Same error 
     //... 
    } 

    /** 
    * @param args 
    * 
    */ 
    public static void main (String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       BingoMain main = new BingoMain(); 
      } 
     }); 

    } // main 

} 

嘗試和避免static變量,你可能需要使用變量

更新的多個實例

正如@peeskillet指出的那樣,在你的代碼示例中似乎沒有實現actionPerformed。這可能僅僅是對貴公司的疏忽,或者你會招致下一個問題......

請務必添加

@Override 
public void actionPerformed(ActionEvent evt) { 
} 

到您的類和import java.event.ActionEvent你的進口,以及...

+0

不是OP得到一個錯誤,而不是覆蓋actionPerformed()? –

+0

@peeskillet這是一個很好的觀點。也許這會引發一個新的問題;) – MadProgrammer

2

該代碼應該生成一個BingoMain的實例。 main方法是static這意味着它不與該類的任何實例關聯。關鍵字static表示方法,字段等與類本身相關聯,而不是類的實例。該代碼錯誤地假定static主要方法可以引用該類本身的一個實例,這是靜態的,這是不可能的。

public static void main (String[] args) { 
     /* Omitted*/ 
     BingoMain main = new BingoMain(); 
     fileMenu1.addActionListener(main);  //NO ERROR! 

     /* Omitted*/ 
} 
0
fileMenu1.addActionListener(this);  //ERROR! 
    fileMenu2.addActionListener(this);  //Same error 

main方法是一個靜態方法,並且在一個靜態的上下文中沒有this。你必須創建BingoMain類的實例,並在傳遞類的一個實例。

0

你或許應該建立自己的接口在類一樣的構造函數:

public class BingoMain extends JFrame implements ActionListener { 
    public BingoMain() { 
     // code to build your UI 
     fileMenu1.addActionListener(this); 
     // some more code 
    } 

    public static void main (String[]args){ 
     new BingoMain(); 
    } 
} 
相關問題