java.lang.RuntimeException: No OpenGL context found in the current thread - java

im trying to create a applet for a little game i created. when i run the game normally (no applet) it works just fine but when im trying to run it as an applet it gives me the following error.
im using lwjgl 2.8.4 opengl
java.lang.RuntimeException: No OpenGL context found in the current thread.
java.lang.RuntimeException: Unable to create display
at com.base.engine.GameApplet.init(GameApplet.java:202)
at sun.applet.AppletPanel.run(AppletPanel.java:434)
at java.lang.Thread.run(Thread.java:722)
here is the code for the GameApplet.java
package com.base.engine;
import com.base.game.Game;
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;
public class GameApplet extends Applet {
Canvas display_parent;
/** Thread which runs the main game loop */
Thread gameThread;
/** is the game loop running */
private static boolean running = false;
private static Game game;
public void startLWJGL() {
//gameThread = new Thread() {
// #Override
//public void run() {
running = true;
try {
initDisplay();
Display.setParent(display_parent);
System.out.println("hij loopt");
//Display.create();
System.out.println("hij loopt");
initGL();
initGame();
gameLoop();
cleanUp();
} catch (LWJGLException e) {
return;
}
//gameLoop();
//}
//};
//gameThread.start();
}
private static void initGame()
{
game = new Game();
}
private static void getInput()
{
System.out.print("before input");
game.getInput();
System.out.print("after input");
}
private static void update()
{
game.update();
}
private static void render()
{
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
game.render();
Display.update();
Display.sync(60);
}
private static void gameLoop()
{
System.out.print("before while");
while(!Display.isCloseRequested())
{
while(running) {
System.out.print("before running shit");
Display.sync(60);
Display.update();
Display.destroy();
//getInput();
update();
render();
System.out.println("running gameLoop..");
}
}
System.out.print("after while");
}
private static void initGL()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, Display.getWidth(), 0, Display.getHeight(), -1, 1);
glMatrixMode(GL_MODELVIEW);
glDisable(GL_DEPTH_TEST);
glClearColor(0,0,0,0);
}
private static void cleanUp()
{
Display.destroy();
Keyboard.destroy();
}
private static void initDisplay()
{
try
{
Display.setDisplayMode(new DisplayMode(800,600));
Display.create();
Keyboard.create();
System.out.println("Keyboard created");
Display.setVSyncEnabled(true);
} catch (LWJGLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static ArrayList<GameObject> sphereCollide(float x, float y, float radius)
{
return game.sphereCollide(x, y, radius);
}
/**
* Tell game loop to stop running, after which the LWJGL Display will
* be destoryed. The main thread will wait for the Display.destroy().
*/
private void stopLWJGL() {
running = false;
}
#Override
public void start() {
//startLWJGL();
}
#Override
public void stop() {
}
/**
* Applet Destroy method will remove the canvas,
* before canvas is destroyed it will notify stopLWJGL()
* to stop the main game loop and to destroy the Display
*/
#Override
public void destroy() {
remove(display_parent);
super.destroy();
}
#Override
public void init() {
setLayout(new BorderLayout());
try {
display_parent = new Canvas() {
#Override
public final void addNotify() {
super.addNotify();
startLWJGL();
}
#Override
public final void removeNotify() {
stopLWJGL();
super.removeNotify();
}
};
display_parent.setSize(800,600);
add(display_parent);
System.out.println("gaat ie lekker");
display_parent.setFocusable(true);
display_parent.requestFocus();
display_parent.setIgnoreRepaint(true);
setVisible(true);
} catch (Exception e) {
System.err.println(e);
throw new RuntimeException("Unable to create display");
}
}
}
can someone tell me what im doing wrong?

Related

Java Applet Adding and Removing labels

I am trying to make code that adds a label when I click and then removes the label when I press e. Can someone help me do this
I added the labels and I got it to compile but the label won't show up and its for my graphics project I worked on it really hard
import java.awt.geom.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;
import java.awt.Label;
public class Volcano_Client extends Applet implements MouseListener, KeyListener, Runnable
{
Label label1;
boolean pickE=false;
boolean play = true;
boolean makeLava=false;
Thread t;
Thread thr;
Thread th;
boolean mouseEntered;
int count;
Volcano v1;
public void init()
{
label1 = new Label("You see lava flowing down as you press e");
v1 = new Volcano();
thr=new Thread(this);
thr.start();
t=new Thread(this);
t.start();
th= new Thread(this);
count=0;
addMouseListener(this);
addKeyListener(this);
}
public void keyTyped(KeyEvent k)
{
}
public void keyReleased(KeyEvent k)
{
}
public void keyPressed(KeyEvent k)
{
if(k.getKeyCode() ==KeyEvent.VK_E)
{
pickE=true;
repaint();
k.consume();
}
}
public void mouseExited(MouseEvent me)
{
mouseEntered=false;
repaint();
}
public void mousePressed(MouseEvent me)
{
}
public void mouseReleased(MouseEvent me)
{
}
public void mouseEntered(MouseEvent me)
{
mouseEntered=true;
repaint();
}
public void mouseClicked(MouseEvent me)
{
if(mouseEntered==true)
{
makeLava=true;
}
else
{
makeLava=false;
}
repaint();
}
public void run()
{
while(play==true)
{
try
{
Thread.sleep(100);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
repaint();
}
while(true)
{
try{
Thread.sleep(20);
}
catch(Exception e){};
repaint();
}
}
public void stop()
{
}
public void start()
{
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
label1 = new Label("You see lava flowing down as you press e");
v1.makeVolcano(g2);
if(makeLava)
{
v1.makeLavaUp(g2);
g.setColor(Color.black);
g.drawString("KABOOM!!!",200,70);
add(label1);
}
else
{
g.setColor(Color.white);
g.drawString("Please Click For Eruption part 1",160,250);
}
if(pickE)
{
v1.makeLavaFlow(g2);
remove(label1);
}
else
{
//g.setColor(Color.white);
//g.drawString("Please press 'E' for Eruption part 2",160,276);
}
}
}
To display the label, below is modified init() function:
public void init()
`{`
`label1 = new Label("You see lava flowing down as you press e");`
//v1 = new Volcano();
thr=new Thread(this);
thr.start();
t=new Thread(this);
t.start();
th= new Thread(this);
count=0;
addMouseListener(this);
addKeyListener(this);
add(label1); //to display label
}

"Run" Method Not Working

Hey guys I'm new to Java game programming and I'm working with the Runnable interface right now. For some reason, my run() method never gets called and I'm not sure why. I've tried putting many System.out.println statements in there but they never get printed. Any help would be greatly appreciated!
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
public class GamePanel extends JPanel implements Runnable
{
private final int WIDTH = 160;
private final int HEIGHT = WIDTH/12 *9;
private final int RATIO = 3;
private Thread animator;
private volatile boolean running;
private volatile boolean gameOver;
private double FPS = 60D;
private double period = 1000/FPS;
private Image dbImage;
private Graphics dbg;
public GamePanel()
{
setPreferredSize(new Dimension(WIDTH *3, HEIGHT*3));
setBackground(Color.WHITE);
setFocusable(true);
requestFocus();
terminate();
}
public void addNotify()
{
super.addNotify();
startGame();
}
public void startGame()
{
System.out.println("Thread started");
animator = new Thread();
animator.start();
}
public void stopGame()
{
System.out.println("Thread stopped");
running = false;
}
public void run()
{
long beforeTime, timeDiff, sleepTime;
beforeTime = System.currentTimeMillis();
System.out.println(beforeTime);
running = true;
while (running)
{
System.out.println("Running");
gameUpdate();
gameRender();
paintScreen();
timeDiff = System.currentTimeMillis() - beforeTime;
sleepTime = (long) period - timeDiff;
if(sleepTime <= 0)
sleepTime = 5;
try
{
Thread.sleep(sleepTime);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
beforeTime = System.currentTimeMillis();
}
System.exit(0);
}
public void gameRender()
{
if (dbImage == null)
{
dbImage = createImage(WIDTH, HEIGHT);
}
else
dbg = dbImage.getGraphics();
dbg.setColor(Color.WHITE);
dbg.fillRect(0, 0, WIDTH, HEIGHT);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(dbImage, 0, 0, null);
}
public void gameUpdate()
{
}
private void paintScreen()
{
Graphics g;
try
{
g = this.getGraphics();
if (g!= null && dbImage!= null)
g.drawImage(dbImage, 0, 0, null);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
}
}
public void terminate()
{
addKeyListener (new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_ESCAPE)
{
stopGame();
}
}
});
}
}
import javax.swing.JFrame;
public class GameFrame extends JFrame
{
private final int WIDTH = 160;
private final int HEIGHT = WIDTH/12*9;
private final int RATIO = 3;
public GameFrame()
{
setTitle("User Input Game");
setSize(WIDTH*3,HEIGHT*3);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
GamePanel mainPanel = new GamePanel();
add(mainPanel);
}
}
public class Main
{
public static void main(String[] args)
{
new GameFrame().setVisible(true);
}
}
You need to change your startGame() method:
animator = new Thread(new GamePanel());
You need to pass a Runnable (of which GamePanel is one) into the Thread constructor. The thread then runs the runnable when it starts.
You don't seem to have a main method anywhere. Either in this class or an external class you need a main method that creates an instance of GamePanel and pass it as an argument to a Thread class. Like so:
public class Test
{
public static void main(String[] args)
{
Thread t = new Thread(new GamePanel()).start();
}
}

Eclipse ADT Applet blank screen

I'm trying to show some images on my applet and have them move around but whenever I run my project through the applet all I get is a blank/black screen. I can change the color of the background, but I can't see any of my images. Also, the applet isn't initialized when I try to start the applet. Here's the code:
package test;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.net.URL;
public class MCTaRE extends Applet implements Runnable, KeyListener {
private Character character;
private Image image, robot;
private Graphics graphics;
private URL base;
#Override
public void init() {
setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Test");
robot = getImage(base, "data/character.png");
}
#Override
public void start() {
Thread thread = new Thread(this);
thread.start();
character = new Character();
}
#Override
public void stop() {
}
#Override
public void run() {
while (true) {
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void update(Graphics g) {
if (image == null) {
image = createImage(this.getWidth(), this.getHeight());
graphics = image.getGraphics();
}
// graphics.setColor(getBackground());
graphics.fillRect(0, 0, getWidth(), getHeight());
// graphics.setColor(getForeground());
paint(graphics);
g.drawImage(image, 0, 0, this);
}
#Override
public void paint(Graphics g) {
g.drawImage(robot, character.getInitX() - 61,
character.getInitY() - 63, this);
}
public void KeyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_SPACE:
System.out.println("Space");
break;
}
}
public void KeyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
package test;
public class Character {
private int initX = 100;
private int initY;
private int speedX = 0;
public void update(){
//if (key listener is at the top){
moveLeft();
//}
//else {
stop();
//}
initY = 200;
}
public int getInitX() {
return initX;
}
public int getInitY() {
return initY;
}
public int getSpeedX() {
return speedX;
}
public void setInitX(int initX) {
this.initX = initX;
}
public void setInitY(int initY) {
this.initY = initY;
}
public void setSpeedX(int speedX) {
this.speedX = speedX;
}
public void moveLeft(){
speedX = -5;
}
public void stop(){
speedX = 0;
}
}
Any help would be greatly appreciated I need to make this work. I can try to use an AVD but I think that would complicate things even more. And a JApplet isn't an option.
"but I can't see any of my images."
You have a few options loading the images.
I like to use getClass().getResource("/path/to/image") as it load from the class path, which is used from embedded resources.
try {
robot = ImageIO.read(getClass().getResource("/data/character.png"));
} catch (IOException ex) {
ex. printStackTrace();
}
You could do the same thing using ImageIcon.getImage where you can avoid the try/catch but I prefer the former, so you can get exception if path is incorrect
robot = new ImageIcon(getClass().getResource("/data/character.png")).getImage();
For Applet, you can use getCodeBase() as seen here
try {
URL url = new URL(getCodeBase(), "data/character.png");
robot = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
}
NOTE: All three options will work with your code (just tested all), given your file structure is as follows, with data in the src
ProjectRoot
src
data
character.png
test
MCTaRE.java
Side Note
You are not calling super.paint in your paint method, which will leave you with paint artifacts. So call it
#Override
public void paint(Graphics g) {
super.paint(g);
Why code an Applet in the first place. If it must be an Applet, why AWT Applet and not Swing JApplet. If this is a class assignment, have your professor read Why CS teachers should stop teaching Java applets
If you want to ditch the zero (AWT) and get with the hero (Swing), read more at Creating GUI with Swing

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.

Cannot Load Texture in Java (lwjgl)

I have been going about on this for the past 3 hours.
I'm trying to make a 2D Strategy game in Java using the lwjg libraries, and for starters, I've got stuck at loading a texture for an object (Farmer).
Its giving me this:
Exception in thread "main" java.lang.NullPointerException
at _2nd_Branch.Farmer.render(Farmer.java:42)
at _1st_Branch.CoreGame.render(CoreGame.java:30)
at _1st_Branch.Game.GameLoop(Game.java:33)
at _1st_Branch.Game.main(Game.java:13)
Here is the code I've been working on (As a way to organize things. Got this from someone on youtube explaining some bits about lwjgl):
Game.java:
package _1st_Branch;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
public class Game {
private static CoreGame coreGame;
public static void main(String [] args)
{
CD();
createGame();
GameLoop();
CleanUp();
}
private static void CD()
{
Window.create(800, 600);
}
private static void createGame()
{
coreGame = new CoreGame();
}
public static void GameLoop()
{
while(!Window.isCloseRequested())
{
Window.Clear();
coreGame.input();
coreGame.logic();
coreGame.render();
Display.update();
if(Keyboard.isKeyDown(Keyboard.KEY_ESCAPE))
{
Display.destroy();
System.exit(0);
}
}
}
private static void CleanUp()
{
coreGame.dispose();
Window.Destroy();
}
}
CoreGame.java:
package _1st_Branch;
import _2nd_Branch.Farmer;
import _2nd_Branch.Player;
public class CoreGame {
public final static int TILE_SIZE = 64;
private static Player player;
private static Farmer farmer;
public CoreGame()
{
farmer = new Farmer();
}
public void input()
{
}
public void logic()
{
}
public void render()
{
farmer.render();
}
public void dispose()
{
}
}
Window.java:
package _1st_Branch;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;
public class Window {
public static void create(int width, int height)
{
try
{
Display.setDisplayMode(new DisplayMode(width, height));
Display.setTitle("Artyas RTS");
Display.create();
initGL();
initInput();
}
catch (LWJGLException e)
{
e.printStackTrace();
}
}
public static void initGL()
{
glClearColor(0.5f, 0.5f, 1, 1);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, Display.getWidth(), 0, Display.getHeight(), -1, 1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glLoadIdentity();
}
private static void initInput()
{
try
{
Keyboard.create();
}
catch (LWJGLException e)
{
e.printStackTrace();
}
}
public static void Clear()
{
glClear(GL_COLOR_BUFFER_BIT);
}
public static void Destroy()
{
Keyboard.destroy();
Display.destroy();
System.exit(0);
}
public static void update()
{
Display.update();
Display.sync(60);
}
public static boolean isCloseRequested()
{
return Display.isCloseRequested();
}
}
Farmer.java:
//CIVILIAN UNIT
package _2nd_Branch;
import java.io.IOException;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.Color;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;
public class Farmer {
public Farmer() {};
private Texture texture;
public void init() {
try {
// load texture from PNG file
texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("Farmer.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void render()
{
Color.white.bind();
texture.bind();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0,0);
GL11.glVertex2f(400,500);
GL11.glTexCoord2f(1,0);
GL11.glVertex2f(450,500);
GL11.glTexCoord2f(1,1);
GL11.glVertex2f(450, 550);
GL11.glTexCoord2f(0,1);
GL11.glVertex2f(400, 550);
GL11.glEnd();
}
}
I am literally stuck here. If someone could indicate what needs to be done, I will be eternally grateful! I really need to get going on making this project, to learn more about Java.
The texture.bind() function from the Farmer class gives me the error.
Being stuck here, I don't know what it says about me as a programmer.
You never call Farmer.init() which loads the texture. You only call the constructor in CoreGame. Either you should call init() from inside the Farmer constructor or call init after calling the constructor in CoreGame. I recommend calling init() from CoreGame, and continue to keep texture loading away from the constructor simply because if you initialize and have to call the constructor to Farmer before you have created your display and initialized OpenGL (Window.initGL()) you don't want to load the texture. Loading a texture with slick before the display is created and opengl is initialized can cause a NullpointerException in TextureLoader.

Categories

Resources