Java btn.getclicked?

jpmasta12666

Baseband Member
Messages
26
Location
Canada
So im making a trivia game and im stuck on a part

Im trying to make it so if the btnAnswer1.getClicked
lblAnswer.setText("Incorrect")

The problem is the btnAnswer1.getClicked isn't functional Do I have the wrong code?

if so what is the correct code to make this function
 

Celegorm

Site Team
Staff member
Messages
11,741
Location
USA
usually the syntax is some form of "onClick(Event e)" for the function. If I'm correct that'll varry a bit based on what GUI library you are using but that should be the jist of it.
 

berry120

Fully Optimized
Messages
3,434
Location
UK
Nowhere near enough information here to answer this - you need to post the exact code you're using!
 

jpmasta12666

Baseband Member
Messages
26
Location
Canada
I am using the graphic designer.
here's the code:
int roll;
roll = (int)((3 -1 +1)*Math.random() +1);
if(roll==1){
lblQuestion.setText("What is a jump on a skateboard called?");
btnAnswer1.setText("Ollie");
if(btnAnswer1.isClicked)

btnAnswer2.setText("Face plant");
btnAnswer3.setText(" Jump");
btnAnswer4.setText("A Ninja");
}
 

berry120

Fully Optimized
Messages
3,434
Location
UK
What class type is btnAnswer1? If it's JButton, then there's no isClicked method (or field) which means that code won't compile. You probably want to add an action listener to the button:

Code:
btnAnswer1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        //Whatever you want to do when the button is clicked
    }
});
If the above code doesn't ring any bells, then you need to take a deeper look at how events work in swing.
 
Last edited:

berry120

Fully Optimized
Messages
3,434
Location
UK
What if i want to add an if statement to it where would the () go
An if statement can be added as part of the normal code flow anywhere in that example. If you want one when you click on the button for instance:

Code:
btnAnswer1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        if(x==1) { //Whatever
            System.out.println("x was 1!");
        }
    }
});
Sorry about the spacing,
 

jpmasta12666

Baseband Member
Messages
26
Location
Canada
so how can i write if(btnAnswer1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lblAnswer.setText("correct");
}
}
});
 
Top