2017-04-25 75 views
-1

我想在基於GUI的Hangman遊戲中使用基於JButton的鍵盤。但是,當我想檢查被按下的鍵是否隱藏在單詞中時,我不確定在哪裏需要將字符串的類型更改爲字符。我想使用基於GUI的鍵盤,而不是允許用戶使用鍵盤,以儘量減少需要完成的驗證。這些是我迄今爲止創建的類。我很努力做到這一點。JButton鍵盤 - 將setText轉換爲字符

package guis; 

import java.awt.*; 
import java.awt.event.*; 
import java.io.File; 
import java.io.IOException; 
import javax.imageio.ImageIO; 
import javax.swing.*; 

public class MouseClick extends JFrame implements ActionListener, MouseListener 
{ 
private static final long serialVersionUID = 1L; 
private static ActionListener letterHandler = null; 
private Container cPane; 
private JLabel lblTitle, lblTries, lblCountryToGuess, chancesLabel, message;//, usedLettersPanel; 
private JButton btnExit, btnStart, btn1, btn3, btn4, btnX; 
private JButton [] btn = new JButton[26]; 
private JPanel pNorth, pSouth, pEast, pWest, pCenter, wordPanel, messagePanel, usedLettersPanel, hangPanel, drawingFrame;//, lblCountryToGuess; 
private JMenuItem mIRules, mIDev, mIRestart, mIExit; 
private javax.swing.JLabel jLabel1; 
private javax.swing.JMenu jMenu1; 
private javax.swing.JMenu jMenu2; 
private javax.swing.JMenu jMenu3; 
private javax.swing.JMenuBar jMenuBar1; 
private javax.swing.JMenuItem jMenuItem1; 
private javax.swing.JMenuItem jMenuItem3; 
private javax.swing.JMenuItem jMenuItem4; 
private javax.swing.JMenuItem jMenuItem5; 
private javax.swing.JPopupMenu.Separator jSeparator1; 
private JFrame frame = new JFrame(); 
private JButton enter; 
private JLabel[] wordArray, usedLetters; 
//private JFrame drawingFrame; 
private HangmanDrawing drawing; 
private char[] incorrectGuesses; 
private char[] buttonLetters = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; 
private String word; 
private int chances; 
char input; 

private JFrame endFrame; 
private JPanel top, bottom; 
private JLabel doNow; 
private JButton restart, exit; 

MouseClick() throws IOException 
{ 
    super("Assignment 2 - Hangman"); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    word = new WordHandler().getRandomWord(); 
    chances = 7; 

    cPane = getContentPane(); 
    cPane.setBackground(new Color (236, 128, 19)); 

    pNorth = new JPanel(); 
    pSouth = new JPanel(); 
    pEast = new JPanel(); 
    pWest = new JPanel(); 
    pCenter = new JPanel(); 

    lblTitle = new JLabel(" Hangman ", SwingConstants.CENTER); 
    lblTitle.setFont(new Font("Comic Sans MS", Font.BOLD, 24)); 
    lblTitle.setBorder(BorderFactory.createRaisedBevelBorder()); 
    lblTitle.setBackground(new Color (38, 29, 226)); 
    lblTitle.setOpaque(true); 
    lblTitle.setForeground(Color.white); 
    pNorth.add(lblTitle); 

    /*lblCountryToGuess = new JLabel("", SwingConstants.CENTER); 
    lblCountryToGuess.setFont(new Font("Comic Sans MS", Font.BOLD, 24)); 
    //lblCountryToGuess.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 5)); 
    lblCountryToGuess.setBounds(50, 1, 500, 60); 
    lblCountryToGuess.setBorder(BorderFactory.createTitledBorder("This is the country to be guessed...")); 
    //wordArray = new JLabel [hiddenCountry.length()]; 
    //for (int i = 0 ; i < wordArray.length ; i++) 
    //{ 
     // wordArray[i] = new JLabel("_"); 
     // wordArray[i].setFont(new Font("Comic Sans MS.", Font.BOLD, 23)); 
     // lblTitle4.add(wordArray[i]); 
    //} 
    pCenter.add(lblCountryToGuess);*/ 

    hangPanel = new HangmanDrawing(); 
    //drawing = new HangmanDrawing(); 
    drawingFrame = new JPanel(); 
    //drawingFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); 
    //drawingFrame.setFocusableWindowState(false); 
    //drawingFrame.getContentPane().add(drawing); 
    //int xPosition = (int) ((scrnsize.width/2) + (this.getWidth()/2)); 
    //drawingFrame.setSize(scrnsize.width - xPosition - 10, 
     //scrnsize.width - xPosition - 10); 
    // drawingFrame.setLocation(xPosition, 
     //(int) (scrnsize.height - this.getHeight())/3); 

    setVisible (true); 
    drawingFrame.setVisible(true); 
    pCenter.add(drawingFrame); 

    wordPanel = new JPanel(); 
    wordPanel.setBounds(100, 100, 100, 60); 
    wordPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 5)); 
    wordPanel.setBorder(BorderFactory.createTitledBorder("This is the country to guess...")); 
    wordArray = new JLabel [word.length()]; 
    for (int i = 0 ; i < wordArray.length ; i++) 
    { 
     wordArray[i] = new JLabel("_"); 
     wordArray[i].setFont(new Font("Arial", Font.BOLD, 23)); 
     wordPanel.add(wordArray[i]); 
    } 
    pCenter.add(wordPanel); 

    usedLettersPanel = new JPanel(); 
    usedLettersPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 13, 5)); 
    incorrectGuesses = new char [chances]; 
    usedLetters = new JLabel [incorrectGuesses.length]; 
    for (int i = 0 ; i < usedLetters.length ; i++) 
    { 
     usedLetters[i] = new JLabel("~"); 
     usedLetters[i].setFont(new Font("Comic Sans MS", Font.BOLD, 18)); 
     usedLettersPanel.add(usedLetters[i]); 
    } 
    pCenter.add(usedLettersPanel); 

    messagePanel = new JPanel(); 
    messagePanel.setLayout (new FlowLayout (FlowLayout.LEFT)); 
    message = new JLabel ("Guess a letter..."); 
    message.setFont (new Font ("Comic Sans MS", Font.BOLD, 17)); 
    messagePanel.add(message); 
    pCenter.add(messagePanel); 

    /*usedLettersPanel = new JLabel(); 
    usedLettersPanel.setFont(new Font("Comic Sans MS", Font.BOLD, 24)); 
    usedLettersPanel.setBounds(50, 1, 500, 60); 
    usedLettersPanel.setBorder(BorderFactory.createTitledBorder("Letters already guessed...")); 
    //usedLettersPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 13, 5)); 
    //incorrectGuesses = new char [chances]; 
    //usedLetters = new JLabel [incorrectGuesses.length]; 
    //for (int i = 0 ; i < usedLetters.length ; i++) 
    //{ 
     //usedLetters[i] = new JLabel("~"); 
     //usedLetters[i].setFont(new Font("Comic Sans MS", Font.BOLD, 18)); 
     //usedLettersPanel.add(usedLetters[i]); 
    //} 
    pCenter.add(usedLettersPanel);*/ 

    btnStart = new JButton(" Start/New Game "); 
    btnStart.setFont(new Font("Comic Sans MS", Font.BOLD, 12)); 
    btnStart.setBackground(Color.GREEN); 
    btnStart.setForeground(Color.white); 
    btnStart.setOpaque(true); 
    btnStart.setBorder(BorderFactory.createRaisedBevelBorder()); 
    pWest.add(btnStart); 

    btnStart.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      dispose(); 
      jMenuItem1.setVisible(true); 
      MouseClick sample = null; 
      try 
      { 
       sample = new MouseClick(); 
      } 
      catch (IOException e1) 
      { 
       e1.printStackTrace(); 
      } 
      sample.setTitle("Assignment 2 - Hangman Game"); 
      sample.setSize(1200, 800); 
      sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      sample.setVisible(true); 
     }// end actionPerformed method 
    }); 

    chancesLabel = new JLabel (chances + " chances left..."); 
    chancesLabel.setFont (new Font ("Comic Sans MS", Font.BOLD, 17)); 
    //lblTries = new JLabel(" Tries Remaining "); 
    //lblTries.setFont(new Font("Comic Sans MS", Font.BOLD, 12)); 
    chancesLabel.setBackground(new Color (38, 29, 226)); 
    chancesLabel.setForeground(Color.white); 
    chancesLabel.setOpaque(true); 
    chancesLabel.setBorder(BorderFactory.createRaisedBevelBorder()); 
    pWest.add(chancesLabel); 

    btnExit = new JButton(" Exit Game"); 
    btnExit.setFont(new Font("Comic Sans MS", Font.BOLD, 12)); 
    btnExit.setBackground(new Color (236, 19, 35)); 
    btnExit.setForeground(Color.white); 
    btnExit.setBorder(BorderFactory.createRaisedBevelBorder()); 
    pWest.add(btnExit); 

    for(int i = 0; i < 26; i++) 
    { 
     //JButton btnX = new JButton(); 
     btnX = new JButton(new KeyboardListener(buttonLetters[i])); 
     btnX.setText("" + buttonLetters[i]); 
     pSouth.add(btnX); 
     btnX.setVisible(true); 
     //btn[i] = btnX; 
     //btn[i].setText("" + (char)('A'+ i)); 
     //btn[i].setText("" + buttonLetters[i]); 
     //input = buttonLetters[i]; 
     //pSouth.add(btn[i]); 
     //btn[i].setVisible(true); 

    } 

    cPane.add(pNorth, BorderLayout.NORTH); 
    cPane.add(pSouth, BorderLayout.SOUTH); 
    pSouth.setLayout(new GridLayout(3,10,1,1)); 
    cPane.add(pWest, BorderLayout.WEST); 
    pWest.setLayout(new GridLayout(3,1,1,10)); 
    cPane.add(pEast, BorderLayout.EAST); 
    cPane.add(pCenter, BorderLayout.CENTER); 
    pCenter.setLayout(new GridLayout(4, 1, 1, 1)); 

    /*Container chancesContainer = new Container(); 
    chancesContainer.setLayout(new FlowLayout (FlowLayout.RIGHT)); 
    chancesContainer.add(chancesLabel); 

    JPanel wrongGuessesContainer = new JPanel(); 
    wrongGuessesContainer.setLayout(new GridLayout (1, 2)); 
    wrongGuessesContainer.setBorder(BorderFactory.createTitledBorder ("Wrong Guesses")); 
    wrongGuessesContainer.add(usedLettersPanel); 
    wrongGuessesContainer.add (chancesContainer); 

    Container bottomContainer = new Container(); 
    bottomContainer.setLayout(new BorderLayout()); 
    bottomContainer.add(wrongGuessesContainer, BorderLayout.NORTH); 
    bottomContainer.add(messagePanel, BorderLayout.SOUTH); 

    getContentPane().setLayout(new BorderLayout()); 
    //getContentPane().add (inputPanel, BorderLayout.NORTH); 
    getContentPane().add(wordPanel, BorderLayout.CENTER); 
    getContentPane().add(bottomContainer, BorderLayout.SOUTH);*/ 

    btnExit.addActionListener(this); 

    pCenter.addMouseListener(this); 
    pNorth.addMouseListener(this); 
    pSouth.addMouseListener(this); 
    pEast.addMouseListener(this); 
    pWest.addMouseListener(this); 

    jMenuBar1 = new javax.swing.JMenuBar(); 
    jMenu1 = new javax.swing.JMenu(); 
    jMenuItem1 = new javax.swing.JMenuItem(); 
    jMenu2 = new javax.swing.JMenu(); 
    jMenuItem3 = new javax.swing.JMenuItem(); 
    jSeparator1 = new javax.swing.JPopupMenu.Separator(); 
    jMenuItem4 = new javax.swing.JMenuItem(); 
    jMenu3 = new javax.swing.JMenu(); 
    jMenuItem5 = new javax.swing.JMenuItem(); 

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 


    jMenu1.setText("File"); 

    jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK)); 
    jMenuItem1.setText("New Game"); 
    jMenuItem1.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      dispose(); 
      jMenuItem1.setVisible(true); 
      MouseClick sample = null; 
      try 
      { 
       sample = new MouseClick(); 
      } 
      catch (IOException e1) 
      { 
       e1.printStackTrace(); 
      } 
      sample.setTitle("Assignment 2 - Hangman Game"); 
      sample.setSize(1200, 800); 
      sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      sample.setVisible(true); 
     }// end actionPerformed method 
    }); 
    jMenu1.add(jMenuItem1); 

    jMenuBar1.add(jMenu1); 

    jMenu2.setText("Help"); 

    jMenuItem3.setText("Rules"); 
    jMenuItem3.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      JOptionPane.showMessageDialog(frame, "Hangman is a guessing game where the word" 
       +"\n to guess is represented by dashes. The player" 
       +"\n is given the option to enter a letter. If the letter" 
       +"\n guessed is contained in the word, the letter will" 
       +"\n replace the dash in its approprate placement." 
       +"\n You cannot exceed 7 wrong guesses or else you" 
       +"\n lose. Words are selected randomly.", "Instructions", 
       JOptionPane.INFORMATION_MESSAGE); 
     } 
    }); 
    jMenu2.add(jMenuItem3); 
    jMenu2.add(jSeparator1); 

    jMenuItem4.setText("Developer"); 
    jMenuItem4.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      JOptionPane.showMessageDialog(frame, "Developer: Ryan Smith"); 
     } 
    }); 
    jMenu2.add(jMenuItem4); 

    jMenuBar1.add(jMenu2); 

    jMenu3.setText("Exit"); 

    jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK)); 
    jMenuItem5.setText("Exit Game"); 
    jMenuItem5.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      System.exit(0); 
     } 
    }); 
    jMenu3.add(jMenuItem5); 

    jMenuBar1.add(jMenu3); 

    setJMenuBar(jMenuBar1); 

    pack(); 

    /*drawing = new HangmanDrawing(); 
    drawingFrame = new JFrame(); 
    drawingFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); 
    drawingFrame.setFocusableWindowState(false); 
    drawingFrame.getContentPane().add(drawing); 
    int xPosition = (int) ((scrnsize.width/2) + (this.getWidth()/2)); 
    drawingFrame.setSize(scrnsize.width - xPosition - 10, 
     scrnsize.width - xPosition - 10); 
    drawingFrame.setLocation(xPosition, 
     (int) (scrnsize.height - this.getHeight())/3); 

    setVisible (true); 
    drawingFrame.setVisible(true);*/ 
} 

private void endGame() 
{ 
     enter.removeActionListener (this); 
     //inputField.removeActionListener(this); 
     //inputField.setEditable (false); 

     endFrame = new JFrame(); 
     top = new JPanel(); 
     bottom = new JPanel(); 
     doNow = new JLabel ("What do you want to do now?"); 
     restart = new JButton ("Start Again"); 
     exit = new JButton ("Exit Hangman"); 

     doNow.setFont (new Font ("Verdana", Font.BOLD, 17)); 
     top.setLayout (new FlowLayout (FlowLayout.CENTER)); 
     top.add (doNow); 

     restart.setFont (new Font ("Arial", Font.BOLD, 12)); 
     restart.addActionListener(this); 
     exit.setFont (new Font ("Arial", Font.BOLD, 12)); 
     exit.addActionListener(this); 

     bottom.setLayout (new FlowLayout (FlowLayout.CENTER, 44, 10)); 
     bottom.add (restart); 
     bottom.add (exit); 

     endFrame.getContentPane().setLayout (new BorderLayout()); 
     endFrame.getContentPane().add (top, BorderLayout.NORTH); 
     endFrame.getContentPane().add (bottom, BorderLayout.SOUTH); 
     endFrame.pack(); 
     Dimension scrnsize = Toolkit.getDefaultToolkit().getScreenSize(); 
     endFrame.setLocation ((int) (scrnsize.width - endFrame.getWidth())/2, 
      (int) (scrnsize.height - this.getHeight())/3 + this.getHeight()); 
     endFrame.setResizable (false); 
     endFrame.setVisible (true); 
     this.setFocusableWindowState(false); 
    } 

    public void actionPerformed (ActionEvent event) 
    { 
     if(event.getSource().equals(btnExit)) 
     { 
      System.exit(0); 
     } 
     else if (event.getSource().equals(restart)) 
     { 
      endFrame.dispose(); 
      MouseClick.this.dispose(); 
      //drawingFrame.dispose(); 
      //new HangmanMenu(); 
     } 
     else if (event.getSource().equals(exit)) 
     { 
      endFrame.dispose(); 
      MouseClick.this.dispose(); 
      //drawingFrame.dispose(); 
      System.exit(0); 
     } 
     else 
     { 
      try 
      { 
       //char input = Character.toUpperCase(inputField.getText().charAt(0)); 
       //if(event.getSource().equals(btn)) 
       //{ 
        //System.out.println("\n" + input); 
        boolean letterInWord = false; 
        for (int i = 0 ; i < word.length() ; i++) 
        { 
         if (word.charAt (i) == input) 
         { 
          letterInWord = true; 
          break; 
         } 
        } 
        if (!letterInWord) { 
        boolean alreadyGuessed = false; 
        for (int i = 0 ; i < incorrectGuesses.length ; i++) { 
         if (incorrectGuesses [i] == input) { 
          alreadyGuessed = true; 
          message.setText ("You already guessed that!"); 
          break; 
         } 
        } 
        if (!alreadyGuessed) { 
         chances--; 
         drawing.addPart(); 
         if (chances >= 0) { 
          incorrectGuesses [incorrectGuesses.length - chances - 1] = input; 
          usedLetters [usedLetters.length - chances - 1].setText ("" + input); 
          message.setText ("Woops, wrong! Try again!"); 
          chancesLabel.setText (chances + " chances left..."); 
         } else { 
          chancesLabel.setText ("Sorry, you lose."); 
          message.setText ("The word was: " + word); 
          endGame(); 
         } 
        } 
       } else { 
        boolean alreadyGuessed = false; 
        for (int i = 0 ; i < wordArray.length ; i++) { 
         if (wordArray [i].getText().charAt (0) == input) { 
          alreadyGuessed = true; 
          message.setText ("You already guessed that!"); 
          break; 
         } 
        } 
        if (!alreadyGuessed) { 
         for (int i = 0 ; i < word.length() ; i++) { 
          if (word.charAt (i) == input) { 
           wordArray [i].setText ("" + input); 
          } 
         } 
         boolean wordComplete = true; 
         for (int i = 0 ; i < wordArray.length ; i++) { 
          if (!Character.isLetter (wordArray [i].getText().charAt (0))) { 
           wordComplete = false; 
           break; 
          } 
         } 
         if (!wordComplete) { 
          message.setText ("Well done, you guessed right!"); 
         } else { 
          message.setText ("Congratulations, you win the game!"); 
          drawing.escape(); 
          endGame(); 
         } 
        } 
       //} 
       } 
       //inputField.setText (""); 
      }catch (Exception x) 
      { 
      } 
     } 
    } 

@Override 
public void mouseClicked(MouseEvent e){} 
@Override 
public void mouseEntered(MouseEvent e){} 
@Override 
public void mouseExited(MouseEvent e){} 
@Override 
public void mousePressed(MouseEvent e){} 
@Override 
public void mouseReleased(MouseEvent e){} 

class KeyboardListener implements ActionListener 
{ 
    private final char letter; 

    public KeyboardListener(char letter) 
    { 
     this.letter = letter; 
    } 

    public char getLetter() 
    { 
     return letter; 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) 
    { 
     char tempLetter; 

     if (e.getSource().equals(btnX)) 
     { 
      tempLetter = 'A'; 

     } 
    } 
} 

}
這是WordHandler類的代碼。

package guis; 

import java.io.*; 

class WordHandler 
{ 

private BufferedReader fileIn; 
private String[] wordArray; 
private File wordFile; 

public WordHandler() throws IOException 
{ 
    wordFile = new File("countriesnospaces.txt"); 
    int arrayCounter = 0; 
    try { 
      BufferedReader fileIn = new BufferedReader(new FileReader(wordFile)); 

      while (fileIn.readLine() != null) 
      { 
       arrayCounter++; 
      } 
      wordArray = new String [arrayCounter]; 
      fileIn.close(); 

      fileIn = new BufferedReader(new FileReader(wordFile)); 
      for (int pos = 0 ; pos < arrayCounter ; pos++) 
      { 
       wordArray[pos] = fileIn.readLine(); 
      } 
      fileIn.close(); 
    } catch (FileNotFoundException e) 
    { 
     System.out.println("File not found. Please create it and add words."); 
    } 
    catch (Exception e) 
    { 
     System.out.println("Error: " + e); 
    } 
} 

public String getRandomWord() throws IOException 
{ 
    int random = (int) (Math.random() * wordArray.length); 
    return wordArray[random].toUpperCase(); 
} 

public void sort() 
{ 
    String temp; 
    for (int loop = 0 ; loop < wordArray.length - 1 ; loop++) { 
     for (int pos = 0 ; pos < wordArray.length - 1 - loop ; pos++) { 
      if (wordArray[pos].compareTo(wordArray[pos + 1]) >0) { 
       temp = wordArray[pos]; 
       wordArray[pos] = wordArray[pos + 1]; 
       wordArray[pos + 1] = temp; 
      } 
     } 
    } 
} 

public String[] getArray() 
{ 
    return wordArray; 
} 
} 

這是測試類。

package guis; 

import java.io.IOException; 
import javax.swing.JFrame; 

public class TestMouseClick 
{ 
public static void main(String[] args) throws IOException 
{ 
    MouseClick sample = new MouseClick(); 
    sample.setTitle("Assignment 2 - Hangman"); 
    sample.setSize(800, 750); 
    sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    sample.setVisible(true); 
} 
} 
+0

你在國家陣列中有什麼? – Omore

+0

這個國家是一個隨機的國家,作爲字符串從txt文件讀入。 – Gooner

回答

0

一個簡單的修正將獲得在使用charAt(0)方法,通過JButton的提示文本返回的字符串的第一個字符並將其分配給輸入:

char input = jButton26.getToolTipText().charAt(0); 

,或者你可能分裂它,使它更清晰:

String s = jButton26.getToolTipText(); 
char input = s.charAt(0); 

而且只是末端,代替手動編碼GUI鍵盤每個單獨的JButton,可以創建包含所有26不要的陣列然後創建按鈕並使用for循環附加偵聽器。這將顯着減少您必須編寫的代碼量。


新編輯:創建和設置大量類似的對象

(另外我注意到你創建了一個數組來存儲按鈕,以及一個buttonLetters陣列 - 這是沒有必要,除非你已經改變你的代碼來使用一組按鈕)

這裏需要注意的重要一點是ActionListener是Java中的一個對象,因此它可以被定義爲像任何其他類一樣存儲數據和其他方法定義。就個人而言,我寧願寫一個內部類,延伸ActionListener來存儲每個按鈕所代表的字母。

//define this inner class outside of the methods 
class KeyboardListener extends ActionListener { 
    //field type depends on your buttonLetters array (not sure if it is chars or Strings) 
    private final String letter; 

    public KeyboardListener(String letter) { 
     this.letter = letter; 
    } 

    public String getLetter() { 
     return letter; 
    } 

    @Override 
    public void actionPerformed(ActionEvent ae) { 
     //do something when button is clicked 
     //you can make use of the getLetter() method to retrieve the letter 
    } 
} 

//this goes in the for loop when creating each button 
    JButton btnX = new JButton(new KeyboardListener(buttonLetters[i])); 
    //add button to interface and anything else 

注:將JButton構造函數之一可以實現了Action接口(或在這種情況下,延伸ActionListener),以在創建時添加它,而不必調用addActionListener()任何類。

+0

感謝您的指點,我會在我的代碼中嘗試這些。感謝幫助。 – Gooner

+0

沒問題! :)你寫的越少越好! – PandaK

+0

所以我改變了添加按鈕的代碼,從單獨添加它們到使用循環來完成它。但是現在我不知道如何添加監聽器,這是我上面改變的代碼。 – Gooner