-2

可能重复:
带有 gui 的 Java 刽子手游戏,增加/减少数字的问题

所以问题是我挥杆很烂,不知道如何使用keylistener,它开始听键太多次(第二场比赛后录制2个键,第三场后录制3个键,依此类推)。我不知道如何正确使用 Event Dispatch Thread,或者我什至应该使用它,并且赢/输计数错误地递增。此外,当我希望框架听键盘输入时,我请求它在窗口中的焦点,但是当我不希望框架读取键盘输入时,我不知道如何取消焦点。欢迎任何帮助。这是我第二次问这个问题,希望这次我让程序和问题更容易理解。编辑:游戏现在可以工作,还添加了写入日志文件的缓冲写入器。抱歉,懒得将代码的某些命名部分更改为英文,因为它们是立陶宛语。

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;

public class Hangman {

    static int won = 0;
    static int lost = 0;
    static String key = "";
    static String word = null;
    static int no = 0;
    static StringBuffer toguess;
    static KeyboardFocusManager manager;
    static Runnable hangman;
    static ArrayList<String> tried;
    static int gamecount = 0;

    @SuppressWarnings("resource")
    public static void main(String[] args) throws IOException {
        FileWriter filewriter = new FileWriter("rezultatai.txt", true);
        final BufferedWriter writer = new BufferedWriter(filewriter);
        final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        final Date date = new Date();
        hangman = new Runnable() {

            public void run() {
                final JFrame frame = new JFrame();
                frame.setLayout(new GridLayout(4, 1));
                final JLabel label = new JLabel();
                label.setFont(new Font("Serif", Font.BOLD, 48));
                label.setForeground(Color.GREEN);
                label.setText("Kaledines kartuves");
                final JPanel panel1 = new JPanel();
                final JPanel panel2 = new JPanel();
                final JPanel panel3 = new JPanel();
                final JPanel panel4 = new JPanel();
                final JLabel label3 = new JLabel();
                panel1.add(label);
                panel4.add(label3);
                final JLabel label2 = new JLabel();
                frame.setVisible(true);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                final JButton button = new JButton("Pradeti");
                panel2.add(button);
                frame.add(panel1);
                frame.add(panel2);
                frame.add(panel3);
                frame.setSize(800, 600);
                button.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        gamecount = gamecount + 1;
                        no = 0;
                        label3.setText("6 tries left");
                        frame.add(panel4);
                        frame.setFocusable(true);
                        frame.requestFocusInWindow();
                        label2.setText("won " + won + ", lost " + lost);
                        panel3.add(label2);
                        button.setText("Sekantis");
                        BufferedReader reader = null;
                        try {
                            reader = new BufferedReader(new FileReader("hangeng.txt"));
                        } catch (FileNotFoundException e1) {
                            e1.printStackTrace();
                        }
                        int lineno = (int) (Math.random() * 167);
                        for (int i = 0; i < lineno; i++) {
                            try {
                                reader.readLine();
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                        }
                        word = null;
                        try {
                            word = reader.readLine().replace(" ", "");
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                        String missing = "";
                        for (int u = 0; u < (word.length() - 2); u++) {
                            missing = missing + "*";
                        }
                        final String guess = word.charAt(0) + missing
                                + word.charAt((word.length() - 1));
                        toguess = new StringBuffer(guess);
                        label.setText(toguess.toString());
                        tried = new ArrayList<String>();
                    }
                });
                frame.addKeyListener(new KeyListener() {

                    @Override
                    public void keyPressed(KeyEvent e) {
                    }

                    @Override
                    public void keyReleased(KeyEvent e) {
                    }

                    @Override
                    public void keyTyped(KeyEvent e) {
                        if ((no == 6) && (!(toguess.toString().equals(word)))) {
                            frame.setFocusable(false);
                            button.requestFocusInWindow();
                            label.setText("Deja, bet zodis buvo " + word);
                            lost = lost + 1;
                        }
                        key = String.valueOf(e.getKeyChar());
                        String guessing = key;
                        Boolean k = false;
                        if ((no < 6)) {
                            k = false;
                            if (!(tried.contains(guessing))) {
                                tried.add(guessing);
                                for (int length = 1; length < (word.length()
                                        - 1); length++) {
                                    if (guessing.equals(word.substring(length,
                                            (length + 1)))) {
                                        toguess.replace(length, (length + 1),
                                                String.valueOf(word.charAt(length)));
                                        k = true;
                                    }
                                }
                                if (k == false) {
                                    no = no + 1;
                                }
                            }
                            label.setText(toguess.toString());
                            if (toguess.toString().equals(word)) {
                                label.setText("Teisingai! Zodis buvo " + word);
                                frame.setFocusable(false);
                                button.requestFocusInWindow();
                                no = 6;
                                won = won + 1;
                            }
                        }
                        label3.setText((6 - no) + " tries left");
                    }
                });
                frame.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                        try {
                            writer.write(System.getProperty("line.separator")
                                    + dateFormat.format(date)
                                    + System.getProperty("line.separator")
                                    + (gamecount - 1) + " games played, "
                                    + lost + " lost " + won + " won");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        try {
                            writer.flush();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        try {
                            writer.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        };
        hangman.run();
    }
}
4

1 回答 1

3

一些让你走上正轨的提示:

  1. 您正在向actionPerformed()方法中的框架添加一个关键侦听器。这意味着每次单击按钮时,都会将一个新的键侦听器添加到框架中。当初始化框架时,应该添加一次关键侦听器,并且只添加一次。

  2. 如果您不想听按键,那么您可以将keyTypedIgnored标志设置为 true。在键侦听器中,如果此标志为真,则忽略该事件。如果它设置为假,那么你做一些事情。

  3. 关于 EDT,是的,所有挥杆交互都应该在 EDT 上完成。应该使用 调用 Runnable SwingUtilities.invokeLater(runnable),如Swing 教程中所述。

最后,也许是最重要的建议,不要用单一的巨大方法做所有事情。将执行特定任务的对象和方法中的代码分开。添加一些空白行以使代码可读。正确缩进代码。

于 2012-12-25T20:01:21.197 回答