Search ( Min 3 characters )
| Tech | Title | Updated |
![]() | Setting the Default Close Operation on a Java Application | 2012-04-11 11:30:31 |
When running a java Application which terminates, there can still be threads running that do not stop. To ensure that everything is correctly stopped and all java instances are removed, you can add the following to your JFrame. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); This will terminate all threads and exit the application cleanly. You can also use JFrame.DISPOSE_ON_CLOSE But this relies on there being a window, as it is called after the last window is closed. | ||
![]() | Simple Hello World Java Application | 2012-04-11 11:36:01 |
// a new JFrame public class myClass() extends JFrame { // constructor for the class public myClass() { super("Hello World"); // call the super constructor for the JFrame, and set the frame title setBounds(0,0,200,200); // set the window size to 200x200 setVisible(true); // after this the window is visible. Without this call, the program will terminate. } // the entry point , this is the first bit of code that is executed. public static void main( String[] args ) { // create a new myClass object new myClass(); } } | ||
![]() | How to delete a file in Java | 2012-04-12 16:26:03 |
Deleting a file is very simple in a Java application File f1= new File("filename"); boolean itWorked = f1.delete(); itWorked will return true if the file is deleted. If the file does not exist then you will get false. | ||
![]() | Load a Binary file into Java | 2012-04-17 09:55:36 |
A Simple way to load a binary file into a byte[] is as follows: File file=new File("filename"); int size=file.length(); // get File Length byte[] contents=new byte[size]; // allocate buffer FileInputStream in=new FileInutStream(file); // input stream in.read(contents); // Read the data in.close(); // Close the file | ||
![]() | Get the current working directory in Java | 2012-04-17 10:09:26 |
to get the directory where the application was invoked use: String curDir = System.getProperty("user.dir"); | ||
![]() | Loading a Class or Object from a file in Java | 2012-04-17 11:31:30 |
To load a class or object from Java, first the class must be serializable, you can then follow the following to load it. FileInputStream saveFile; try { fileHandle = new FileInputStream(filename); ObjectInputStream data = new ObjectInputStream(fileHandle); MyClass myclass = (MyClass) data.readObject(); return hist; } | ||
![]() | Save a Class or Object to file in Java | 2012-04-17 11:31:47 |
to save a serialized class to disk, follow the example below: try { FileOutputStream fileHandle; fileHandle = new FileOutputStream(<filename>); ObjectOutputStream save = new ObjectOutputStream(fileHandle); save.writeObject(<myClass>); save.close(); } | ||
![]() ![]() | How to setup and load GLSL Shaders in JOGL | 2012-04-13 20:15:19 |
In this example we set up 2 shaders. 1) A Vertex shader 2) A Fragment shader This tutorial will show you how to Load GLSL Shader into your JOGL Program , and how to use them. Contains FULL Class Code. Add the folowing code to the init glContext. // create a new shader object that we can reference later to activate it. shader = new ShaderControl(); shader.fsrc = shader.loadShader("f.txt"); // fragment GLSL Code shader.vsrc = shader.loadShader("v.txt"); // vertex GLSL Code shader.init(gl); You will have to create your own f.txt and v.txt, there is an example at the bottom of this article. Create this following class. // The shader control class. // loads and starts/stops shaders. Public class ShaderControl { private int vertexShaderProgram; private int fragmentShaderProgram; private int shaderprogram; public String[] vsrc; public String[] fsrc; // this will attach the shaders public void init( GL gl ) { try { attachShaders(gl); } catch (Exception e) { e.printStackTrace(); } } // loads the shaders // in this example we assume that the shader is a file located in the applications JAR file. // public String[] loadShader( String name ) { StringBuilder sb = new StringBuilder(); try { InputStream is = getClass().getResourceAsStream(name); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { sb.append(line); sb.append('\n'); } is.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Shader is " + sb.toString()); return new String[] { sb.toString() }; } // This compiles and loads the shader to the video card. // if there is a problem with the source the program will exit at this point. // private void attachShaders( GL gl ) throws Exception { vertexShaderProgram = gl.glCreateShader(GL.GL_VERTEX_SHADER); fragmentShaderProgram = gl.glCreateShader(GL.GL_FRAGMENT_SHADER); gl.glShaderSource(vertexShaderProgram, 1, vsrc, null, 0); gl.glCompileShader(vertexShaderProgram); gl.glShaderSource(fragmentShaderProgram, 1, fsrc, null, 0); gl.glCompileShader(fragmentShaderProgram); shaderprogram = gl.glCreateProgram(); // gl.glAttachShader(shaderprogram, vertexShaderProgram); gl.glAttachShader(shaderprogram, fragmentShaderProgram); gl.glLinkProgram(shaderprogram); gl.glValidateProgram(shaderprogram); IntBuffer intBuffer = IntBuffer.allocate(1); gl.glGetProgramiv(shaderprogram, GL.GL_LINK_STATUS, intBuffer); if (intBuffer.get(0) != 1) { gl.glGetProgramiv(shaderprogram, GL.GL_INFO_LOG_LENGTH, intBuffer); int size = intBuffer.get(0); System.err.println("Program link error: "); if (size > 0) { ByteBuffer byteBuffer = ByteBuffer.allocate(size); gl.glGetProgramInfoLog(shaderprogram, size, intBuffer, byteBuffer); for (byte b : byteBuffer.array()) { System.err.print((char) b); } } else { System.out.println("Unknown"); } System.exit(1); } } // this function is called when you want to activate the shader. // Once activated, it will be applied to anything that you draw from here on // until you call the dontUseShader(GL) function. public int useShader( GL gl ) { gl.glUseProgram(shaderprogram); return shaderprogram; } // when you have finished drawing everything that you want using the shaders, // call this to stop further shader interactions. public void dontUseShader( GL gl ) { gl.glUseProgram(0); } } Place the following functions around the piece of code that you want the shader to affect // Turn on the shader useShader(); ... Drawing code here that uses the shader // turn off the shader dontUseShader(); Now for the GLSL Code itself. These shaders are part of a water effect I use. the fragment shader. < FILE :: f.txt > uniform sampler2D fish_y_offset; uniform float alphavalue; void main() { gl_FragColor = texture2D(fish_y_offset, gl_TexCoord[0].st); gl_FragColor.a=alphavalue; } and the vertex shader < FILE :: v.txt > uniform float waveTime; uniform float waveWidth; uniform float waveHeight; void main(void) { vec4 v = vec4(gl_Vertex); v.y = 11 + sin(waveWidth * v.x + waveTime) * cos(waveWidth * v.z + waveTime) * waveHeight; gl_Position = gl_ModelViewProjectionMatrix * v; gl_TexCoord[0] = gl_MultiTexCoord0; } You will notice that there are some variables that begin with uniform, these can be manipulated from the application. Thus allowing you to configure the shader in real time. To modify the shader variables, add this to your main render loop.. int waveWidthLoc = gl.glGetUniformLocation(sp, "waveWidth"); gl.glUniform1f(waveWidthLoc, waveWidth); In the above code, we ask for the variable "waveWidth", we are then given an id for that variable. int the secondline, we then ask gl to set the variable with our own value waveWidth. | ||
![]() ![]() | JOGL Example - Loading a Texture | 2012-04-14 18:09:13 |
To load a texture is very simple. however, it is important to remember that the size of the texture should be a power of 2 for the width and the height. Although this may load on your system , as some GFX cards can handle it, it wont on others, and you will be left with no texture. ie 8,16,32,64,128,256,512,1024,2048 To load a normal texture Texture text = TextureIO.newTexture(new File(filename), false); to load the texture mip map Texture text = TextureIO.newTexture(new File(filename), true); if using MipMaps dont forget the following code: gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_GENERATE_MIPMAP, GL.GL_TRUE); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_BASE_LEVEL, 0); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_LEVEL, 5); | ||
![]() ![]() | JOGL LIGHTING - A Simple Lighting Example | 2012-04-11 10:25:46 |
The following code will set up a light source at cords ( 2000,3000,2000) ( x,y,z ) This example uses one light. Ambient light is the minimal light that will be seen. If this was 0,0,0 then where the light does not shine would be black. Which is not really good as when you face the direction of the light, all the objects would appear black. Therefore a 0.2f value for the ambient is sufficient to show the objects and some shading. Diffuse is used along with the normal, this should be set to 1, to allow full light intensity when facing the light. Specular light gives off a shiny surface light reflection. float[] lightPos = { 2000,3000,2000,1 }; // light position float[] noAmbient = { 0.2f, 0.2f, 0.2f, 1f }; // low ambient light float[] diffuse = { 1f, 1f, 1f, 1f }; // full diffuse colour gl.glEnable(GL.GL_LIGHTING); gl.glEnable(GL.GL_LIGHT0); gl.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, noAmbient, 0); gl.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, diffuse, 0); gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION,lightPos, 0); This will give you a basic light source for you scene. | ||
![]() ![]() | Setting Ortho Mode in JOGL | 2012-04-14 18:08:43 |
If you want to draw a panel or flat sprites ontop of your 3D scene, then you probably want to draw in Ortho mode.. This mode allows you to draw sprites , and polygons in 2D. To set up Orthos mode, simply use the following code public void setOrtho() { gl.glLoadIdentity(); gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); gl.glOrtho(0, getWidth(), getHeight(), 0, 0, 2000); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glViewport(0, 0, getWidth(), getHeight()); gl.glDisable(GL.GL_CULL_FACE); // Disable Culling gl.glDisable(GL.GL_DEPTH_TEST); // Disable Depth Testing gl.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST); gl.glDisable(GL.GL_LIGHTING); gl.glColor4f(1, 1, 1, 1); } Cull face , and depth testing have been turned off as, we want to see everything we draw, and we dont want to worry about polygon winding. | ||
![]() ![]() | Using MIP Mapped Textures in JOGL | 2012-04-14 18:08:20 |
To enable and use Mip Maps in JOGL, insert the following into your main render loop.. gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_BASE_LEVEL, 0); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_LEVEL, 5); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_GENERATE_MIPMAP, GL.GL_TRUE); gl.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST); gl.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST_MIPMAP_NEAREST); The above sets Mip Mapping on, and with 5 levels. The GL.GL_GENERATE_MIPMAP flag ensures that JOGL will create the mip maps for you. The final part to get Mip Map Textures to work is, when you load the Texture, you must specify true in the "use mipmaps" flag. texture = TextureIO.newTexture(ABufferedImage, true); | ||
![]() ![]() | Creating a Texture from a Buffered Image in JOGL | 2012-04-14 18:08:00 |
To create a texture from a BufferedImage, use the following code. public static Texture createFromMemory( BufferedImage img ) { if (img == null) return null; Texture text = TextureIO.newTexture(img, true); // mipmap on return text; } | ||
![]() ![]() | Adding FOG to your scene in JOGL | 2012-04-14 18:07:39 |
Adding FOG is simple... call this from your main render loop... public void DoFog( GL gl ) { FOG_DISTANCE = 90; float[] fogcol = { 0, 0, 0, 0 }; gl.glEnable(GL.GL_FOG); // Enable FOG gl.glFogi(GL.GL_FOG_MODE, GL.GL_LINEAR); // Set the FOG Type gl.glFogf(GL.GL_FOG_DENSITY, 0f); // Set Density gl.glFogfv(GL.GL_FOG_COLOR, fogcol, 0); // Set Fog Color gl.glFogf(GL.GL_FOG_START, FOG_DISTANCE - 30); // Start FOG gl.glFogf(GL.GL_FOG_END, FOG_DISTANCE); // End of FOG gl.glHint(GL.GL_FOG_HINT, GL.GL_NICEST); // NICE! } | ||
![]() | Javascript reflection, using reflection to list members and variables | 2012-05-16 11:08:45 |
In java script we can use reflection to list all the members and variables of a class, The concept is the same as iterating through an array for ( var methods in object ) { var meth = methods; var value = object[methods]; } A complete example of listing methods and variables using reflection <script> bob = function() { this.a = 1; this.b = 2; this.meth = function(test) { var c=a+b; } } var bb = new bob(); for ( var methods in bb ) { document.write("name: "+methods+"<br>"); document.write("value: "+bb[methods]+"<br><br>"); } </script> the output from the above code name: a value: 1 name: b value: 2 name: meth value: function (test) { var c=a+b; } | ||


