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

  • Java
  • Thread starter Darkmisc
  • Start date
  • Tags
    Java
In summary, the conversation discusses how to modify a Java code to print "Hello" while a button is held down and stop printing when the button is released. Suggestions include using a MouseListener, adding a key press and release event, and using the Processing IDE for game development.
  • #1
Darkmisc
204
27
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
  • #2
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 Darkmisc
  • #3
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
  • #4
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 Darkmisc
  • #5
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 Darkmisc
  • #6
@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
  • #7
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.
 
  • #8
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.
 
  • #9
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 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 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 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 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 Wrichik Basu

1. How do I create a button in Java?

In order to create a button in Java, you can use the JButton class from the javax.swing package. First, create an instance of the JButton class and then add it to your user interface using a layout manager.

2. How can I detect when a button is pressed in Java?

In order to detect when a button is pressed, you can use an ActionListener. This interface has a method called actionPerformed() that will be called whenever the button is clicked. You can add this ActionListener to your button using the addActionListener() method.

3. How can I make an action repeat as long as the button is pressed?

In order to make an action repeat as long as the button is pressed, you can use a while loop inside the actionPerformed() method. The condition of the while loop can be set to check whether the button is still being pressed. This way, the action will continue to repeat until the button is released.

4. Can I change the action that is performed when the button is pressed?

Yes, you can change the action that is performed when the button is pressed by changing the code inside the actionPerformed() method. This method is where the action is defined, so you can add or remove code to modify the action that is performed.

5. How do I stop the action when the button is released?

In order to stop the action when the button is released, you can use a flag variable inside the actionPerformed() method. The flag can be set to true when the button is pressed and then set to false when the button is released. You can use this flag to control the execution of the action code.

Similar threads

  • Programming and Computer Science
Replies
6
Views
2K
Back
Top