I am trying to print "Hello" only when the jButton2 is clicked after the jButton1 and print "Bye" only when any other jButtons are clicked after jButton1. At the moment, the following code does not print anything.
public void MouseClicked(java.awt.event.MouseEvent e){
if (e.getSource() == jButton1) {
if (e.getSource() == jButton2) {
System.out.println ("Hello");
} else {
System.out.println ("Bye");
}
}
}
This code has two problems.
MouseClicked
should be mouseClicked
(first letter in small case) as in parent (super) class so that it is overridden and mouse event is captured.if-else
statements as this method would be called on every click and state of any previous clicks on other buttons is not saved.This code will work for you.
boolean button1ClickedLast = false;
public void mouseClicked(java.awt.event.MouseEvent e){
if (e.getSource() == jButton1) {
button1ClickedLast = true;
System.out.println ("Bye");
}
else if (e.getSource() == jButton2) {
if(button1ClickedLast) {
System.out.println ("Hello");
}
else{
// do nothing or something if you want
}
}
else {
button1ClickedLast = false; // to change status to false in case any other button is clicked last
}
}