In Eclipse, how should I change the entry point for my program.
I have two separate packages each with static main methods. My original static main method found in the main package will now be called upon after running the main method found in the title package.
What I want to happen is:
Display the title screen, and If the user choice to play the game then call the Game.main()
Here are the two classes:
package game.title;
import game.main.entities.movement.MenuKeyListener;
import game.main.graphics.ImageLoader;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.*;
import src.game.main.Game;
// Referenced classes of package game.main:
// MenuKeyListener, Game
public class TitleScreen extends JFrame
{
class MyCanvas extends Canvas
{
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(image, 0, 0, TitleScreen.SCREENHEIGHT, TitleScreen.SCREENWIDTH, this);
}
public void update(Graphics g)
{
if(TitleScreen.toggle == 0)
{
g.clearRect(0, 0, TitleScreen.SCREENWIDTH, TitleScreen.SCREENHEIGHT);
g.drawImage(image, 0, 0, TitleScreen.SCREENHEIGHT, TitleScreen.SCREENWIDTH, this);
int xCord[] = {
322, 350, 350
};
int yCord[] = {
533, 533, 553
};
g.setColor(Color.CYAN);
g.fillPolygon(xCord, yCord, 3);
} else
if(TitleScreen.toggle == 1)
{
g.clearRect(0, 0, TitleScreen.SCREENWIDTH, TitleScreen.SCREENHEIGHT);
g.drawImage(image, 0, 0, TitleScreen.SCREENHEIGHT, TitleScreen.SCREENWIDTH, this);
int xCord[] = {
322, 350, 350
};
int yCord[] = {
600, 600, 620
};
g.setColor(Color.CYAN);
g.fillPolygon(xCord, yCord, 3);
}
}
final TitleScreen this$0;
MyCanvas()
{
this$0 = TitleScreen.this;
//super();
}
}
public static void main(String args[])
throws IOException
{
new TitleScreen();
}
public TitleScreen()
throws FileNotFoundException, IOException
{
SCALE = 2;
quit = false;
runGame = false;
setTitle("Mortem");
setSize(new Dimension(SCREENWIDTH, SCREENHEIGHT));
setLocationRelativeTo(null);
setDefaultCloseOperation(3);
setResizable(false);
MyCanvas canvas = new MyCanvas();
add(canvas);
ImageLoader loader = new ImageLoader();
image = loader.load("/Title Screen.jpg");
setVisible(true);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(20, 20));
JLabel label = new JLabel();
label.setLocation(10, 10);
label.setSize(220, 100);
panel.add(label);
//Sound music = new Sound("/piano1.wav");
//music.play();
canvas.addKeyListener(new MenuKeyListener());
while(!check)
{
canvas.update(canvas.getGraphics());
try
{
Thread.sleep(500L);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
if(toggle == 1){
System.out.println("BYE!");
System.exit(0);
}
else if(toggle == 0)
{
//music.stop();
Game.main(null);
System.out.println("Start Game!");
}
}
private static int SCREENWIDTH = 700;
private static int SCREENHEIGHT = 700;
private int SCALE;
private static Graphics g;
private final BufferedImage image;
private static BufferedImage titleImage;
public static int toggle = 0;
private boolean quit;
private boolean runGame;
public static boolean check = false;
}
Which calls:
package game.main;
import game.main.entities.Enemy;
import game.main.entities.Entity;
import game.main.entities.Player;
import game.main.entities.Title;
import game.main.entities.movement.EnemyMovementThread;
import game.main.entities.movement.KeyManager;
import game.main.graphics.CharacterSpriteSheet;
import game.main.graphics.ImageLoader;
import game.main.graphics.ImageManager;
import game.main.graphics.SpriteSheet;
import game.main.levels.Level;
import game.main.sounds.Sound;
import game.main.tiles.Heart0Tile;
import game.main.tiles.Tile;
import game.title.TitleScreen;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.LayoutManager;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable{
public static final int HEIGHT = 240, WIDTH = 360, SCALE = 3, TILESIZE = 16;
public static boolean running = false;
public Thread gameThread;
public Thread enemyMovement;
private BufferedImage spriteSheet;
private BufferedImage characterAnimation;
private static ImageManager im;
private static Level level1;
static BufferedImage level;
private static Player player;
private static Enemy enemy;
private Title title;
private Heart0Tile life;
private Sound titleTheme;
public void init() throws IOException{
ImageLoader loader = new ImageLoader();
spriteSheet = loader.load("/SS.png");
characterAnimation = loader.load("/characterAnimation.png");
SpriteSheet ss = new SpriteSheet(spriteSheet);
CharacterSpriteSheet ca = new CharacterSpriteSheet(characterAnimation);
im = new ImageManager(ss, ca);
level = loader.load("/level1.png");
level1 = new Level(level);
player = new Player(WIDTH * SCALE / 2, HEIGHT * SCALE /2, im);
enemy = new Enemy(WIDTH * SCALE /2, HEIGHT * SCALE /2 , im);
this.addKeyListener(new KeyManager());
title = new Title(50, 70, ss);
titleTheme = new Sound("/Boss theme riff (1).wav");
titleTheme.play();
}
public synchronized void start(){
if(running)return;
running = true;
gameThread = new Thread(this);
gameThread.start();
enemyMovement = new Thread(new EnemyMovementThread("enemyMovement", 2000));
enemyMovement.start();
}
public synchronized void stop(){
if(running == false) return;
running = false;
try{
gameThread.join();
enemyMovement.join();
}catch(InterruptedException e){
e.printStackTrace();
}
}
public void run(){
try {
init();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long lastTime = System.nanoTime();
final double AMOUNTOFTICKS = 60D;
double ns = 1000000000/AMOUNTOFTICKS;
double delta = 0;
while(running){
long now = System.nanoTime();
delta += (now - lastTime)/ns;
lastTime = now;
if(delta >= 1){
tick();
delta--;
}
render();
}
stop();
}
public void tick(){
player.tick();
//enemy.tick();
//title.tick();
}
public void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//RENDER HERE
g.fillRect(0, 0, WIDTH*SCALE, HEIGHT*SCALE);
level1.render(g);
//title.render(g);
player.render(g);
//enemy.render(g);
//END RENDER
g.dispose();
bs.show();
}
public static void main(String[] args){
Game game = new Game();
game.setPreferredSize( new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
game.setMaximumSize( new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
game.setMinimumSize( new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
JFrame frame = new JFrame("Game");
frame.setSize(WIDTH*SCALE, HEIGHT*SCALE);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setResizable(false);//change later
frame.add(game);
frame.setVisible(true);
game.start();
}
public static Player getPlayer(){
return player;
}
public static Enemy getEnemy(){
return enemy;
}
public static Level getLevel(){
return level1;
}
public static ImageManager getImageManager(){
return im;
}
}
After try to run the TitleScreen class I get this in my console:
Error: Could not find or load main class game.title.TitleScreen
In "Run Configuration" menu you can set your main class to be run.
To change your main method, you need to modify it in your launch configurations.
1.Right click your project
2. Select Run as-> Run Configurations
3. Set your main method for your application by searching the main class.
4. Save configuration and run your project.
Related
I'm trying to make a test application.First I made the basic things (frame, graphics, textures). When I ran the application it shows an empty window. At first I thought it was from my texture class. But when I tried to set the color black it also didn't worked. Here's my code:
package Main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
import Audio.MusicPlayer;
import MultiThreading.ThreadPool;
import Textures.Textures;
public class Main extends Canvas implements Runnable{
private static final long serialVersionUID = 1L;
private boolean running = true;
private Thread thread;
public static Main test = new Main();
public static final int height = 842 ;
public static final int width = 595;
public static final int scale = 1;
private Textures background;
public void init(){
background = new Textures("Test paper");
System.out.println("Initiating...");
}
public void run() {
init();
System.out.println("Starting...\nReady!");
running = true;
requestFocus();
while (running) {
//System.out.println("Running...");
render();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
stop();
}
public void render(){
BufferStrategy bs = getBufferStrategy();
if(bs == null){
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.dispose();
bs.show();
g.setColor(new Color(0, 11, 54));
g.fillRect(0, 0, width, height);
background.render(g, 100, 100);
}
private synchronized void stop() {
if (!running) return;
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.exit(1);
}
public static void main (String args[])
{
ThreadPool pool = new ThreadPool(2);
JFrame frame = new JFrame("Stilul gotic si stilul renascentist");
frame.add(test);
frame.setSize(width / scale, height / scale);
frame.setFocusable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
frame.pack();
MusicPlayer audio = new MusicPlayer("J");
pool.runTask(test);
pool.runTask(audio);
pool.join();
}
}
I checked the multithreading, so it couldn't be from there (the audio file is running and I used same classes for a game). Also, in the console isn't any error...
Can anyone help me?
This is my code so far, what I want to do is to add a new Object every time the mouse is moved, but the system is not even accessing the MouseEvent class after hours of thinking, I still am not able to figure the problem. Please Help!!
My main class:
package testing;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.util.Random;
public class Wincall extends Canvas implements Runnable {
public static final int HEIGHT = 640, WIDTH = 1080;
private WinTest w;
private Handler handler;
private ME me = new ME(this);
public Wincall(){
handler = new Handler();
w = new WinTest(WIDTH, HEIGHT, "Test", this);
}
public synchronized void run(){
while(true){
long now = System.currentTimeMillis();
this.tick();
this.render();
long after = System.currentTimeMillis();
int tt = (int) (after-now);
if(tt>5)
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Time Taken in millisecs : " + tt);
}
}
public void tick(){
handler.tick();
}
public void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null)
{
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//render
g.setColor(Color.BLACK);
g.fillRect(0 ,0 ,WIDTH, HEIGHT);
handler.render(g);
//render end
g.dispose();
bs.show();
}
public void addStuff(){
handler.addObject(new TestGO(me.getX(), me.getY(), 32, 32));
}
public static void main(String[] args){
new Wincall();
}
}
My MouseEvent class:
package testing;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class ME implements MouseMotionListener{
private int mx = 0, my = 0;
private Wincall game;
public ME(Wincall game){
this.game = game;
}
public void mouseDragged(MouseEvent e){}
public void mouseMoved(MouseEvent e) {
game.addStuff();
mx = e.getX();
my = e.getY();
System.out.println(mx);
System.out.println(my);
}
public int getX(){
return mx;
}
public int getY(){
return my;
}
}
My window class:
package testing;
import java.awt.Canvas;
import javax.swing.JFrame;
public class WinTest {
private static final long serialVersionUID = -369751247370351003L;
public WinTest(int h, int w, String title, Wincall game){
JFrame f = new JFrame(title);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(h, w);
f.add(game);
f.setVisible(true);
f.requestFocus();
f.setResizable(false);
f.setFocusable(true);
game.addMouseMotionListener(new ME());
game.run();
}
}
Though its not clear what you are trying to do. But you need to add the MouseMotionListener to canvas not to the JFrame. Since you are adding canvas to the JFrame, it is the canvas which should capture MouseEvents. Hence, your Wintest should probably look like this :
public class WinTest extends Canvas {
private static final long serialVersionUID = -369751247370351003L;
public WinTest(int h, int w, String title, Wincall game, ME me) {
JFrame f = new JFrame(title);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(h, w);
f.add(game);
f.setVisible(true);
f.requestFocus();
f.setResizable(false);
f.setFocusable(true);
// f.addMouseMotionListener(me);
game.addMouseMotionListener(me);
game.run();
}
}
Update :
Wincalll Class:
public class Wincall extends Canvas implements Runnable {
public static final int HEIGHT = 640, WIDTH = 1080;
private WinTest w;
// private Handler handler;
private ME me = new ME(this);
public Wincall() {
// handler = new Handler();
w = new WinTest(WIDTH, HEIGHT, "Test", this, me);
}
public synchronized void run() {
while (true) {
long now = System.currentTimeMillis();
this.tick();
this.render();
long after = System.currentTimeMillis();
int tt = (int) (after - now);
if (tt > 5)
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// System.out.println("Time Taken in millisecs : " + tt);
}
}
public void tick() {
// handler.tick();
}
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
// render
g.setColor(Color.BLACK);
g.fillRect(0, 0, WIDTH, HEIGHT);
// handler.render(g);
// render end
g.dispose();
bs.show();
}
public void addStuff() {
System.out.println("addStuff");
// handler.addObject(new TestGO(me.getX(), me.getY(), 32, 32));
}
public static void main(String[] args) {
new Wincall();
}
}
I was looking at some of my old source codes:
Try
addMouseMotionListener(me);
Instead of:
f.addMouseMotionListener(me);
Ok, so I'm new to programming and I'm following a tutorial on Youtube to build my own game. My problem is that my screen doesn't turn red, it just stays gray. I'm sure I did something wrong but there are no errors on eclipse. Here is the code:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static int width = 300;
public static int height = width / 16 * 9;
public static int scale = 3;
private Thread thread;
private JFrame frame;
private boolean running = false;
public Game() {
Dimension size = new Dimension(width * scale, height * scale);
setPreferredSize(size);
frame = new JFrame();
}
public synchronized void start() {
running = true;
thread = new Thread("Display");
thread.start();
}
public synchronized void stop() {
running = false;
try {
thread.join();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
while (running) {
update();
render();
}
}
public void update() {
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.RED);
g.fillRect(0, 0, getWidth(), getHeight());
g.dispose();
bs.show();
}
public static void main(String[] args){
Game game = new Game();
game.frame.setResizable(false);
game.frame.setTitle("JJF");
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
game.start();
}
}
You never actually provide the Thread with something to run...
public synchronized void start() {
running = true;
// Not the reference to this...
thread = new Thread(this, "Display");
thread.start();
}
By passing this (which is an instance of your Game class which implements Runnable), the Thread will be able to call your run method
nb:
The size of your viewable area should be defined by the component, not the frame. This can be achieved by overriding the getPreferredSize method and returning the preferred viewable size you want the component to be. Otherwise, the viewable area will be the size of the frame minus it's decoration insets, which may not meet your expectations.
In your "game-loop" you should consider having a small delay between cycles to give time for the system to actually update the screen, this takes some of the pressure of the Thread
Runnable example
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static int width = 300;
public static int height = width / 16 * 9;
public static int scale = 3;
private Thread thread;
private JFrame frame;
private boolean running = false;
public Game() {
Dimension size = new Dimension(width * scale, height * scale);
setPreferredSize(size);
frame = new JFrame();
}
public synchronized void start() {
running = true;
thread = new Thread(this, "Display");
thread.start();
}
public synchronized void stop() {
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
while (running) {
update();
render();
// try {
// Thread.sleep(40);
// } catch (InterruptedException ex) {
// }
}
}
public void update() {
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.RED);
g.fillRect(0, 0, getWidth(), getHeight());
g.dispose();
bs.show();
}
public static void main(String[] args) {
Game game = new Game();
game.frame.setResizable(false);
game.frame.setTitle("JJF");
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
game.start();
}
}
I have this really crappy sprite sheet that I made, which is basically just a bunch of circles and ovals so I can grasp Sprite animation.
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class CircleSprite extends JFrame implements ActionListener, Runnable{
BufferedImage circles;
BufferedImage[] test;
Timer timer;
int cycle = 0;
Graphics g = getGraphics();
public void asd(){
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
circles = ImageIO.read(new File("CircleTest.png"));
} catch (IOException e) {
e.printStackTrace();
}
final int width = 206;
final int height = 206;
final int rows= 2;
final int columns = 3;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test = new BufferedImage[rows * columns];
try{
for(int i = 0; i < rows; i++)
for(int j = 0;j<columns;j++)
{
test[i*columns + j] = circles.getSubimage(j * width, i * height, width, height);
}
}catch(Exception e){
e.printStackTrace();
}
timer = new Timer(500, this);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
//0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0, 1, 2, etc.
repaint();
g.drawImage(test[cycle], 25, 25, null);
if(cycle >= 5){
cycle--;
}
if(cycle <=0){
cycle++;
}
}
public void run(){
asd();
while(timer.isRunning() == false && this.isVisible() == true){
timer.start();
try {
CircleSpriteRun.t1.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The error occurs here: g.drawImage(test[cycle], 25, 25, null);
At first I though it had to do with the ImageObserver being null, and looking further into it, I was wrong. Now, I think it might be because of the timer, but I don't really know too much about Timers, let alone the swing one.
This all runs on a Thread being executed in another class, and it could also have to do with the while statement in the run method, since that also involves the timer.
Since you didn't provide a runnable example, I created one to show how to properly code a Swing application.
First, you must start a Swing application with the SwingUtilities.invokeLater method. Here's how I started the CircleSprite class.
public static void main(String[] args) {
SwingUtilities.invokeLater(new CircleSprite());
}
Second, you should use a JPanel for drawing, not a JFrame. Here's the DrawingPanel I created. My version of CircleSprite draws a circle in a random location every 2 seconds.
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = -4603711384104715819L;
private int x;
private int y;
private BufferedImage image;
public DrawingPanel(BufferedImage image) {
this.image = image;
this.x = 0;
this.y = 0;
setPreferredSize(new Dimension(500, 500));
}
public void setPoint(int x, int y) {
this.x = x;
this.y = y;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, x, y, null);
}
}
Third, you create the Swing GUI before you do anything with the Swing GUI. Here's the run method from the CircleSprite class. I create the GUI, then I start the thread that does the random drawing.
public void run() {
circle = createCircle();
frame = new JFrame("Circle Sprite");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawingPanel = new DrawingPanel(circle);
frame.add(drawingPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
new Thread(new RandomDraw(drawingPanel)).start();
}
Fourth, you only extend a Swing component when you want to override a method, like I did in the DraawingPanel class. You use Swing Components otherwise.
Here's the entire, runnable, CircleSprite class. You can use this as a model for future Swing applications.
package com.ggl.testing;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CircleSprite implements Runnable {
private BufferedImage circle;
private DrawingPanel drawingPanel;
private JFrame frame;
#Override
public void run() {
circle = createCircle();
frame = new JFrame("Circle Sprite");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawingPanel = new DrawingPanel(circle);
frame.add(drawingPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
new Thread(new RandomDraw(drawingPanel)).start();
}
private BufferedImage createCircle() {
BufferedImage image = new BufferedImage(100, 100,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 100, 100);
g.setColor(Color.BLUE);
g.fillOval(10, 10, 80, 80);
g.dispose();
return image;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new CircleSprite());
}
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = -4603711384104715819L;
private int x;
private int y;
private BufferedImage image;
public DrawingPanel(BufferedImage image) {
this.image = image;
this.x = 0;
this.y = 0;
setPreferredSize(new Dimension(500, 500));
}
public void setPoint(int x, int y) {
this.x = x;
this.y = y;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, x, y, null);
}
}
public class RandomDraw implements Runnable {
private DrawingPanel drawingPanel;
private Random random;
public RandomDraw(DrawingPanel drawingPanel) {
this.drawingPanel = drawingPanel;
this.random = new Random();
}
#Override
public void run() {
while (true) {
sleep();
int x = random.nextInt(400);
int y = random.nextInt(400);
drawingPanel.setPoint(x, y);
}
}
private void sleep() {
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
}
}
}
}
I've been getting this error when I run my game, not debug it for some reason :/ If anyone can help me with this bug than I'd greatly appreciate it, here's the error: (I'm new to the website)
Exception in thread "Display" java.lang.ArrayIndexOutOfBoundsException: 48600
at com.cmnatic.IndieFirstStudios.Game.render(Game.java:78)
at com.cmnatic.IndieFirstStudios.Game.run(Game.java:60)
at java.lang.Thread.run(Unknown Source)
Here is my code :
package com.cmnatic.IndieFirstStudios;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
import com.cmnatic.IndieFirstStudios.graphics.Screen;
public class Game extends Canvas implements Runnable {
/**
*
*/
private static final long serialVersionUID = 1L;
public static int width = 300;
public static int height = width / 16 * 9;
public static int scale = 3;
private Thread thread;
private JFrame frame;
private boolean running = false;
private Screen screen;
private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();
public Game() {
Dimension size = new Dimension(width * scale, height * scale);
setPreferredSize(size);
screen = new Screen(width, height);
frame = new JFrame();
}
public synchronized void start() {
running = true;
thread = new Thread(this, "Display");
thread.start();
}
public synchronized void stop() {
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
while (running == true) {
update();
render();
}
}
public void update() {
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
screen.render();
for (int i = 0; 1 < pixels.length; i++) {
pixels[i] = screen.pixels[i];
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
g.dispose();
bs.show();
}
public static void main(String[] args) {
Game game = new Game();
game.frame.setResizable(false);
game.frame.setTitle("Fallen Humanity");
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
game.start();
}
}
You have an infinite loop at line 78. Your saying run through the for loop if 1(one) < pixel.length. So eventually i will be > pixel.length
Just change the loop to:
for (int i = 0; i < pixels.length; i++) {
pixels[i] = screen.pixels[i];
}