java - How to check if any button in JPanel is clicked by a user -
i've been making bus booking project , i've made booking page.
the jpanel
named panelseat
, contains buttons (about 36 buttons) inside.
i want check if button inside jpanel
clicked, disable button , if user clicks util 3 buttons, stopped or user can't click anymore.
this code i've written far:
private void countticket() { try { int count = 3; component[] components = panelseat.getcomponents(); (int = 0; < components.length; i++) { if (components[i] instanceof jbutton) { if (((jbutton) components[i]).isselected()) { // wanna check if button clicked user if (joptionpane.showconfirmdialog(this, "seat confirmation") == joptionpane.yes_option) { // confirm message ((jbutton) components[i]).setenabled(false); // disable button count--; system.out.println("your ramaining seat : " + count); } } } } } catch (exception e) { e.printstacktrace(); } }
how check if button has been clicked?
since want count how many times button pressed, , disable counts involved suggest wrap jbutton class in order make performing tasks easier, this solution better
class jbuttonwrapper extends jbutton { int count=0; public void increment() { count++; if (count==numberofclickstodisable) { this.setenabled(false); } } } //then can following. jbuttonwrapper [] buttons= new jbuttonwrapper [numbersofbuttonsyouhave]; (int i=0; i<=numbersofbuttonsyouhave;i++) { buttons[i].addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { buttons[i].increment(); } }); }
and solution based on code
static int count=3; component[] components = panelseat.getcomponents(); (int = 0; < components.length; i++) { if (components[i] instanceof jbutton) { { components[i].addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { count--; } }); }
Comments
Post a Comment