Java: reset button for your game

73 Views
Published
#Java #reset #button

Java reset button game tutorial explained

//--------------------------------------------------------------------------------------------
public class Main {

public static void main(String[] args) {

new GameFrame();

}
}
//--------------------------------------------------------------------------------------------
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class GameFrame extends JFrame implements ActionListener{

Game game;
JButton resetButton;

GameFrame(){

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600, 500);
this.setLayout(null);

resetButton = new JButton();
resetButton.setText("Reset");
resetButton.setSize(100, 50);
resetButton.setLocation(0, 200);
resetButton.addActionListener(this);

game = new Game();

this.add(resetButton);
this.add(game);
this.setVisible(true);

}

@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==resetButton) {
this.remove(game);
game = new Game();
this.add(game);
SwingUtilities.updateComponentTreeUI(this);
}
}
}
//--------------------------------------------------------------------------------------------
import java.awt.Color;
import java.util.Random;
import javax.swing.JPanel;

public class Game extends JPanel{

Random random;

Game(){
// code for game goes here :D

random = new Random();

int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);

this.setSize(500, 500);
this.setLocation(100,0);
this.setBackground(new Color(r,g,b));

}
}
//--------------------------------------------------------------------------------------------
Category
Bro Code
Tags
java reset button, reset button java, java reset
Be the first to comment