- #1
Darkmisc
- 220
- 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.
<Moderator's note: please put code within CODE tags.>
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);
}
}
}
Last edited by a moderator: