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

  • Thread starter Thread starter Darkmisc
  • Start date Start date
  • Tags Tags
    Java
AI Thread Summary
To achieve continuous action while a button is pressed in Java, a MouseListener should be added to detect mouse press and release events, rather than relying solely on ActionListener, which only responds to button clicks. The current implementation using a while loop causes excessive output due to rapid execution, as System.out buffers the output, leading to delayed stopping of the print action. A suggested alternative is to use a GUI component like a JLabel to visually represent the action instead of printing to the console. For game development, using the Processing IDE is recommended for its simpler structure and better handling of mouse events. Ultimately, the choice between using Java GUI or Processing depends on the user's learning goals and preferences.
Darkmisc
Messages
222
Reaction score
31
TL;DR Summary
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?
 
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 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!
 
Neither of these are going to help if you just keep spewing out text to the console as fast as you can loop.
 
@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 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.
 
  • #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.
 
  • #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.
 
  • #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.
 
  • #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 Wrichik Basu

Similar threads

Replies
6
Views
3K
Back
Top