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 7954161
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T03:20:33+00:00 2026-06-04T03:20:33+00:00

I have an application in which it would be very convenient for me to

  • 0

I have an application in which it would be very convenient for me to have a mouse click event emulate a user typing in a certain string to standard input. So I was wondering, is there a way in code to WRITE to standard in? I realize it’s a bit of a hack, but it would work very well for what I need to do.

EDIT (in response to Hovercraft’s EDIT2):

Thanks. I understand how that code keeps the human player from moving a piece when they shouldn’t. What I don’t understand is how you are envisioning the main game loop. Would you mind writing code to show me what you’re thinking for that? Are you just picturing a busy-wait loop that constantly generates new computer moves and calls your Move() method (most of the time being rejected while it’s waiting for the human player to make a move)? Something like this?

public void gameLoop()
{
   while (gameNotOver)
   {
      Move compMove = generateComputersNextMove();
      move(blackPlayer, compMove); // where the blackPlayer is the computerPlayer 
   }
}
  • 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-04T03:20:34+00:00Added an answer on June 4, 2026 at 3:20 am

    You state:

    Basically, I want my code to block at a certain point and wait for the user to click a specific JLabel in my JFrame. Once the user clicks a JLabel, I want the code to resume, after getting the id of the JLabel that was clicked. I’m not sure how I would go about doing this. The way I had it before was that at that point in the code, the user would just type in an id (and Scanner’s next() method blocks for you).

    You don’t want to block your program (not in an event-driven program) so much as change the state of your GUI, and base your response to user’s input on this state. Your attempted solution is a linear way of thinking, and doesn’t work well with Swing or other event driven GUI’s.

    For instance as a simple example consider giving your program a boolean variable,

    private boolean labelClicked = false;
    

    And change this to true in the JLabel’s MouseListener after the JLabel has been clicked. Then only respond to other user input if the boolean is true.

    Or another possible solution: if you want to activate a JButton after a JLabel has been pressed, then make the JButton disabled, and call setEnabled(true) on the JButton from within the JLabel’s MouseListener.

    The key is to think Event-Driven Programming.
    The other key when asking questions like this in this forum is not to ask us a code-specific question, but rather a behavior-specific question. The true question here is not how to write to the standard in, but rather how to get your program to pause and await user input — that’s a big difference.

    Finally, if you need more specific and better recommendations, please fill us in on the details of your problem, and certainly ask questions if any of this is confusing. Best of luck!

    Edit 1
    You’re likely going to have several classes including GUI and non-GUI classes managing this application, and the non-GUI classes can include:

    • Player class: this can be either human or computer
    • Board class: the logical (non-gui) representation of the chess board
    • Piece class: abstract class that all the concrete Pieces derive from
    • ChessAI class: this is your AI class, the one that figures out for the computer what the next best move should be.
    • Game class: perhaps the most important class for this discussion as this will control game flow and decide whose turn it is to move.

    The Game class will have fields including a Player field called turn that will hold a reference to whoever’s turn it is. So say your Game class holds two Player variables, humanPlayer and computerPlayer. The turn variable will hold one or the other of these objects, and how Player responds will depend on what object is held by turn.

    The Game class will have a loop of sorts, a game loop, that alternates between telling the humanPlayer object and the computerPlayer object that its their turn to move.

    So say its the computer’s turn, and it is taking a while to calculate the next best move. If meanwhile the human player tries to drag a chess piece on the GUI, the GUI will inform the Game class of the human’s attempt to move, the Game class will check if it’s the human’s turn (by checking if (turn == humanPlayer)) and if it’s not the human’s turn, Game will inform the GUI this, and the GUI will set the piece back to where it was and perhaps pop up a warning message.

    After the computer has requested Game to move its piece, Game will tell the GUI to move the computer’s piece, and then Game will set turn = humanPlayer, now allowing the human player to move. After humanPlayer tries to move, the GUI will tell Game of the human’s attempted move. Game will check if its a valid move, and if so, will tell computerPlayer that it should now make a move.

    Note that when I say “tell”, I mean that it will call a public method on that object.

    Edit 2
    I mean something sort of like this:

    public class Game {
       private Player whitePlayer;
       private Player blackPlayer;
       private Player turn;
       private Board board = new Board(); // non-GUI logical board
       private Gui gui; // the Swing GUI that displays all
    
       public Game(String humanPlayerName, boolean humanWhite) {
          if (humanWhite) {
             whitePlayer = new HumanPlayer(humanPlayerName, this);
             blackPlayer = new ComputerPlayer("Computer", this);
          } else {
             whitePlayer = new ComputerPlayer("Computer", this);
             blackPlayer = new HumanPlayer(humanPlayerName, this);
          }
       }
    
       public void start() {
          whitePlayer.setMyTurn(true); // tell white player to move
       }
    
       public void move(Player playerMakingMove, Move move) {
    
          // only respond if the right player is making the move
          if (turn == playerMakingMove) {
             // check if its a valid move
             // if so, tell GUI to make move
             // check if game over
    
             turn.setMyTurn(false); // current player's turn is over
             turn = (turn == blackPlayer) ? whitePlayer : blackPlayer; // swap players
             turn.setMyTurn(true); // tell other player, it's his turn
    
             turn.makeMove(); // *** added
          } else {
             // send message that it's not their turn to move
          }
       }
    }
    

    So if the human player tries to move the GUI will move(…) for the human player, but the Game object won’t respond unless it is in fact the human’s turn.

    Edit 3
    makeMove() method added to Player
    Note that the Game’s move(...) method may be all the game loop that is needed, especially if the ComputerPlayer’s makeMove(...) method tells the AI engine to create the next best move and then calls Game’s move(…) method again:

    abstract class Player {
       private String name;
       private boolean myTurn = false;
       protected Game game;
    
       public Player(String name, Game game) {
          this.name = name;
          this.game = game;
       }
    
       public abstract void makeMove();
    
       public boolean isMyTurn() {
          return myTurn;
       }
    
       public void setMyTurn(boolean myTurn) {
          this.myTurn = myTurn;
       }
    
       public String getName() {
          return name;
       }
    
    }
    
    class HumanPlayer extends Player {
    
       public HumanPlayer(String name, Game game) {
          super(name, game);
       }
    
       @Override
       public void makeMove() {
          // TODO: ask GUI to inform player that it's his turn to move and accept the move
    
       }
    
    
    }
    
    class ComputerPlayer extends Player {
       private ChessAi chessAi = new ChessAi();
    
       public ComputerPlayer(String name, Game game) {
          super(name, game);
       }
    
       @Override
       public void makeMove() {
          game.move(this, chessAi.calcBestMove());
       }
    
    }
    

    Both players would call game.move(...) when they have figured out the move, which makes the Game prompt the next player to move…. until game is over.

    Note, that this is not a running program and not meant to be, but more of a mock-up to illustrate possible game logic. I’ve not done something like this, and there are probably better and cleaner ways to do this, but I just want to get the point across of ways of implementing turn-based logic in an event-driven GUI program.

    Edit 4
    Compile and run the following simple event driven GUI:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class EventDrivenGui extends JPanel {
       private static final Color GO_COLOR = Color.green;
       private static final Color STOP_COLOR = Color.red;
       private static final int SIDE = 300;
       private static final int TIMER_DELAY = 4 * 1000; // change light every 4 seconds
       private boolean go = false;
       private JButton button = new JButton("Button");
    
    
       public EventDrivenGui() {
          add(button);
          button.addActionListener(new ButtonListener());
          new Timer(TIMER_DELAY, new TimerListener()).start();
       }
    
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D) g;
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
    
          Color color = go ? GO_COLOR : STOP_COLOR;
          g2.setColor(color);
          g2.fillOval(0, SIDE / 3, SIDE, SIDE);
       }
    
       @Override
       public Dimension getPreferredSize() {
          return new Dimension(SIDE, (4 * SIDE) / 3);
       }
    
       private class ButtonListener implements ActionListener {
          @Override
          public void actionPerformed(ActionEvent arg0) {
             if (go) {
                JOptionPane.showMessageDialog(EventDrivenGui.this, "Button is Active");
             }
          }
       }
    
       private class TimerListener implements ActionListener {
          @Override
          public void actionPerformed(ActionEvent e) {
             // toggle go. if true, now false, and visa versa
             go = !go;
             repaint(); // redraw oval
          }
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                EventDrivenGui mainPanel = new EventDrivenGui();
    
                JFrame frame = new JFrame("EventDrivenGui");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.getContentPane().add(mainPanel);
                frame.pack();
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
             }
          });
       }
    
    }
    

    You’ll see that there’s a JButton held in a JPanel. You as the user can press the button any time you’d like, but it will only respond when the light is green (when the go boolean variable is true). This is one example where the button’s behavior, whether it responds to presses or not, depends on the state of the class, whether go is true or not. Once the GUI is set up — the constructor has been called, it has been placed in a JFrame, and is displayed, there’s no code that blocks or anything like that. There’s a Swing Timer whose only job is to toggle go’s value and repaint the JFrame, but that’s it.

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

Sidebar

Related Questions

I have an application in which I would like to support multiple orientations. I
I have a c++ console application which I would like to publish using clickonce.
I have an application which takes time to load so i would like to
I am writing a little application in android which would have a server part
I would like to develop an Android application which will have a local database.
I am thinking of making an (initially) small Web Application, which would eventually have
I am new to iPhone world. I have developed an application, which I would
I would like to deplay a django application/project, which i have created within Aptana.
I have a very simple problem. I have an application which is written in
I have an application in which a user can pass in some or all

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.