im trying to create a game where there are two buttons and you have to click the one with the even number to continue or else you lose. I need help on how to make it loop. I am a noob at java programming so please forgive me : D.
This is my code:
package button_game; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Button_Game { //A1 and B1 contain what to do when they are clicked. Right now they terminate the program until i figure out how to loop it. private static class A1 implements ActionListener{ public void actionPerformed(ActionEvent e){ System.exit(0); } } private static class B1 implements ActionListener { public void actionPerformed(ActionEvent e){ System.exit(0); } } //addComponentsToPane positions the buttons on the screen randomly public static void addComponentsToPane(Container pane){ int x; x = (int)(200*Math.random()); int y; y = (int)(200*Math.random()); pane.setLayout(null); int a = (int)(1000*Math.random()); int b = a%2; if (b == 0){ String c = Integer.toString(a); JButton A2 = new JButton(c); JButton B2 = new JButton(); A1 listener = new A1(); A2.addActionListener(listener); B2.addActionListener(listener); pane.add(B2); pane.add(A2); Insets insets = pane.getInsets(); Dimension size = B2.getPreferredSize(); B2.setBounds(x + insets.left, x + insets.top, size.width, size.height); size = A2.getPreferredSize(); A2.setBounds(y + insets.left, y + insets.top, size.width, size.height); } else if(b != 0); int c = a +1; String d = Integer.toString(c); JButton A2 = new JButton(d); JButton B2 = new JButton(); A1 listener = new A1(); A2.addActionListener(listener); B2.addActionListener(listener); pane.add(B2); pane.add(A2); Insets insets = pane.getInsets(); Dimension size = B2.getPreferredSize(); B2.setBounds(x + insets.left, x + insets.top, size.width, size.height); size = A2.getPreferredSize(); A2.setBounds(y + insets.left, y + insets.top, size.width, size.height); } //this runs the game private static void runGUI(){ JFrame window = new JFrame("Button Game"); addComponentsToPane(window.getContentPane()); window.setSize(300,300); window.setVisible(true); } //this part runs the subroutine which runs the game public static void main(String Args[]){ javax.swing.SwingUtilities.invokeLater(new Runnable(){ public void run(){ runGUI(); } }); } }