I have this code and I want the user to be able to restart the game by pressing R, but I do not know how to do this, I've tried to call the main method again, which obviously didn't work, but I don't know any other way to restart it, this is the main class code:
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends JPanel implements KeyListener {
long startT = System.currentTimeMillis();
long elapsedTimeMillis;
float elapsedT;
private Player player;
private Stage stage;
private boolean isGameOver = false;
private EnemyManager manager;
public Main() {
setSize(800,600);
setPreferredSize(new Dimension(800,600));
setFocusable(true);
addKeyListener(this);
stage = new Stage();
player = new Player(this, 200, 500);
manager = new EnemyManager(this, 10);
}
#Override
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
if(!isGameOver){
player.draw(g);
manager.draw(g);
stage.draw(g);
long elapsedTimeMillis = System.currentTimeMillis() - startT;
elapsedT = elapsedTimeMillis/1000F;
g.setColor(Color.white);
g.setFont(new Font("Century Gothic", Font.BOLD, 24));
g.drawString("You're alive for: " + elapsedT, 400, 50);
}else {
g.setFont(new Font("Century Gothic", Font.BOLD, 55));
g.setColor(Color.RED);
g.drawString("Game Over" , 250, 150);
g.setColor(Color.ORANGE);
g.setFont(new Font("Century Gothic", Font.BOLD, 24));
g.drawString("You lasted for: ", 300, 250);
g.drawString("Press to restart", 300, 300);
g.setColor(Color.white);
g.drawString("" + elapsedT, 480, 250);
g.drawString("R", 364, 300);
}
g.dispose();
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_W){
}
if (code == KeyEvent.VK_A){
player.setdirectionX(-1);
}
if (code == KeyEvent.VK_S){
}
if (code == KeyEvent.VK_D){
player.setdirectionX(1);
}
if (code == KeyEvent.VK_R){
}
}
public void setGameOver(boolean flag){
isGameOver = flag;
}
#Override
public void keyReleased(KeyEvent e){
player.setdirectionX(0);
player.setdirectionY(0);
}
#Override
public void keyTyped(KeyEvent e) {
}
public Stage getStage(){
return stage;
}
public EnemyManager getEnemyManager(){
return manager;
}
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setTitle("Dodge the bloody rectangles");
frame.add(new Main());
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(800,600));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
public void restart() {
stage = new Stage();
player = new Player(this, 200, 500);
manager = new EnemyManager(this, 10);
isGameOver = false;
}
...
#Override
public void keyPressed(KeyEvent e) {
...
if (code == KeyEvent.VK_R){
restart();
}
}
Related
I'm writing a small game in java but I have a little problem. All the rendered frames stay on the screen, so if I move the image, it just keeps rendering more images, but I want my image to move over the screen. What am I doing wrong?
public void tick(){
balk.tick();
}
public void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs==null){
createBufferStrategy(2);
return;
}
Font myFont = new Font ("Courier New", 1, 50);
Graphics g = bs.getDrawGraphics();
///////////////////////////////
g.drawImage(balk.getBalk(), balk.getX(), 900, this);
g.setFont(myFont);
g.drawString("Score: " + 0, 50, 100);
///////////////////////////////
//g.dispose();
bs.show();
}
public void init(){
frame = new JFrame();
WIDTH = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
HEIGHT = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
}
public static void main(String[] args){
Game game = new Game();
game.init();
game.setPreferredSize(new Dimension(WIDTH, HEIGHT));
game.setMaximumSize(new Dimension(WIDTH, HEIGHT));
game.setMinimumSize(new Dimension(WIDTH, HEIGHT));
frame.add(game);
frame.setUndecorated(true);
frame.setTitle("Ping Pong");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setLayout(null);
frame.addKeyListener(new KeyListener(){
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_A){
balk.setVelX(-5);
}
if(key == KeyEvent.VK_D){
balk.setVelX(5);
}
}
public void keyReleased(KeyEvent e) {
balk.setVelX(0);
}
public void keyTyped(KeyEvent arg0) {}
});
frame.setVisible(true);
game.start();
}
}
Clear the screen before drawing anything with a fillRect that fills yours window, in a color you like.
g.setColor(Color.black);
g.fillRect(0, 0, width, height);
//draw here
Something like this.
I am trying to build a traffic light semaphore using threads but I can't get right.Semaphore should display red, yellow, green with break between colors. Any help is much appreciated.
Thanks.
Here is my code...
import java.awt.BorderLayout;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class StopTheLights extends JFrame implements ActionListener {
JButton start;
JButton stop;
JPanel panel;
Boolean flag;
public StopTheLights(String title) {
Container c = getContentPane();
start = new JButton("Start");
stop = new JButton("Stop");
start.addActionListener(this);
stop.addActionListener(this);
panel= new JPanel();
panel.add(start);
panel.add(stop);
c.add(panel, BorderLayout.SOUTH);
setSize(300, 450);
setVisible(true);
setLocation(200,200);
}
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.black);
g.drawOval(50,50,100,100);
g.drawOval(50,155,100,100);
g.drawOval(50,260,100,100);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == start){
flag = true;
new ThreadExtend(this).start();
}else{
flag = false;
}
}
public class ThreadExtend extends Thread {
Graphics g;
JFrame frame;
public ThreadExtend(JFrame frame){
this.frame = frame;
g = frame.getGraphics();
}
public void run(){
while(flag) {
try{
paintRed(g);
if(!flag) {
break;
}
Thread.sleep(1000);
paintAmber(g);
if(!flag) {
break;
}
Thread.sleep(1000);
paintGreen(g);
if(!flag){
break;
}
}catch(InterruptedException e) {
}
}
}
}
public void paintRed(Graphics g){
g.setColor(new Color(255,0,0));
g.fillOval(52, 52, 96, 96);
g.fillOval(52, 52, 96, 96);
g.fillOval(52, 262, 96, 96);
}
public void paintAmber(Graphics g){
g.setColor(new Color(250,170,0));
g.fillOval(52, 157, 96, 96);
g.fillOval(52, 52, 96, 96);
g.fillOval(52, 262, 96, 96);
}
public void paintGreen(Graphics g){
g.setColor(new Color(0,250,0));
g.fillOval(52, 262, 96, 96);
g.fillOval(52, 52, 96, 96);
g.fillOval(52, 157, 96, 96);
}
public static void main(String[] args) {
new StopTheLights();
}
}
There are several problems here.
Your Thread does not wait after showing Green light.
You paint all the lights in all the methods calls, which is not needed.
You don't change the color when "closing" other lights.
I did some fixing in your code, and now it works:
import java.awt.BorderLayout;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class StopTheLights extends JFrame implements ActionListener {
JButton start;
JButton stop;
Boolean i;
//create constructor method
public StopTheLights(String title) {
// create Start button
start = new JButton("Start");
//create Stop button
stop = new JButton("Stop");
//add Action listeners
start.addActionListener(this);
stop.addActionListener(this);
//create new Button Panel
JPanel buttonPanel = new JPanel();
buttonPanel.add(start);
buttonPanel.add(stop);
Container c = getContentPane();
c.add(buttonPanel, BorderLayout.SOUTH);
setSize(200, 425);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.black);
g.fillOval(50,50,100,100);
g.fillOval(50,155,100,100);
g.fillOval(50,260,100,100);
}
public static void main(String[] args) {
new StopTheLights("Stop The Lights");
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == start){
i = true;
new ThreadExtend(this).start();
}else{
i = false;
}
}
public class ThreadExtend extends Thread {
Graphics g;
JFrame frame;
public ThreadExtend(JFrame frame){
this.frame = frame;
g = frame.getGraphics();
}
public void run(){
while(i) {
try{
red(g);
if(!i) {
break;
}
Thread.sleep(1000);
amber(g);
if(!i) {
break;
}
Thread.sleep(1000);
green(g);
if(!i){
break;
}
Thread.sleep(1000);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void red(Graphics g){
g.setColor(Color.black);
g.fillOval(52, 262, 96, 96);
g.setColor(new Color(255,0,0));
g.fillOval(52, 52, 96, 96);
}
public void amber(Graphics g){
g.setColor(Color.black);
g.fillOval(52, 52, 96, 96);
g.setColor(new Color(250,170,0));
g.fillOval(52, 157, 96, 96);
}
public void green(Graphics g){
g.setColor(Color.black);
g.fillOval(52, 157, 96, 96);
g.setColor(new Color(0,250,0));
g.fillOval(52, 262, 96, 96);
}
}
First of all I am making a minigame with the Five Nights At Freddy's graphics and jump scares. I already know how to import and draw a picture (png and etc). The only one I don't know how to import, are gifs.
Here Is My Code:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Minigame extends JPanel
{
/**
*
*/
private static final long serialVersionUID = 1L;
GameEvents gameEvents = new GameEvents();
Timer gameTimer = new Timer(1, gameEvents);
int i = 0;
int horizontalposition = 500;
int verticalposition = 500;
BufferedImage Picture;
BufferedImage Picture2;
BufferedImage Picture3;
BufferedImage Picture4;
BufferedImage Picture5;
BufferedImage Picture6;
//Don't forget to declare your variables!
Minigame()
{
gameTimer.start();
this.addKeyListener(gameEvents);
try
{
Picture = ImageIO.read(getClass().getResource("Child.gif"));
Picture2 = ImageIO.read(getClass().getResource("Freddycake_Gif.gif"));
Picture3 = ImageIO.read(getClass().getResource("Purple_man.png"));
Picture4 = ImageIO.read(getClass().getResource("Cake_Child_Idle.png"));
Picture5 = ImageIO.read(getClass().getResource("Cake_Child.gif"));
//The format for this is Picture = ImageIO.read(getClass().getResource("NameOfFile.typeoffile"));
}
catch (IOException e)
{
System.out.println("Pictures failed to load");
}
}
#Override
protected void paintComponent(Graphics g)
{
g.setColor(Color.black);
g.fillRect(0,0,this.getWidth(), this.getHeight());
///g.drawImage(Picture, horizontalposition, verticalposition, 100, 150, null);
g.drawImage(Picture, 200, 10, 70, 100, null);
g.drawImage(Picture, 200, 100, 70, 100, null);
g.drawImage(Picture, 200, 200, 70, 100, null);
g.drawImage(Picture, 200, 300, 70, 100, null);
g.drawImage(Picture, 200, 400, 70, 100, null);
g.drawImage(Picture, 200, 500, 70, 100, null);
g.drawImage(Picture2, horizontalposition, verticalposition, 100, 150, null);
g.drawImage(Picture3, 1100, 50, 100, 150, null);
g.drawImage(Picture4, 900, 50, 100, 150, null);
//g.drawImage(Picture5, 900, 50, 100, 150, null);
}
public class GameEvents implements ActionListener, KeyListener
{
#Override
public void actionPerformed(ActionEvent arg0)
{
repaint();
}
#Override
public void keyPressed(KeyEvent key) //stuff inside here happens when a key is pressed
{
if(key.getKeyChar()=='d')
{
horizontalposition=horizontalposition+50;
}
if(key.getKeyChar()=='s')
{
verticalposition=verticalposition+50;
}
if(key.getKeyChar()=='w')
{
verticalposition=verticalposition-50;
}
if(key.getKeyChar()=='a')
{
horizontalposition=horizontalposition-50;
}
if(horizontalposition<0)
{
horizontalposition=0;
}
System.out.println(key.getKeyChar());
System.out.println('d');
}
#Override
public void keyReleased(KeyEvent arg0) {
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
public static void main(String[] args)
{
JFrame f = new JFrame("Java Graphics Example Project");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Minigame p = new Minigame();
f.setSize(1500,700);
f.add(p);
f.setVisible(true);
p.requestFocusInWindow();
}
}
Any yes, I already know how to do g.drawImage();
Look up this answer response: Show animated GIF
If you don't feel like it, I'll just put the code of the person who replied here. However, they explain it there and really go in detail.
THIS IS THE CODE FROM STACKER WHO EXPLAINED IT ON THE LINK I GAVE YOU
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("<URL to your Animated GIF>");
Icon icon = new ImageIcon(url);
JLabel label = new JLabel(icon);
JFrame f = new JFrame("Animation");
f.getContentPane().add(label);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
I have added a while loop that will change between players as seen in the code below. Before I add this while loop it displays the grid, buttons, etc but when I add this loop the panel is just plain white. I have no idea why.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.security.auth.x500.X500Principal;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.omg.CORBA.PRIVATE_MEMBER;
public class Game
{
boolean p1;
private int counterY1 = 515, counterY2 = 515, counterY3 = 515, counterY4 = 515;
boolean playerTurn = true;
boolean playerTurn2 = false;
boolean moveLoop = true;
public void moveC1Up()
{
counterY1 -= 51 * diceRoll();
}
public void moveC2Up()
{
counterY2 -= 51 * diceRoll();
}
public void moveC3Up()
{
counterY3 -= 51 * diceRoll();
}
public void moveC4Up()
{
counterY4 -= 51 * diceRoll();
}
public int diceRoll()
{
int randGen = (int)(Math.random()*1) + 1;
System.out.print(randGen);
return randGen;
}
private JButton moveC1But, moveC2But, rollDiceButton;
private JLabel amountRolledLabel;
public Game()
{
JFrame window = new JFrame ("Main Game");
final JPanel firstPanel = new JPanel(new GridLayout(3,1))
{
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g2d);
int width = getWidth() / 3;
int height = getHeight() / 11;
for (int i = 0; i < 4; i++) {
g.drawLine(i * width, 0, i * width, getHeight());
}
for (int i = 0; i < 11; i++) {
g.drawLine(0, i * height, getWidth(), i * height);
}
g.setColor(Color.DARK_GRAY);
g.drawOval(220, counterY1, 40, 40);
g.fillOval(220, counterY1, 40, 40);
g.drawOval(300, counterY2, 40, 40);
g.fillOval(300, counterY2, 40, 40);
g.setColor(Color.LIGHT_GRAY);
g.drawOval(410, counterY3, 40, 40);
g.fillOval(410, counterY3, 40, 40);
g.drawOval(490, counterY4, 40, 40);
g.fillOval(490, counterY4, 40, 40);
}
};
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(firstPanel, BorderLayout.CENTER);
JPanel rightSidePanel = new JPanel(new GridLayout(10,1));
moveC1But = new JButton("Move Counter 1");
moveC2But = new JButton("Move Counter 2");
rollDiceButton = new JButton("Roll Dice");
rightSidePanel.add(moveC1But, BorderLayout.LINE_START);
rightSidePanel.add(moveC2But, BorderLayout.LINE_END);
rightSidePanel.add(rollDiceButton, BorderLayout.SOUTH);
mainPanel.add(rightSidePanel, BorderLayout.EAST);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(mainPanel);
window.setSize(700, 600);
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setResizable(false);
while(moveLoop == true)
{
moveC1But.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
diceRoll();
moveC1Up();
firstPanel.repaint();
System.out.print(diceRoll());
System.out.print("Test1");
playerTurn = false;
playerTurn2 = true;
moveLoop = false;
}
});
moveC2But.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
diceRoll();
moveC3Up();
firstPanel.repaint();
System.out.print(diceRoll());
System.out.print("Test1");
playerTurn = false;
playerTurn2 = true;
moveLoop = false;
}
});
}
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new Game();
}
});
}
}
EDIT:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.security.auth.x500.X500Principal;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.omg.CORBA.PRIVATE_MEMBER;
public class Game
{
boolean p1;
private int counterY1 = 515, counterY2 = 515, counterY3 = 515, counterY4 = 515;
boolean playerTurn = true;
boolean playerTurn2 = false;
boolean moveLoop = true;
public void moveC1Up()
{
counterY1 -= 51 * diceRoll();
}
public void moveC2Up()
{
counterY2 -= 51 * diceRoll();
}
public void moveC3Up()
{
counterY3 -= 51 * diceRoll();
}
public void moveC4Up()
{
counterY4 -= 51 * diceRoll();
}
public int diceRoll()
{
int randGen = (int)(Math.random()*1) + 1;
System.out.print(randGen);
return randGen;
}
private JButton moveC1But, moveC2But, rollDiceButton;
private JLabel amountRolledLabel;
public Game()
{
JFrame window = new JFrame ("Main Game");
final JPanel firstPanel = new JPanel(new GridLayout(3,1))
{
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g2d);
int width = getWidth() / 3;
int height = getHeight() / 11;
for (int i = 0; i < 4; i++) {
g.drawLine(i * width, 0, i * width, getHeight());
}
for (int i = 0; i < 11; i++) {
g.drawLine(0, i * height, getWidth(), i * height);
}
g.setColor(Color.DARK_GRAY);
g.drawOval(220, counterY1, 40, 40);
g.fillOval(220, counterY1, 40, 40);
g.drawOval(300, counterY2, 40, 40);
g.fillOval(300, counterY2, 40, 40);
g.setColor(Color.LIGHT_GRAY);
g.drawOval(410, counterY3, 40, 40);
g.fillOval(410, counterY3, 40, 40);
g.drawOval(490, counterY4, 40, 40);
g.fillOval(490, counterY4, 40, 40);
}
};
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(firstPanel, BorderLayout.CENTER);
JPanel rightSidePanel = new JPanel(new GridLayout(10,1));
moveC1But = new JButton("Move Counter 1");
moveC2But = new JButton("Move Counter 2");
rollDiceButton = new JButton("Roll Dice");
rightSidePanel.add(moveC1But, BorderLayout.LINE_START);
rightSidePanel.add(moveC2But, BorderLayout.LINE_END);
rightSidePanel.add(rollDiceButton, BorderLayout.SOUTH);
mainPanel.add(rightSidePanel, BorderLayout.EAST);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(mainPanel);
window.setSize(700, 600);
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setResizable(false);
if(playerTurn == true)
{
moveC1But.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
diceRoll();
moveC1Up();
firstPanel.repaint();
System.out.print(diceRoll());
System.out.print("Test1");
playerTurn = false;
playerTurn2 = true;
moveLoop = false;
}
});
moveC2But.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
diceRoll();
moveC2Up();
firstPanel.repaint();
System.out.print(diceRoll());
System.out.print("Test1");
playerTurn = false;
playerTurn2 = true;
moveLoop = false;
}
});
}else if (playerTurn2 == true)
{
moveC1But.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
diceRoll();
moveC3Up();
firstPanel.repaint();
System.out.print(diceRoll());
System.out.print("Test1");
playerTurn = false;
playerTurn2 = true;
moveLoop = false;
}
});
moveC2But.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
diceRoll();
moveC4Up();
firstPanel.repaint();
System.out.print(diceRoll());
System.out.print("Test1");
playerTurn = false;
playerTurn2 = true;
moveLoop = false;
}
});
}
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new Game();
}
});
}
Yours is a common problem: you've got a long-running bit of code that is running on the Swing event thread, completely tying it up. Since this thread is responsible for all of Swing drawing and user interaction, your GUI becomes essentially frozen until the long-running code finishes. Possible solutions include:
Use a Swing Timer for your game loop, avoiding the use of while (true) on the Swing event thread.
Use a background thread for a long-running bit of code. This can be conveniently be done with a SwingWorker.
Do neither. Having a look at your code, I see no reason to have the while (true) loop in the first place. All it does is to add ActionListeners to JButtons multiple times and thus is completely worthless. So get rid of it and add the ActionListeners only once. For your code, this is your best option -- rethink your code so that it makes more sense.
Edit
You ask:
Yes I see what the ifs are doing and have removed them. But basically I have two buttons, move counter 1 and move counter 2 each player has 2 counters, but only the two buttons. I want player 1 to start and hit which counter they would like to move, this then allows the second player to move their counter and visa versa.
The logic must be inside your ActionListener. For example:
moveC1But.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
diceRoll();
if (player1Turn) {
// logic for player turn 1
} else {
// logic for player turn 2
}
}
});
In your current code the loop doesn't let the JFrame to call repaint(); because it is never broken until the user clicks a button, which is impossible if the JFrame can't draw the components.
Here's how you should do your inputs instead.
package beaudoin.apps;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import sun.awt.RepaintArea;
public class Game {
boolean p1;
private int counterY1 = 515, counterY2 = 515, counterY3 = 515, counterY4 = 515;
boolean playerTurn = true;
boolean playerTurn2 = false;
public void moveC1Up() {
counterY1 -= 51 * diceRoll();
}
public void moveC2Up() {
counterY2 -= 51 * diceRoll();
}
public void moveC3Up() {
counterY3 -= 51 * diceRoll();
}
public void moveC4Up() {
counterY4 -= 51 * diceRoll();
}
public int diceRoll() {
int randGen = (int) (Math.random() * 1) + 1;
System.out.print(randGen);
return randGen;
}
private JButton moveC1But, moveC2But, rollDiceButton;
private JLabel amountRolledLabel;
public Game() {
JFrame window = new JFrame("Main Game");
final JPanel firstPanel = new JPanel(new GridLayout(3, 1)) {
private static final long serialVersionUID = -1729570833533906839L;
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g2d);
int width = getWidth() / 3;
int height = getHeight() / 11;
for (int i = 0; i < 4; i++) {
g.drawLine(i * width, 0, i * width, getHeight());
}
for (int i = 0; i < 11; i++) {
g.drawLine(0, i * height, getWidth(), i * height);
}
g.setColor(Color.DARK_GRAY);
g.drawOval(220, counterY1, 40, 40);
g.fillOval(220, counterY1, 40, 40);
g.drawOval(300, counterY2, 40, 40);
g.fillOval(300, counterY2, 40, 40);
g.setColor(Color.LIGHT_GRAY);
g.drawOval(410, counterY3, 40, 40);
g.fillOval(410, counterY3, 40, 40);
g.drawOval(490, counterY4, 40, 40);
g.fillOval(490, counterY4, 40, 40);
}
};
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(firstPanel, BorderLayout.CENTER);
JPanel rightSidePanel = new JPanel(new GridLayout(10, 1));
moveC1But = new JButton("Move Counter 1");
moveC1But.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
diceRoll();
moveC1Up();
firstPanel.repaint();
playerTurn = false;
playerTurn2 = true;
}
});
moveC2But = new JButton("Move Counter 2");
moveC2But.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
diceRoll();
moveC3Up();
firstPanel.repaint();
playerTurn = false;
playerTurn2 = true;
}
});
rollDiceButton = new JButton("Roll Dice");
rightSidePanel.add(moveC1But, BorderLayout.LINE_START);
rightSidePanel.add(moveC2But, BorderLayout.LINE_END);
rightSidePanel.add(rollDiceButton, BorderLayout.SOUTH);
mainPanel.add(rightSidePanel, BorderLayout.EAST);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(mainPanel);
window.setSize(700, 600);
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setResizable(false);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Game();
}
});
}
}
Hi I'm trying to call the paint method every time in a game loop.At the moment the screen pops up with a label and a button once the button has been pressed the label and button go which i want but i can't get the paint method to start i tried j.repaint() & j.validate() neither accessed paint method.Any help would be appreciated.
package sgame;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SGame extends JPanel
{
public static void main(String[] args)
{
final JFrame window = new JFrame("hello");
final JPanel window1 = new JPanel();
Timer loop = new Timer(1000, new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
GameLoop(window1);
}
});
Window(window, loop);
}
public static void Window(final JFrame window, final Timer loop)
{
final JButton b1 = new JButton("GO!");
b1.setLocation(210, 300);
b1.setSize(70, 50);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(500, 500);
window.setLocation(420, 170);
window.setBackground(Color.BLACK);
final JLabel Title = new JLabel("Snake", JLabel.CENTER);
Title.setFont(new Font("Times New Roman", Font.ITALIC, 60));
Title.setVerticalAlignment(JLabel.CENTER);
Title.setForeground(Color.WHITE);
window.add(b1);
window.add(Title);
b1.addActionListener(new ActionListener() // runs when buttons pressed
{
#Override
public void actionPerformed(ActionEvent e) // clears header,button and starts timer
{
b1.invalidate();
b1.setVisible(false);
Title.setVisible(false);
Title.invalidate();
loop.start();
}
});
}
public static void GameLoop(JPanel j)
{
// Call paint method
}
public void paintComponent(Graphics g)
{
g.setColor(Color.yellow);
g.drawRect(30, 30, 30, 30);
}
}
The paintComponent() method in SGame is never called because you didn't instanciate any SGame object. And window1 has not been added to the frame.
Something like this should be better :
public class SGame extends JPanel {
private Timer loop;
public SGame(){
loop = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
gameLoop();
}
});
}
public static void main(String[] args) {
final JFrame window = new JFrame("hello");
final JButton b1 = new JButton("GO!");
b1.setLocation(210, 300);
b1.setSize(70, 50);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(500, 500);
window.setLocation(420, 170);
window.setBackground(Color.BLACK);
final JLabel Title = new JLabel("Snake", JLabel.CENTER);
Title.setFont(new Font("Times New Roman", Font.ITALIC, 60));
Title.setVerticalAlignment(JLabel.CENTER);
Title.setForeground(Color.WHITE);
window.add(b1);
window.add(Title);
b1.addActionListener(new ActionListener() { // runs when buttons pressed
#Override
public void actionPerformed(ActionEvent e) // clears header,button
{
b1.invalidate();
b1.setVisible(false);
Title.setVisible(false);
Title.invalidate();
SGame sg = new SGame();
window.add(sg);
sg.start();
}
});;
}
public void start(){
loop.start();
}
public void gameLoop() {
repaint();
}
#Override
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.yellow);
g.drawRect(30, 30, 30, 30);
}
}