people of internet.
i want have sort of start screen game ive been writing. far features 4 buttons each 1 of 4 players change color on click red green , vice versa representing individual "ready"-status if makes sense. used jframe , jbuttons.
now want window close if every 1 of buttons set "ready" aka button.getbackground() == color.green.
any suggestions eventlisteners use this/implementation tips/code snippets appreciated since research on windowclosing on event didnt bring me.
thank in advance , greetings.
since you're awaiting , acting on button presses, logical listener actionlistener.
consider making buttons jtogglebuttons, , in listener querying each button see if selected (isselected()
) , if so, launch program. side bit, i'd consider making intro window jdialog , not jframe, either or making jpanel , swapping out via cardlayout when necessary.
for example:
import java.awt.color; import java.awt.dialog.modalitytype; import java.awt.dimension; import java.awt.window; import java.awt.event.actionevent; import java.awt.event.actionlistener; import java.util.arraylist; import java.util.list; import javax.swing.*; public class areweready extends jpanel { list<abstractbutton> buttons = new arraylist<>(); private int usercount; public areweready(int usercount) { this.usercount = usercount; buttonlistener buttonlistener = new buttonlistener(); (int = 0; < usercount; i++) { jbutton btn = new jbutton("user " + (i + 1)); buttons.add(btn); btn.addactionlistener(buttonlistener); add(btn); } } private class buttonlistener implements actionlistener { @override public void actionperformed(actionevent e) { abstractbutton btn = (abstractbutton) e.getsource(); color c = color.green.equals(btn.getbackground()) ? null : color.green; btn.setbackground(c); (abstractbutton button : buttons) { if (!color.green.equals(button.getbackground())) { // if button not have green background return; // leave method } } // otherwise if green, we're here window win = swingutilities.getwindowancestor(btn); win.dispose(); // else launch gui } } private static void createandshowgui() { int usercount = 4; areweready arewereadypanel = new areweready(usercount); jframe frame = new jframe("main application"); frame.setdefaultcloseoperation(jframe.dispose_on_close); frame.getcontentpane().add(box.createrigidarea(new dimension(400, 300))); frame.pack(); frame.setlocationbyplatform(true); jdialog dialog = new jdialog(frame, "are ready?", modalitytype.application_modal); dialog.add(arewereadypanel); dialog.pack(); dialog.setlocationbyplatform(true); dialog.setvisible(true); // reached when modal dialog above no longer visible frame.setvisible(true); } public static void main(string[] args) { swingutilities.invokelater(new runnable() { public void run() { createandshowgui(); } }); } }
Comments
Post a Comment