Graphics not Showing - java

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?

Related

Why doesn't my screen turn red?

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();
}
}

Changing which main() to run in eclipse

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.

JFrame Java setColor and fillRect staying Blank?

Why am I getting a Blank screen instead of Black when I debug or run?? I've looked everywhere and tried a lot! Please help. I'm just trying to make my screen black as I am a beginner to all of this java coding. I don't believe anything is wrong with the code as I'm not getting any errors. I'm using eclipse.
package com.techon.rain;
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 JFrame frame;
private Thread thread;
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();
}
}
public void update() {
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if(bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
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("Rain");
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
game.start();
}
}
replace
public void run() {
while(running);{
update();
render();
}
by
public void run() {
while(running){
update();
render();
}
due to while(running); it is not executing other stetement inside loop.

Why Won't the Screen Change Color?

I've been trying to fix but it never changes the screen. I'm trying to used the Graphics as seen in the render() method. Tell me if something is wrong inside the render method so I can relax, because I can't seem to find the problem.
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.*;
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 boolean running = false;
private JFrame frame;
public synchronized void start() {
thread = new Thread();
thread.start();
running = true;
}
public synchronized void stop() {
running = false;
try{
thread.join();
}catch(InterruptedException e) {
e.printStackTrace();
}
}
public Game() {
Dimension size = new Dimension(width * scale, height * scale);
setPreferredSize(size);
frame = new JFrame();
}
public void run() {
while(running) {
tick();
render();
}
}
void tick() {}
public void render() {
BufferStrategy bs = getBufferStrategy();
if(bs==null){
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
bs.dispose();
bs.show();
}
public static void main(String[] args) {
Game game = new Game();
game.frame.setResizable(false);
game.frame.setTitle("Rain");
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
game.start();
}
}
Let me give you a stack trace of your error.
Your render method is not even being called here.
This is because your run method is not being called at all.
The reason behind all this is that you have not passed correct Runnable object at the time of Thread creation. It creates a Thread with empty run.
In your start method, just replace
thread = new Thread();
with
thread = new Thread(this);
And it should work.
Hope this helps. Enjoy.

createBufferStrategy(3); not working

I have code like that :
private int[] pixels;
BufferStrategy bs = this.getBufferStrategy();
if(bs == null) {
createBufferStrategy(3);
return;
}
it returns an error on line 2 in the code example :
Syntax error on token ; { expected after this token.
And returns error on the last line (}) in the code example :
Insert } to complete block.
This is my first time working with canvas, and when i get those annoying errors i freak out,
but this error freak me out to the next level..
FULL CODE OF THE MAIN CLASS :
package game.display;
import game.display.graphics.Render;
import game.display.graphics.Screen;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
public class Display extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 800;
public static final int HEIGHT = 600;
public static final String TITLE = "Ultimate Game | Pre alpha 0.01";
private Thread thread;
private Boolean isRunning = false;
private Render render;
private Screen screen;
private BufferedImage img;
private int[] pixels;
BufferStrategy bs = this.getBufferStrategy();;
if(bs == null) {
createBufferStrategy(3);
return;
}
public Display() {
screen = new Screen(WIDTH, HEIGHT);
img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
}
private void start() {
if (isRunning)
return;
isRunning = true;
thread = new Thread(this);
System.out.println("Initialize the thread game!");
thread.start();
System.out.println("The thread has initialized!");
System.out.println("The game has started!");
}
private void stop() {
if (!isRunning)
return;
isRunning = false;
System.out.println("The game stopped!");
System.out.println("Stopping the thred!");
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(0);
}
}
public void run() {
while (isRunning) {
System.out.println("The Game is Running!");
tick();
render();
}
}
private void tick() {
}
private void render() {
bs = this.getBufferStrategy();
screen.render();
for(int i = 0; i < WIDTH * HEIGHT; i++) {
pixels[i] = screen.pixels[i];
}
Graphics g = bs.getDrawGraphics();
g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
g.dispose();
bs.show();
}
public static void main(String[] args) {
System.out.println("The program called!");
System.out.println("Initialize the display and the JFrame!");
Display game = new Display();
JFrame frame = new JFrame();
frame.add(game);
frame.pack();
frame.setTitle(TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
System.out.println("Starting the game!");
game.start();
}
}
Th code should be in a method like this.
void method(){
BufferStrategy bs = this.getBufferStrategy();;
if(bs == null) {
createBufferStrategy(3);
return;
}
}

Categories

Resources