Trying to perform an action when a button is pressed - java

I am trying to make a game and I made a Button class using the JButton library.
This code is in the button class:
#Override public void mouseClicked(MouseEvent e) { pressed = true; }
public boolean getPressed(){
return pressed;
}
Then in the main java file:
Button playButton = new Button("PLAY", frame);
frame.add(playButton);
while (true){
if (playButton.getPressed())
System.out.println("test");
}
It never seems to print test even though I checked and the boolean value is being changed

I am unfamiliar with JButton. But it seems that in your if statement in your while loop, there is no condition. Please reply if this helps!

Related

Is there a way to detect button click in another method?

Like
#FXML
void start() {
// for game loop
while(!winning) {
if (attack.clicked()) attack();
else if (defend.clicked()) defend();
}
}
Can it possible to do this? Thanks.
You can assisgn true or false to a flag when when button click(at the button's click handler method). Your sintax may be different at click handler, but your code like this.
private boolean isAttackButtonClicked = false;
public void attackButtonclickHandler(ClickEvent e){
...
isAttackButtonClicked = true;
...
}

java addActionListener not working

I am trying to make it easier to make buttons by making a method, but when i use the method to make a button nothing happens when i press the button, even though i have a listener for the button
public void assignButton(Button wtf,String text) //program to assign buttons easily
{
wtf = new Button(text);
add(wtf);
wtf.addActionListener(this);
}
i use assignButton(Check,"words"); to make the button
public void actionPerformed(ActionEvent event) //checks if button has been pressed
{
if(event.getSource() == Check)
{
code ++;
}
else
{
code = 2;
}
repaint();
every time i press the button it sets code to 2, anyone know what i am doing wrong?
Edit:
full code
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class PressSafeTemp extends Applet implements ActionListener
{
Button clear,Check;
int code = 0;
public void init() //assigns buttons
{
clear = new Button("C");
add(clear);
clear.addActionListener(this);
assignButton(Check,"words");
}
public void paint(Graphics g)
{
g.drawString(""+code,10,10);
}
public void assignButton(Button wtf,String text) //program to assign buttons easily
{
wtf = new Button(text);
add(wtf);
wtf.addActionListener(this);
}
public void actionPerformed(ActionEvent event) //checks if button has been pressed
{
if(event.getSource() == Check)
{
code ++;
}
else if(event.getSource() == clear)
{
code = 0;
}
else
{
code = 2;
}
repaint();
}
}
The problem is you pass Check to the method (as wtf) but then immediately set it to a new instance; this instance is not Check. It does get added but you can't get at it with Check.
You probably want to do...
Button getButton(String text) {
Button button = new Button(text);
button.addActionListener(this);
return button;
}
and then Check = getButton(someText); followed by add(Check);.
If you don't actually need Check laying around, you could also just add it directly with add(getButton(someText));.
I'm not sure what means for you event.getSource() == Check but that is the key, you need to check the correct comparison in your case. Something like for example:
event.getSource().class.equals(JCheckBox.class)

Do while loops in Java not check their conditions if there is no body?

In this example I have a simple JFrame containing a JButton with an ActionListener tied to it. This AcitonListener just changes a boolean flag that should allow the program to complete.
public class Test {
public static void main(String[] args){
final boolean[] flag = new boolean[1];
flag[0] = false;
JFrame myFrame = new JFrame("Test");
JButton myButton = new JButton("Click Me!");
myButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Button was clicked!");
flag[0] = true;
}
});
myFrame.add(myButton);
myFrame.setSize(128,128);
myFrame.setVisible(true);
System.out.println("Waiting");
while(!flag[0]){}
System.out.println("Finished");
}
}
This never prints "Finished", and after the button has been clicked once prints
Waiting
Button was clicked!
However, if I modify the while loop to read
while(!flag[0]){
System.out.println("I should do nothing. I am just a print statement.");
}
This works! The printout looks like
Waiting
I should do nothing. I am just a print statement.
I should do nothing. I am just a print statement.
....
I should do nothing. I am just a print statement.
Button was clicked!
Finished
I understand this probably isn't the proper way to wait on an action, but nonetheless I am interested in knowing why Java behaves this way.
The likeliest reason is that flag[0] = true; is executed on the UI thread, whereas while(!flag[0]) is executed on the main thread.
Without synchronization, there is no guarantee that the change made in the UI thread will be visible from the main thread.
By adding the System.out.println you introduce a synchronization point (because the println method is synchronized) and the problem gets solved.
You could make flag a volatile instance or class boolean variable (not an array), or, more simply, put whatever code you want executed on the button being pressed in the listener itself.
For reference, the code with a volatile variable would look like this:
private static volatile boolean flag;
public static void main(String[] args) {
JFrame myFrame = new JFrame("Test");
JButton myButton = new JButton("Click Me!");
myButton.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent arg0) {
System.out.println("Button was clicked!");
flag = true;
}
});
myFrame.add(myButton);
myFrame.setSize(128, 128);
myFrame.setVisible(true);
System.out.println("Waiting");
while (!flag) { }
System.out.println("Finished");
}

Check Button is Click in different class in Java

i had two classes, one is Main.java another is Button.java
So in Main.java, i need to confirm while Jbutton in Button.java is clicked, then Main.java will do something
in Button.java
public void actionPerformed(ActionEvent e) {
if(e.getSource()==Jsend)
{
String userinput = Jusertxt.getText();
setUserText(userinput);//setUserText is a method for Main.java can get a String from user input.
Jusertxt.setText("");
}
}
what is the statement i need to write in Main.java to check button is clicked in Button.java?
here is some code in Main.java
while(true){
if(//in here i need to ensure button is clicked){
} }
To receive notification button is pressed, you must register listener in Main.java. With it you can synchronize a local variable to store the status of the button (if it is clicked). This variable can use later to determine whether the button is pressed (once).
Edit Another option is the variable part of Button.java and to implement a public method isClicked()
Put a boolean value within the button, use a getter to retrieve the value of the boolean e.g
Example :
//Within main
Button button = new Button(); // I wouldn't recommend using button as a
class name by the way, will get very confusing
if(button.getPressed){
// do stuff
}
Your button code:
public void actionPerformed(ActionEvent e) {
if(e.getSource()==Jsend)
{
String userinput = Jusertxt.getText();
setUserText(userinput);//setUserText is a method for Main.java can get a String from user input.
Jusertxt.setText("");
isPressed = true;
}
}
public boolean getPressed(){
return isPressed;
}

Count number of button clicks in given time

JButton btnNewButton = new JButton("CLICK ME!");
btnNewButton.setBounds(134, 142, 274, 77);
btnNewButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
clicked++;
String x=Integer.toString(clicked);
textArea.setText(x);
}
});
I'm stuck here I want to create a program in GUI that counts the number of button click in specific time for example the timer start then count the number of clicks when the loop stop the button click is not working or stop counting the clicks
There are two possible solution
1.Make the button clickable when timer starts and unclickable when timer stops
Or
2.also u can use flag to check whether timer is running Or not.If timer is running make flag true when gets over make it false. Somthing like below snipet
public void actionPerformed(ActionEvent e) {
if (flag) {
clicked++;
String x=Integer.toString(clicked);
textArea.setText(x);
}
else
{
// doSomething
}
}
You can have some boolean variable which says if it's time for clicking (set on true when timer is started and on false when time's up). Then count clicks when this variable is true:
public void actionPerformed(ActionEvent e) {
if (timeIsRunning) {
clicked++;
String x=Integer.toString(clicked);
textArea.setText(x);
}
}
https://stackoverflow.com/a/9413767/1306811
Have a click counter.
private int clickCounter = 0; // as an example
Create get/set methods for it.
Add a MouseListener to your JButton so you can effectively track click events (MouseEvent arg0, arg0.getClickCount(), etc). At the end of each call to mouseClicked increment the clickCounter (clickCounter += arg0.getClickCount(), as an example).
Modify the answer linked so that clickCounter is set to 0 at every "time step" (however long you want it to be).
Voila.

Categories