我正在尝试在基于GUI的Hangman游戏中使用基于JButton的键盘。但是,当我想检查按下的键是否在隐藏的单词中时,我不确定在哪里需要将类型从String更改为char。我想使用基于GUI的键盘,而不是允许用户使用键盘,尝试最小化需要完成的验证。这些是我到目前为止创建的类。我正在努力让这个工作。
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 :(得分:0)
一个简单的解决方法是使用charAt(0)
方法获取JButton工具提示文本返回的String中的第一个字符并将其分配给输入:
char input = jButton26.getToolTipText().charAt(0);
或者您可以将其拆分以使其更清晰:
String s = jButton26.getToolTipText();
char input = s.charAt(0);
同样只是一个提示,您可以创建一个包含所有26个字母的数组,然后创建按钮并使用for循环附加侦听器,而不是手动编写GUI键盘的每个JButton。这将显着减少您必须编写的代码量。
新编辑:创建和设置大量类似对象
(另外我注意到你创建了一个数组来存储按钮以及一个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()