Trouble with JOGL and Visual Studio Code - java

I'm new to OpenGL in Java, and Java in general. I am following a textbook and trying to create my first window. However, when I run my code, I get the error that "package com.jogamp.opengl does not exist". I have added the .JAR files to my project's reference libraries as shown.
My code reads:
import javax.swing.*;
import static com.jogamp.opengl.GL4.*;
import com.jogamp.opengl.*;
import com.jogamp.opengl.awt.GLCanvas;
public class Code extends JFrame implements GLEventListener {
private GLCanvas myCanvas;
public Code() {
setTitle("Chapter 2 - program 1");
setSize(600, 400);
setLocation(200, 200);
myCanvas = new GLCanvas();
myCanvas.addGLEventListener(this);
this.add(myCanvas);
this.setVisible(true);
}
public void display(GLAutoDrawable drawable) {
GL4 gl = (GL4) GLContext.getCurrentGL();
gl.glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
gl.glClear(GL_COLOR_BUFFER_BIT);
}
public static void main(String[] args) {
new Code();
}
public void init(GLAutoDrawable drawable) {
}
public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
}
public void dispose(GLAutoDrawable drawable) {
}
}
Any advice would be great - I'm guessing it is some simple step I've missed, but I've gone over the section in the book a couple of times now so I'm nto sure what I'm missing.

You have to add jogamp-fat.jar into the classpath. Please rather ask your JOGL specific questions on the official JogAmp forum as only a very few JOGL maintainers and users come on StackOverflow. Please ensure that you use at least JOGL 2.3.2. The namespace used in the JAR(s) must match with the namespace used in your source code above. Moreover, you must include the necessary JAR(s) not only when you compile but when you run your project too.
I don't know how VisualStudio Code works, these are the instructions for other major Java IDEs: https://jogamp.org/wiki/index.php?title=Setting_up_a_JogAmp_project_in_your_favorite_IDE

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?

LibGDX, GDX.files.internal() File not found

I have an issue using LibGDX with assets directory. I actually build my project folder this way. I follow this tutorial to learn. (I work on Eclipse)
The code I use is :
package com.mygdx.game;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.Timer.Task;
public class MyGdxGame implements ApplicationListener {
private SpriteBatch batch;
private TextureAtlas textureAtlas;
private Sprite sprite;
private int currentFrame = 1;
private String currentAtlasKey = new String("0001");
#Override
public void create() {
batch = new SpriteBatch();
// THE PROBLEM IS UNDER THIS LINE
textureAtlas = new TextureAtlas(Gdx.files.internal("spritesheet.atlas"));
AtlasRegion region = textureAtlas.findRegion("0001");
sprite = new Sprite(region);
sprite.setPosition(120, 100);
sprite.scale(2.5f);
Timer.schedule(new Task(){
#Override
public void run() {
currentFrame++;
if(currentFrame > 20)
currentFrame = 1;
// ATTENTION! String.format() doesnt work under GWT for god knows why...
currentAtlasKey = String.format("%04d", currentFrame);
sprite.setRegion(textureAtlas.findRegion(currentAtlasKey));
}
}
,0,1/30.0f);
}
#Override
public void dispose() {
batch.dispose();
textureAtlas.dispose();
}
#Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
sprite.draw(batch);
batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
(if the code is hard to read I use exactly the same code that is in the tutorial linked below)
My package explorer looks like this :
imgur link
And it returns me :
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: File not found: spritesheet.atlas (Internal)
at com.badlogic.gdx.files.FileHandle.read(FileHandle.java:136)
at com.badlogic.gdx.graphics.g2d.TextureAtlas$TextureAtlasData.(TextureAtlas.java:103)
at com.badlogic.gdx.graphics.g2d.TextureAtlas.(TextureAtlas.java:231)
at com.badlogic.gdx.graphics.g2d.TextureAtlas.(TextureAtlas.java:226)
at com.badlogic.gdx.graphics.g2d.TextureAtlas.(TextureAtlas.java:216)
at com.mygdx.game.MyGdxGame.create(MyGdxGame.java:23)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:149)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:126)
I tried some trick like Project>Clean, refreshing, close and re-open Eclipse and even recreated a project. Any idea ?
Okay, I found the trick. For those which encounter the same issue (working on Eclipse but it's pretty the same whatever the IDE is) there is one thread on stack overflow already existing which give additional solutions.
For me I had to set-up the "working directory" (for the desktop main for exemple). To do this go on Run>Run configuration>Arguments and at working directory's section there is Default and Other. Tick Other's box and me I had to write ${workspace_loc:my-gdx-game-core/assets} but I think it works like ${workspace_loc:[name-of-your-core-directory]/assets}. Hope it helped.
maybe you haven't linked the asset folder, if so,
try right click on my-gdx-game-desktop, in properties dialog select Java Build Path, click link source button, then navigate to the assets folder.
if you're already set it, try readd with this step, restart eclipse if needed

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.

Create Polygon with Mouse Listener Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.util.*;
import javax.swing.event.*;
import javax.swing.JPanel;
public class Triangle extends JFrame
{
public Triangle()
{
add(new PolygonsPanel());
}
public static void main(String [] args)
{
Triangle t = new Triangle();
t.setSize(500,500);
t.setTitle("Triangle");
t.setVisible(true);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.setLocationRelativeTo(null);
}
}
class PolygonsPanel extends JPanel implements MouseListener
{
private int x1,x2,x3,y1,y2,y3;
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Polygon p = new Polygon();
p.addPoint(x1,y1);
p.addPoint(x2,y2);
p.addPoint(x3,y3);
this.addMouseListener(this);
g.drawPolygon(p);
}
public void mouseExited(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
int i = 0;
if(i==0)
{
int x1= e.getX();
int y1= e.getY();
i++;
}
else if(i==1)
{
int x2= e.getX();
int y2= e.getY();
i++;
}
else if(i==2)
{
int x3= e.getX();
int y3= e.getY();
i++;
}
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
}
I want to make triangle using polygon and set the coordinate by click the mouse.
compiler did't show error, can anybody help ?
..........................................................................................................................................................................................................
In order to debug such applications, you can add println() lines in the right places. While this sounds a bit childish, this method of debugging, called printf-Debugging is even used by the most professional developers in some cases.
I suggest you add a System.err.println("1") resp. System.err.println("2") / System.err.println("3") in each of the if-branches of mouseClicked() to find out why it's not properly recording the points. Hint: You probably want variable i to have a different scope than now`.
Registering the MouseListener should not be done in paintComponent(). If you think a little bit about this, it should be obvious. Ask yourself: How often do I need to register the MouseListener? Only once. How often is paintComponent() called? Many times. So, the addMouseListener() is certainly in the wrong place.
Once you fixed these, you might notice that you have to hide/unhide, resize or (on some OS) move the window in order for your polygons to be redrawn. That's because once you've changed the appearance by recording a new coordinate for your polygon, you don't tell Java that the component needs to be redrawn.
The programming model usage by extension which you apply is still shown on many web pages and in many books as of today, but it's plainly wrong because it often violates the LSP - Liskov Substitution Principle. In your case, extending the JPanel for a PolygonsPanel is almost right, because that is a kind of Painting Canvas which in fact is a new component, so, creating a new class that is a component is perfect for that. Just JPanel might not be the best superclass for it, check out the class hierarchy of Swing class a bit and you will discover a better superclass. However, in Triangle, you do not really want to extend JFrame, you merely use JFrame without adding any new reusable features to it, so subclassing is not right in that case.

JOGL creating window using NEWT - examples?

I have been looking at using JOGL to create some things and have been looking through what documentation I can find.
Brief tutorials they all mention how using the JOGL version of canvas can have performance issues and instead you should use NEWT. However each and every tutorial / FAQ then goes on to use the canvas! Or simply specify a few tiny snippets of methods to create a window using NEWT but which (on my machine at least) I cannot get to correctly run.
Does anyone have a good source of examples of how to correctly implement creating and rendering to a window in JOGL using the NEWT method? I'm not even sure how it functions compared to the Canvas so an explanation of the differences between the two and a typical layout of methods to create / manage / render to a window would be ideal.
Just a little lost and cannot find anything useful. Hope someone's come across something before!
This tutorial helped me a lot, see chapter 3.9 - Yet Another Tutorial on JOGL.
Also documentation is useful. Take a look at the attached example, please.
JOGL2NewtDemo.java
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLProfile;
import com.jogamp.newt.event.WindowAdapter;
import com.jogamp.newt.event.WindowEvent;
import com.jogamp.newt.opengl.GLWindow;
import com.jogamp.opengl.util.FPSAnimator;
/**
* A program that draws with JOGL in a NEWT GLWindow.
*
*/
public class JOGL2NewtDemo {
private static String TITLE = "JOGL 2 with NEWT"; // window's title
private static final int WINDOW_WIDTH = 640; // width of the drawable
private static final int WINDOW_HEIGHT = 480; // height of the drawable
private static final int FPS = 60; // animator's target frames per second
static {
GLProfile.initSingleton(); // The method allows JOGL to prepare some Linux-specific locking optimizations
}
/**
* The entry main() method.
*/
public static void main(String[] args) {
// Get the default OpenGL profile, reflecting the best for your running platform
GLProfile glp = GLProfile.getDefault();
// Specifies a set of OpenGL capabilities, based on your profile.
GLCapabilities caps = new GLCapabilities(glp);
// Create the OpenGL rendering canvas
GLWindow window = GLWindow.create(caps);
// Create a animator that drives canvas' display() at the specified FPS.
final FPSAnimator animator = new FPSAnimator(window, FPS, true);
window.addWindowListener(new WindowAdapter() {
#Override
public void windowDestroyNotify(WindowEvent arg0) {
// Use a dedicate thread to run the stop() to ensure that the
// animator stops before program exits.
new Thread() {
#Override
public void run() {
if (animator.isStarted())
animator.stop(); // stop the animator loop
System.exit(0);
}
}.start();
}
});
window.addGLEventListener(new JOGL2Renderer());
window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
window.setTitle(TITLE);
window.setVisible(true);
animator.start(); // start the animator loop
}
}
JOGL2Renderer.java
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLEventListener;
/**
* Class handles the OpenGL events to render graphics.
*
*/
public class JOGL2Renderer implements GLEventListener {
private double theta = 0.0f; // rotational angle
/**
* Called back by the drawable to render OpenGL graphics
*/
#Override
public void display(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2(); // get the OpenGL graphics context
gl.glClear(GL.GL_COLOR_BUFFER_BIT); // clear background
gl.glLoadIdentity(); // reset the model-view matrix
// Rendering code - draw a triangle
float sine = (float)Math.sin(theta);
float cosine = (float)Math.cos(theta);
gl.glBegin(GL.GL_TRIANGLES);
gl.glColor3f(1, 0, 0);
gl.glVertex2d(-cosine, -cosine);
gl.glColor3f(0, 1, 0);
gl.glVertex2d(0, cosine);
gl.glColor3f(0, 0, 1);
gl.glVertex2d(sine, -sine);
gl.glEnd();
update();
}
/**
* Update the rotation angle after each frame refresh
*/
private void update() {
theta += 0.01;
}
/*... Other methods leave blank ...*/
}
take a look at JOGL's junit tests, they cover large parts of the NEWT API.

Categories