How do I get Java to perform an action so long as a button is pressed?

  • Context: Java 
  • Thread starter Thread starter Darkmisc
  • Start date Start date
  • Tags Tags
    Java
Click For Summary

Discussion Overview

The discussion revolves around how to modify a Java JButton action so that it continuously performs an action while the button is held down, specifically printing "Hello" to the console. Participants explore various approaches, including the use of MouseListeners and asynchronous tasks, while addressing the limitations of using System.out for this purpose.

Discussion Character

  • Exploratory
  • Technical explanation
  • Debate/contested
  • Homework-related

Main Points Raised

  • One participant suggests using a while loop to achieve continuous printing while the button is pressed, but notes that it continues printing even after the button is released.
  • Another participant recommends adding a MouseListener to the button to handle mouse press and release events, which would allow for starting and stopping actions appropriately.
  • Some participants express concerns that using System.out for printing may lead to performance issues due to buffering, suggesting that a GUI approach with a label would be more effective.
  • There is a discussion about the suitability of different programming environments for game development, with some advocating for the Processing IDE for its simplicity and ease of use compared to Java GUI.
  • One participant mentions the use of onKeyUp and onKeyPressed commands in JavaScript, suggesting that similar functionality might exist in Java's MouseEvent handling.
  • Several participants share differing opinions on whether to use Processing or traditional Java GUI for game development, citing the learning curve and available resources.

Areas of Agreement / Disagreement

Participants do not reach a consensus on the best approach to implement the desired functionality. There are multiple competing views regarding the use of MouseListeners, System.out, and the choice of development environment for game programming.

Contextual Notes

Some participants highlight the limitations of using System.out for rapid output and the potential for buffering issues. There are also discussions about the learning curves associated with different programming environments and the impact on game development.

Who May Find This Useful

This discussion may be useful for individuals interested in Java programming, particularly those looking to implement interactive GUI elements or develop simple games.

Darkmisc
Messages
222
Reaction score
31
TL;DR
I'm trying to get Java to perform an action when a button is held and stop as soon as the button is released. Instead, Java continues the action long after the button is released. How do I fix this?
Hi everyone

I got the code below from YouTuber, Bro Code. It prints "Hello" every time you click on the button.

I wanted the button to print "Hello" while it was held down and stop printing as soon as the button was released, so I changed this line

if(e.getSource()==button)

to

while(e.getSource()==button)

What happens now is that it will print "Hello" many times from one click. It will continue printing long after I've released the button (I don't know for how long. I stop the program half-way).

How can I change the code so that it will stop printing as soon as I release the button?Thanks

EDIT: I get the same result when I use a do/while loop.

Java:
import java.awt.event.*;
import javax.swing.*;

public class MyFrame extends JFrame implements ActionListener{

    JButton button;
    JLabel label;
  
    MyFrame(){
      
        ImageIcon icon = new ImageIcon("point.png");
        ImageIcon icon2 = new ImageIcon("face.png");
      
        label = new JLabel();
        label.setIcon(icon2);
        label.setBounds(150, 250, 150, 150);
        label.setVisible(false);
      
        button = new JButton();
        button.setBounds(100, 100, 250, 100);
        button.addActionListener(this);
        button.setText("I'm a button!");
      
        button.setFocusable(false);
        button.setIcon(icon);
        button.setHorizontalTextPosition(JButton.CENTER);
        button.setVerticalTextPosition(JButton.BOTTOM);
        button.setFont(new Font("Comic Sans",Font.BOLD,25));
        button.setIconTextGap(-15);
        button.setForeground(Color.cyan);
        button.setBackground(Color.lightGray);
        button.setBorder(BorderFactory.createEtchedBorder());
      
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(null);
        this.setSize(500,500);
        this.setVisible(true);
        this.add(button);
        this.add(label);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==button) {
            System.out.println("Hello");
            label.setVisible(true);
        }  
    }
}
<Moderator's note: please put code within CODE tags.>
 
Last edited by a moderator:
Technology news on Phys.org
System.out is not suitable for this.

I don't know who "You Tuber Bro Code" is (and I don't want to know) but I suggest you use a more structured resource. What is your main objective in learning Java?
 
  • Like
Likes   Reactions: Darkmisc
Darkmisc said:
I wanted the button to print "Hello" while it was held down and stop printing as soon as the button was released
The way to do this is to add a MouseListener to your button. When you receive the onPressed(MouseEvent) event in the listener, you start an asynchronous job, and stop the synchronous job when you receive onRelease(MouseEvent). Refer to this answer on Stack Overflow.
 
  • Like
Likes   Reactions: Darkmisc, phinds and Nugatory
The default action for a JButton is 'Click' which corresponds to a button being pressed AND released. You need to listen to MouseEvent.

I found this little piece of code that might be helpful:
https://stackoverflow.com/questions/50796297/how-can-i-get-mouse-pressed-event-in-java-on-a-button#50796358 said:
Try this.
Java:
JButton button = new JButton("Click!");

button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.NOBUTTON) {
textArea.setText("No button clicked...");
} else if (e.getButton() == MouseEvent.BUTTON1) {
textArea.setText("Button 1 clicked...");
    }

  }
});
See available methods
Hope this help!
 
  • Like
Likes   Reactions: Darkmisc
Neither of these are going to help if you just keep spewing out text to the console as fast as you can loop.
 
  • Like
Likes   Reactions: Darkmisc
@pbuk is right, using System.out is the wrong way to print hello in this instance with dynamic mouse control. It means you're printing out faster than the computer can actually display it so System.out buffers the hellos and only when the print buffer is empty will it stop.

If you were to instead use a GUI approach with a label where you showed the label when you started and hid the label when you released the button then you'd see the behavior expected.
 
  • Like
Likes   Reactions: Wrichik Basu, pbuk and Darkmisc
pbuk said:
System.out is not suitable for this.

I don't know who "You Tuber Bro Code" is (and I don't want to know) but I suggest you use a more structured resource. What is your main objective in learning Java?
I'd like to start making simple games.
 
pbuk said:
Neither of these are going to help if you just keep spewing out text to the console as fast as you can loop.
System.out.println was supposed to be a stand-in for another action. I didn't realise Java would buffer it. I wanted to use it for something like charging up a weapon before firing it.
 
jack action said:
The default action for a JButton is 'Click' which corresponds to a button being pressed AND released. You need to listen to MouseEvent.

I found this little piece of code that might be helpful:
Thanks. That's pretty much what I was hoping for.
 
  • #10
Darkmisc said:
I'd like to start making simple games.
Darkmisc said:
System.out.println was supposed to be a stand-in for another action. I didn't realise Java would buffer it. I wanted to use it for something like charging up a weapon before firing it.
You'll probably want to use a game loop.
 
  • Like
Likes   Reactions: Darkmisc
  • #11
In Javascript, there is an onKeyUp command that I've used in some situations like this. I used the onKeyPressed to start the desired process and then onKeyUp to stop it. I haven't used JButtons for a long time but I would think that there would be a similar capability in that or the MouseEvent that @jack action suggested.
 
  • Like
Likes   Reactions: Darkmisc
  • #12
Darkmisc said:
I'd like to start making simple games.
The best approach for simple games would be to use the Processing IDE. The latest incarnation is Processing 4. The basic program design is a setup() and draw(). Setup() is called once to initialize things whereas draw() is called every thirtieth of a second.

Coding is done using java and it provides easy access to the mouse coordinates and buttons.

I’ve done a couple of simple games with it. One was a variation of tic-tac-toe and the other was a simulation of the ESR think-a-dot toy.
 
  • Like
Likes   Reactions: Darkmisc
  • #13
jedishrfu said:
The best approach for simple games would be to use the Processing IDE. The latest incarnation is Processing 4. The basic program design is a setup() and draw(). Setup() is called once to initialize things whereas draw() is called every thirtieth of a second.

Coding is done using java and it provides easy access to the mouse coordinates and buttons.
I have a different opinion on this. If the OP is trying to learn Java GUI, then it will be better if they create the games bare hand (or using third-party libraries, where necessary). This will give far better exposure to controlling events and async tasks. Thereafter, if the OP moves on to something like Android, this experience will be immensely helpful.

It appears that Processing IDE is created keeping in mind the Arduino system, where we have void setup() and void loop(), and they function the same way as what you describe.
 
  • Like
Likes   Reactions: Darkmisc
  • #14
Arduino liked the processing IDE model and borrowed the setup/loop sketch notion from them.
 
  • #15
in my experience the learning curve to get to a game via the Java GUI is much steeper than with Processing. Also Processing has many third party libs that can be tapped for use in a game and can package the game for Windows, Macos or Linux.

They can still utilize Java GUI within their sketch for secondary windows or can use the third party ControlP5 library with a more game like GUI.

in any event, I’m sure the OP can decide this from our post discussion list of pros and cons. @Wrichik Basu it was good to bring it up.

Going the full Java GUI route then Netbeans might be a good choice. It’s arguably more complex to work with but does have Matisse which helps you graphically design your GUI. Again though this approach has an even steeper learning curve as your game around Matisse code can be vexing depending on the nature of the game.

I worked on a project where Matisse was used extensively with custom GUI widgets building very complex Java apps. It was tough at first to understand what was going on and how to handle buttons, textfields, radio selectors…
 
  • Like
Likes   Reactions: Wrichik Basu

Similar threads

  • · Replies 6 ·
Replies
6
Views
3K