Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9030095
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T07:24:17+00:00 2026-06-16T07:24:17+00:00

Possible Duplicate: Java hangman game with gui, problems with incrementing/decrementing numbers So the problem

  • 0

Possible Duplicate:
Java hangman game with gui, problems with incrementing/decrementing numbers

So the problem is that I suck at swing, have no idea how to work with the keylistener, which starts listening to the keys too many times (2 keys recorded after 2nd game, 3 keys after 3rd and so on). I do not know how to work with the Event Dispatch Thread properly or should I even use it, and the won/lost count increments wrongly. Moreover, when i want the frame to listen to keyboard input i request its focus in window, but I don’t know how to unfocus it when I dont want the frame to read keyboard input. Any help is welcome. This is my second time asking this question, and hopefully I have made the program and the problem a bit more comprehensible this time. EDIT: game now works, also with added bufferedwriter that writes a log file. Sorry, was too lazy to change some naming parts of the code to English, as they are in Lithuanian.

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();
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T07:24:18+00:00Added an answer on June 16, 2026 at 7:24 am

    Some hints to get you on the right track:

    1. You’re adding a key listener to the frame in the actionPerformed() method. This means that each time the button is clicked, a new key listener is added to the frame. The key listener should be added once, and only once, when the frame is initialized.

    2. If you don’t want to listen on key presses, then you could just set a keyTypedIgnored flag to true. In the key listener, if this flag is true, you ignore the event. And if it’s set to false, then you do something.

    3. Regarding the EDT, yes, all swing interactions should be done on the EDT. The Runnable should be invoked using SwingUtilities.invokeLater(runnable), as explained in the Swing tutorial.

    And finally, maybe the most important advice, don’t do everything in a single giant method. Separate the code in objects and methods doing a specifc task. Add some blank lines to make the code readable. Indent the code properly.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: Java GUI repaint() problem? I write a Java code, but I have
Possible Duplicate: Java - Regex problem I have list of URLs of types: http://www.example.com/pk/etc
Possible Duplicate: Java garbage collection I know that we have to free object in
Possible Duplicate: Java string comparison? I have encounter the following problem, I have an
Possible Duplicate: Java, GUI builder or hand coding? I have been making GUI hand-coded
Possible Duplicate: Java Compare Two Lists If I have two ordered sequences of numbers
Possible Duplicate: Java: recommended solution for deep cloning/copying an instance I have an object
Possible Duplicate: Java: how to check that a string is parsable to a double?
Possible Duplicate: java String concatenation Sources tell us that concat is implemented as follows:
Possible Duplicate: Java 7 Date/Time API I've read rumors that Joda Time is slated

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.