Keyevent getID causing error - java

I am trying to make a game where the character is a 75x75 object, and he moves around the screen. However, when I run my code, I get the error:
java.lang.IllegalArgumentException: Invalid display mode
at sun.awt.Win32GraphicsDevice.setDisplayMode(Unknown Source)
at sylvyrfysh.Screen.setFullScreen(Screen.java:17)
at sylvyrfysh.ImageDrawer.run(ImageDrawer.java:26)
at sylvyrfysh.ImageDrawer.main(ImageDrawer.java:17)
at sylvyrfysh.Main.main(Main.java:7)
I am not sure what is causing this, as I made another project with the same DisplayMode arguments, and it worked fine.
package sylvyrfysh;
import game.infos.Information;
import java.awt.*;
import javax.swing.*;
public class ImageDrawer extends JFrame{
/**
*
*/
private static final long serialVersionUID = -4278324581016693552L;
public static void main() throws InterruptedException{
DisplayMode dm=new DisplayMode(Information.sX,Information.sY,16,DisplayMode.REFRESH_RATE_UNKNOWN);
ImageDrawer i=new ImageDrawer();
i.run(dm);
}
private void loader(){
bg=new ImageIcon("src/sylvyrfysh/maze_icon.png").getImage();
chara=new ImageIcon("src/sylvyrfysh/char.png").getImage();
}
private void run(DisplayMode dm){
System.out.println("HI");
loader();
s=new Screen();
s.setFullScreen(dm,this);//error here
repaint();
while(EHandler.run){
if(rp){
repaint();
rp=false;
}
}
}
public void paint(Graphics g){
g.drawImage(bg,0,0,null);
g.drawImage(bg,360,0,null);
g.drawImage(bg,720,0,null);
g.drawImage(bg,0,480,null);
g.drawImage(bg,360,480,null);
g.drawImage(bg,720,480,null);
g.drawImage(chara,imgX,imgX,null);
}
private Image bg,chara;
Screen s;
public static int imgX=0;
public static int imgY=525;
public static Boolean rp=false;
}
Any help would be appreciated.

The ability to change graphics device's
display mode is platform- and configuration-dependent and may not always be available. GraphicsDevice.isDisplayChangeSupported() should be used to check prior to change the display mode on graphics device.
Some other important suggestion are made here nicely.

Related

Proper way to create an image with paintCompnent method - Java

I am working on an assignment and I need to first create a simple GUI that displays a picture/gif on it. However I need to use the paintComponent method, which I am struggling with.
Here is the code I have so far:
import javax.swing.*; import java.awt.Graphics.*;
public class HelloGIF extends JFrame {
image1 =Toolkit.getDefaultToolkit().createImage("C:\\Users\\carlo\\Documents\\Carlo's Documents\\ITEC 2610\\Java Files\\HelloGIF\\BT-Thumbsup.gif");
public HelloGIF(String title) {
super(title);
setBounds(75,75,750,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image1, 200, 150, 50,50,this);
}
public static void main(String[] args){
System.out.println("Initializing...");
HelloGIF myApp = new HelloGIF(String.join("+",args));
myApp.setVisible(true);
}
}
At the moment compiling generates an "identfier expected" on "C:\Users\carlo\Documents\Carlo's Documents\ITEC 2610\Java Files\HelloGIF\BT-Thumbsup.gif", pointing to the I in 'HelloGIF'. what declaration should I add? Am I on the right track or am I totally off?

glfwGetPrimaryMonitor() NullPointerException

I'm learning how to make a Java game with ThinMatrix's LWJGL 2 tutorials that I'm adapting to LWJGL 3. Anyway, I can't get the game to detect my monitors. This was working fine just a few days ago on the exact same system with the exact same hardware.
I have tried installing the drivers for them, uninstalling the drivers, and uninstalling the monitors completely from Device Manager. Nothing works. If you need any more information just let me know!
Here is my source code:
Main.java:
package engineTest;
import static org.lwjgl.glfw.GLFW.*;
import static renderEngine.displayManager.*;
public class Main {
public static void main(String[] args) {
window = glfwCreateWindow(WIDTH, HEIGHT, "Farm Game", glfwGetPrimaryMonitor(), 0);
while(!glfwWindowShouldClose(window)) {
updateDisplay();
}
glfwDestroyWindow(window);
}
}
displayManager.java
package renderEngine;
import static org.lwjgl.glfw.GLFW.*;
import org.lwjgl.opengl.GL11;
public class displayManager {
public static int WIDTH = 1280;
public static int HEIGHT = 720;
private static int FPS_CAP = 120;
public static long window;
public static void createDisplay() {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GL11.glViewport(0, 0, WIDTH, HEIGHT);
}
public static void updateDisplay() {
glfwPollEvents();
glfwSwapBuffers(FPS_CAP);
}
public static void closeDisplay() {
glfwDestroyWindow(window);
}
}
Here is the error output.
Exception in thread "main" java.lang.NullPointerException
at org.lwjgl.system.Checks.check(Checks.java:99)
at org.lwjgl.glfw.GLFW.glfwWindowShouldClose(GLFW.java:1874)
at engineTest.Main.main(Main.java:13)
Edit
I have been trying to debug the NullPointerException, and I know what is causing it. The problem is I don't know how to fix it. Sorry, I'm pretty new to Java.
You have to call glfwInit() before you can use any other glfw method. Since this is missing, glfwCreateWindow always returns a nullptr.

Graphics Issue with JFrame in a Game Engine

I'm creating a "simple" 2D game engine for the block game Collapse for my college class. I am trying to make it such that the JFrame is resized any time a new screen is introduced, and I have made two attempts at it, one that resizes correctly, but doesn't show anything, and one that shows SOMETHING, but doesn't resize.
For this post, I will be showing the code for the second game engine that I have created, as my first attempt was a monolithic version that I ended up having trouble following myself.
First off, for some reason the window will not close with the X button, even though the setDefaultCLoseOperation(JFrame.EXIT_ON_CLOSE) is enacted.
Second (for the second attempt) the JFrame will not resize, but will show a sliver of the test StartMenu
(sorry for links, editor said I have to have rep of 10 before being able to post pictures... smart move, but still annoying)
http://i1148.photobucket.com/albums/o577/FoxnEagle/GraphicsWindow1_zpscqdgsjqh.png
but upon resizing;
http://i1148.photobucket.com/albums/o577/FoxnEagle/GraphicsWindow2_zpsckr4eohs.png
I guess the question of the post is what am I doing wrong to have the window become unresponsive, and be able to make modern art with it?
Collapse.java
import gameEngine.*;
import screens.*;
import javax.swing.*;
public class Collapse{
private Game game;
public Collapse(){
this.game = new Game("Test", null);
game.getScrMan().setScreen(new StartMenu(game.getScrMan()));
}
public static void main(String[] args){
new Collapse();
}
}
:||package screens||:
StartMenu.java
package screens;
import gameEngine.*;
import java.awt.*;
import javax.swing.*;
public class StartMenu extends Screen{
private final ScreenManager scrMan;
public StartMenu(ScreenManager scrMan){
super(scrMan);
this.scrMan = scrMan;
}
public void onCreate(){
JButton b1 = new JButton();
scrMan.getScrMan().setSize(200, 200);
scrMan.getScrMan().add(b1);
System.out.println("got here");
}
public void onUpdate(){
}
public void onDraw(Graphics2D g2d){
g2d.setColor(Color.BLACK);
g2d.fillOval(10, 10, 10, 10);
}
public void paintComponent(Graphics g){
g.setColor(Color.BLACK);
g.fillOval(10,10,10,10);
}
}
:||package gameEngine||:
Game.java
package gameEngine;
import javax.swing.*;
import java.awt.*;
public class Game{
private final ImageIcon image;
private final String title;
private final GameLoop gameLoop;
private final ScreenManager scrMan;
private final InputManager inpMan;
private final EntityManager entMan;
private JFrame window;
private boolean running;
//constructor and initializer for gameLoop
public Game(String title, ImageIcon image){
this.title = title;
this.image = image;
window = new JFrame();
scrMan = new ScreenManager(this);
inpMan = new InputManager();
entMan = new EntityManager();
gameLoop = new GameLoop(this);
initialize();
SwingUtilities.invokeLater(gameLoop);
}
private void initialize(){
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //close on exit
window.setTitle(title); //set the title
if(image != null){} //set the image icon NOT IMPLEMENTED YET
//window.setResizable(false); //user cannot resize
window.setFocusable(true); //
window.setLocationRelativeTo(null); //put in center of screen
window.add(scrMan); //add the
window.pack();
window.setVisible(true);
running = true;
}
public JFrame getWindow(){return window;}
public boolean getRunning(){return running;}
public ScreenManager getScrMan(){return scrMan;}
public InputManager getInput(){return inpMan;}
public EntityManager getEntMan(){return entMan;}
public void paused(){running = false;}
public void resume(){running = true;}
}
GameLoop.java
package gameEngine;
import java.lang.Runnable;
public class GameLoop implements Runnable{
private final Game game;
private long time;
private final int fps = 30;
public GameLoop(Game game){this.game = game;}
public void run(){
while(true){
while(game.getRunning()){
//System.out.println("running");//debugging
if(game.getScrMan().getScreen() != null){
game.getScrMan().getScreen().onUpdate();
//System.out.println("screen is updating");//debugging
}
//fps clock, commenting out does not fix problem
time = System.currentTimeMillis();
time = (1000/fps) - (System.currentTimeMillis() - time);
if(time > 0){try{Thread.sleep(time);}catch(Exception e){}}
}
}
}
}
ScreenManager.java
package gameEngine;
import javax.swing.JPanel;
import java.awt.*;
public class ScreenManager extends JPanel{
private final Game game;
private Screen screen;
public ScreenManager(Game game){this.game = game;}
public void setScreen(Screen screen){
this.screen = screen;
this.removeAll();
screen.onCreate();
game.getWindow().revalidate();
//game.getWindow().pack();
}
public Screen getScreen(){return screen;}
public Game getGame(){return game;}
public ScreenManager getScrMan(){return this;}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillOval(0,0, 10, 10);
}
}
Screen.java (StartMenu extends and overrides all functions)
package gameEngine;
import java.awt.Graphics;
import java.awt.Graphics2D;
public abstract class Screen{
private final ScreenManager scrMan;
public Screen(ScreenManager scrMan){this.scrMan = scrMan;}
public abstract void onCreate();
public abstract void onUpdate();
public abstract void onDraw(Graphics2D g2d);
}
InputManager.java (nothing implemented yet, just a placeholder)
package gameEngine;
import java.awt.event.*;
public class InputManager implements KeyListener, MouseListener{
public void mouseClicked(MouseEvent event){
}
public void mouseEntered(MouseEvent event){
}
public void mouseExited(MouseEvent event){
}
public void mousePressed(MouseEvent event){
}
public void mouseReleased(MouseEvent event){
}
public void keyPressed(KeyEvent event){
}
public void keyReleased(KeyEvent event){
}
public void keyTyped(KeyEvent event){
}
}
EntityManager.java and Entity.java are just blank classes
This,
SwingUtilities.invokeLater(gameLoop);
runs your game loop in the event dispatch thread, blocking it. So the repaint manager never has a change to draw the contents. You should instead create the GUI in the event dispatch thread, as modifying or creating swing components from other threads is not safe.
The game loop's timing needs to be done in a way that does not block the EDT. The easiest is using a swing Timer; if that proves later to be insufficient, you can switch to another solution, but then you need to pay close attention to thread safety. Swing timer runs the action listener code in the EDT so it's easy to be thread safe that way.

Overiding a method wont work

I am trying to make my own engine but I need some help.
I am currently doing the level system. The level class extends the render class and the level class overides the Render classes render method. Finally the render class is called from the main class but I dont call the level class.
EDIT:
I have removed the static but now cannot call the render method. I know I am very nooby I kind of teach my self.
package SimpleEngine.Render;
Render Class (This is called)
import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT;
import SimpleEngine.Primitives.*;
import static org.lwjgl.opengl.GL11.glClear;
public class Render {
public void Render() {
}
}
Level Class (This is not called) I want this Render method to override the Render classes render method but it doesn't work.
package SimpleEngine.Level;
import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.glClear;
import SimpleEngine.Render.*;
import SimpleEngine.Primitives.*;
public class Level extends Render {
public void Render() {
glClear(GL_COLOR_BUFFER_BIT);
Primitives.DrawSquare(200, 200, 50, 50, 1, 0, 0);
}
}
My main method (calls render but cannot anymore)
package SimpleEngine;
import org.lwjgl.LWJGLException;
import SimpleEngine.Level.*;
import SimpleEngine.Logic.*;
import SimpleEngine.Input.*;
import SimpleEngine.Render.*;
import SimpleEngine.Entites.*;
import SimpleEngine.Timer.*;
import org.lwjgl.Sys;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;
public class simpleEngine {
public static final int WIDTH = 640;
public static final int HEIGHT = 480;
private static boolean isRunning = true;
public static void main(String[] args) {
setUpDisplay();
setUpOpenGL();
Entity.setUpEntities();
Timer.setUpTimer();
while (isRunning) {
Render.Render();
Logic.logic(Timer.getDelta());
Input.input();
Display.update();
Display.sync(60);
if (Display.isCloseRequested()) {
isRunning = false;
}
}
Display.destroy();
System.exit(0);
}
private static void setUpDisplay() {
try {
Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT));
Display.setTitle("SimpleEngine");
Display.create();
} catch (LWJGLException e) {
e.printStackTrace();
Display.destroy();
System.exit(1);
}
}
private static void setUpOpenGL() {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 640, 480, 0, 1, -1);
glMatrixMode(GL_MODELVIEW);
}
}
You can't override static methods.
As per Oracle tutorail
If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass.
AND
You will get a compile-time error if you attempt to change an instance method in the superclass to a class method in the subclass, and vice versa.
Remove static from Render class render() method and change Level class Render method to render() to introduce overriding behavior
EDIT:
while (isRunning) {
new Level().Render();
Note: Java naming convention suggests that method name should start with small letter and name should be camelcase.
You can't override a static method.
Also, be careful because Java is a case sensitive language, so Render() is not the same as render(), and could be a completely different method.
I would recommend doing something more generic such as having an interface which defines common methods for any state your game could be in which actually looks like the direction you're heading in. This would just combine your Logic and Render classes. For example:
public Interface IGameState {
public void update(int delta);
public void render();
}
And then you can have a class that implements that interface such as:
public class InGameState implements IGameState {
public InGameState() { }
// This is similar to your Logic class
public void update(int delta) {
// Perform any updates necessary such as handling keyboard input
}
public void render() {
// What you included in your example
glClear(GL_COLOR_BUFFER_BIT);
Primitives.DrawSquare(200, 200, 50, 50, 1, 0, 0);
}
}
And then your main method could look something like this:
public static final int WIDTH = 640;
public static final int HEIGHT = 480;
private static boolean isRunning = true;
private IGameState currentGameState;
public static void main(String[] args) {
setUpDisplay();
setUpOpenGL();
Entity.setUpEntities();
Timer.setUpTimer();
// Create a new game state
currentGameState = new InGameState();
while (isRunning) {
// Change to this type of thing
// The delta would be the time since last frame so you can stay frame rate
// independent
currentGameState.update(delta);
currentGameState.render();
Display.update();
Display.sync(60);
if (Display.isCloseRequested()) {
isRunning = false;
}
}
Display.destroy();
System.exit(0);
}

static variable doesn't change

I started using jMonekyEngine and it's easy way of interacting with Swing GUI.
Following their tutorial here http://jmonkeyengine.org/wiki/doku.php/jme3:advanced:swing_canvas
It all works and I get everything loaded,however I'm having trouble modifying things.
According to their tutorial, the constant update and happens here:
public void simpleUpdate(float tpf) {
geom.rotate(0, 2 * tpf, 0);
}
(this is an example from the tutorial on rotating objects).
what i'm trying to do is just increasing and decreasing the speed of rotation (by changing the 2 or tpf with a variable which gets update inside an ActionListener in the Swing gui.
However, since in their tutorial they stated that the swing gui is to be created inside the main method, I have to create a variable which is static in order to change it.
static float rotate = 0.0f;
it gets modified inside the main method, but when trying to use it like so:
public void simpleUpdate(float tpf) {
geom.rotate(0, rotate * tpf, 0);
}
it remains constant to the initial value.
I tried creating a GUI class to build the gui (extends JPanel) and using getters and setters, but still not go..
Any help would be appreciated!
Thanks!
EDIT:
Here's how I change the rotate value:
JButton faster = new JButton("Faster");
faster.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
rotate +=0.1f;
}
});
inside the main method. rotate is a static field.
This is working for me
http://test.jmonkeyengine.org/wiki/doku.php/jme3:beginner:hello_main_event_loop
http://test.jmonkeyengine.org/wiki/doku.php/jme3:beginner:hello_input_system?s[]=input
Is your action listener really triggering the event on click? maybe you have a problem there and not in the rotate variable. Note that I'm not using swing on this example..
import com.jme3.app.SimpleApplication;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Box;
/** Sample 4 - how to trigger repeating actions from the main update loop.
* In this example, we make the player character rotate. */
public class HelloLoop extends SimpleApplication {
public static void main(String[] args){
HelloLoop app = new HelloLoop();
app.start();
}
protected Geometry player;
#Override
public void simpleInitApp() {
Box b = new Box(Vector3f.ZERO, 1, 1, 1);
player = new Geometry("blue cube", b);
Material mat = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", ColorRGBA.Blue);
player.setMaterial(mat);
rootNode.attachChild(player);
initKeys();
}
/* This is the update loop */
#Override
public void simpleUpdate(float tpf) {
// make the player rotate
player.rotate(0, val*tpf, 0);
}
float val = 2f;
private void initKeys() {
// Adds the "u" key to the command "coordsUp"
inputManager.addMapping("sum", new KeyTrigger(KeyInput.KEY_ADD));
inputManager.addMapping("rest", new KeyTrigger(KeyInput.KEY_SUBTRACT));
inputManager.addListener(al, new String[]{"sum", "rest"});
}
private ActionListener al = new ActionListener() {
public void onAction(String name, boolean keyPressed, float tpf) {
if (name.equals("sum") ) {
val++;
}else if (name.equals("rest")){
val--;
}
}
};
}

Categories