java - Need to switch between different screens in swing -
i'm trying create program runs game of go. want 1 screen asks size of go board in question, 1 plays game, , 1 lets decide play again or not. effective way using swing? saw people talk using cardlayout on other questions understanding user can switch between screens on demand, isn't want.
i using eclipse if native gui builder in eclipse work better i've never figured out how make work.
a less modal approach allow user select , play 1 of several common games. using button based memory game example,
enumerate supported game features.
add instances of
enum
valuesjcombobox
.handle changes using
remove()
,validate()
,repaint()
update game board.
in example, jlabel
serves placeholder game. alternatively, leave game view in place, update observable game model, described here, , arrange listening view respond required.
import java.awt.borderlayout; import java.awt.color; import java.awt.dimension; import java.awt.eventqueue; import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.jbutton; import javax.swing.jcombobox; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.jpanel; /** * @see https://stackoverflow.com/a/36714997/230513 */ public class go { private game game = game.easy; private final jcombobox gamecombo = new jcombobox(); enum game { easy(9), fast(13), classic(17), full(19); private int size; private string name; private game(int size) { this.size = size; this.name = this.name() + ": " + size + "\u00d7" + size; } public int size() { return this.size; } @override public string tostring() { return this.name; } } private void display() { jframe f = new jframe("test"); f.setdefaultcloseoperation(jframe.exit_on_close); jpanel board = new jpanel() { @override public color getbackground() { return color.cyan.darker(); } @override public dimension getpreferredsize() { return new dimension(320, 240); } }; board.add(new jlabel(game.tostring())); f.add(board); jpanel p = new jpanel(); (game g : game.values()) { gamecombo.additem(g); } gamecombo.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { game = (game) gamecombo.getselecteditem(); board.removeall(); board.add(new jlabel(game.tostring())); board.validate(); board.repaint(); } }); p.add(new jbutton("start")); p.add(gamecombo, borderlayout.south); f.add(p, borderlayout.south); f.pack(); f.setlocationrelativeto(null); f.setvisible(true); } public static void main(string[] args) { eventqueue.invokelater(new go()::display); } }
Comments
Post a Comment