Java Help

These are some of my notes about programming in java that you may find useful.

TIP #1. If eclipse crashes in linux when starting a new project use sudo gedit /usr/share/themes/oxygen-gtk/gtk-2.0/gtkrc from the terminal to edit the file so that the line which reads …

GtkComboBox::appears-as-list = 1

equals zero instead.

____

Accepting passed arguments into the main method of the primary class at time of execution…
public class DigitalClock {

    
    public static void main(String[] args) {
        
         try{
             if (args[0].contentEquals(“h”)){
                 System.out.println(“This is the help file for Digital Clock…”);
                 System.out.println(“There is no help file for Digital Clock…”);
                 System.out.println(“You are screwed!”);
                
             }
                
         }
        catch (Exception e)
        {
            System.out.println(“You have begun this program without arguments. Using defaults…”);
        }
            
    }

}

Classes and Methods… All programs must have one class and one method within the class. A class is just a complicated type of variable. A method is a function that can be called when a class or an object made from a class is called. The structure is…

class public ClassName(){}

“Class” is a keyword meaning the data type of the variable being declared is a class. The word “public” means the class can be used by other classes. The classname can be anything with some limitations as long as the file in which the class resides has the same name but with a .java file extension. Classnames and the filenames of the files in which they reside are case sensitive. The area between the parenthesis is where you pass arguments into the class if necessary. Between the braces the body of the class is written.

All java programs must have at least one class and one method within it, but other classes can be blank. The method which is necessary is called “main” and the syntax for declaring it is particular. The structure will appear like this…

class public MyProgram()

{

public static void main(String[] args){}

}

The first line has been explained and the braces which belong to the class called “MyProgram” now contain the main method. That method has the word “public” which defines it’s scope or accessibility throughout the class. The word “static” means the method can be called without first creating an object from the class in which is resides. This is necessary for the main method since no objects exist before the main method is used. The word “void” means the method will not return a value. The word “main” is the name of the method. The main method must always be called “main” (case sensitive). The parenthesis contains the arguments that can be passed to method. In this case it must allows be “String[] args” which means a string (“String” must be capitalized) array (the brackets mean an array) and “args” is the name of the argument. It is short for “arguments.” The body of the method will go in between the braces. Remember this syntax is exact and must be exactly as it appears, but the java compiler ignores whitespace so after you write the body of the method the different placement of the braces doesn’t matter.

We can add extra methods and classes to our program as needed. Additional methods can be contained in our primary class, but extra classes must be in their own .java files. For example if I want to create a class called “DoSomething” I need to create a file called DoSomething.java and write my class within that.

To review the syntax for making a basic class is…

public class DoSomething{}

public means other classes have access to it, class is a keyword meaning we are creating a variable of the class type and DoSomething is the name of our class. All code for the class goes between the braces.

If we want to use create an object/instance from this class we just use the code..

new DoSomething();

However this object has no name. To create an object that has a name use this code..

DoSomething myobject = new DoSomething();

If the class contains a variable declaration such as…

int a;

we can now set the variable from our main class like this..

myobject.a = 1;

because the object has all the same variables as our class DoSomething does.

If we want our class to contain variables it should look like this…

public class MyClass
{
int a;
}

Then we can call that method like…

new SayHello().SayHi();

or if we want to make an object first like this…

SayHello myobj = new SayHello();
myobj.SayHi();

If we want our class to contain methods/functions it should look like this…

public class SayHello
{
public void SayHi()  {

System.out.println(“Hi”);

}

}

If we want to create a method that is not within it’s own class file, but is still within the primary class file from which the program executes we just write the primary class file like this…

public class MyClass {

public static void main(String[] args) {
DoSomething();
}

private static void DoSomething() {
//functional code goes here…
}

}

The word “static” is necessary because we are not creating an object to call the method as we would if the method was residing in a separate class, but rather we are using the method immediately as we can since it resides within our primary class. Static methods can be called without creating objects.

If we want our method to return a value the syntax is like this.

public class MyClass {

public static void main(String[] args) {
int a = GetMeAnInteger();
}

private static int GetMeAnInteger() {
return 1;
}

}

Here we are calling the method “GetMeAnInteger” to assign a value to the declared variable “a” which is declared as being of the “int” or “integer” type of variable. The return value is “1” so that will go into “a” giving it “a” a value. In order for this to work however the word “void” in the method declaration had to be replaced with the word “int” meaning that the method will return an integer after it is called. Any formula can be used to arrive at the value that will be returned. In this case we purposely returned a specific value.

Variable declared outside of a method are called “class variables” as they are accessible by everything within the class. If we want to be able to use them without creating an object they must be declared with the “static” keyword like this…

public class MyClass {

static int MyClassVariableIntegerWhichIsStatic;

//..methods would go here, the variable is outside of the methods.

}

But if they are to be associated with objects a simple…

int MyClassVariableInteger;

is fine.

 

 

File Input Output… code samples below

import java.io.*;

public class FileCreate {

//two lines below are class variables (global variables) for simplicity

static BufferedReader BuffRead;
static String OneLine;

public static void main(String[] args)  {

File f = CreateVirtualFile();

try
{
BuffRead = new BufferedReader(new FileReader(f));
}
catch (FileNotFoundException e)
{
System.out.println(“File not found”);
}

try
{
OneLine = BuffRead.readLine();
//System.out.println(OneLine);//will print first line only
while (OneLine != null)
{
System.out.println(OneLine);
OneLine = BuffRead.readLine();//this get the next line for the variable writing over the last
}
}
catch (Exception e)
{
System.out.println(“General Exception”);
}

//BuffRead.close();//at some point in the program you should close the

//bufferreader to save memory

}
public static File CreateVirtualFile(){
File MyFile = new File(“myfile.txt”);
return MyFile;
}

/*public static void WriteFileOnDisk(File f){
try {
if (f.createNewFile()) System.out.println(“File created on disk successfully.”);
else {
System.out.println(“The file could not be created. It may already exist.”);
//System.out.println(“Would you like to delete the old file and try again?”);

}

} catch (IOException e) {
System.out.println(“IO Exception.”);
e.printStackTrace();
}

}
*/

}

 

 

GUI Interfaces… In the book “Java, All-in-One Desk Reference For Dummies 2nd edition” there is some code on page 532 that reads..

import javax.swing.*;
public class HelloFrame extends JFrame{

    public static void main(String[] args) {
        // TODO Auto-generated method stub
new HelloFrame();
    }
public HelloFrame()
{
    this.setSize(200,100);
    (Embs note: etc… here the author goes through misc. parameters to define the different aspects of the frame.)
}
}

Unless you use “extends JFrame” and the class within your program called to define the parameters of the frame is named the same thing as your overall class the program will not compile because of the error “… can not be resolved to a type.”

There are two solutions where you don’t need to extend and can use a different class name to define parameters of the frame.

The first solution is to make the object immediately through a constructor using the JFrame variable type rather than trying to create a custom class to define a new variable type and then setting the parameters for the frame immediately. So this works..

import javax.swing.*;
public class HelloGUI {
  public static void main(String[] args) {
    JFrame myframe = new JFrame(“HelloWorldSwing”);
    myframe.setVisible(true);

(etc… setting all the parameters to make up the frame such as such and so on)
}
}

We can set all the parameters and access the methods of the myframe object in code like…

myframe.setSize(200,100)

etc.. So that the custom code would appear would appear like..

import javax.swing.*;
public class HelloFrame {
  public static void main(String[] args) {
    JFrame myframe = new JFrame(“HelloWorldSwing”);
    myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    myframe.setTitle(“Hello World”);
    myframe.setSize(200,100);
    myframe.setVisible(true);
}
}

The second solution is much more like what the author wanted to do (which is having a method set the options for the frame) is to create the frame object from the JFrame type just as in my example, then pass that object into a method to be manipulated returning it back again like this…

import javax.swing.*;
public class HelloFrame {
  public static void main(String[] args) {
    JFrame myframe = new JFrame(“HelloWorldSwing”);
    myframe = SetMyFrameUp(myframe);
    
  }
  public static JFrame SetMyFrameUp(JFrame myframe)
  {
  myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  myframe.setTitle(“Hello World”);
  myframe.setSize(200,100);
  myframe.setVisible(true);
  return myframe;
  }
}

Now this might need a little explanation. We made an object called myframe from the JFrame type. Then we modified it’s variables by using an “equals” passed to a method called SetMyFrameUp which is acting as a function. The “(myframe)” means “pass the object myframe” into the method so it can be used.

Now the method has to be able to take that object so the method declaration has to have “(Jframe myframe)”. Jframe is the type of object we are sending over and myframe is the object’s name. It also must be able to send the object back so we need use “JFrame” before the classname (which is SetMyFrameUp in this case) so the method can send back an object of the JFrame type. In the body of the method we set as many of the variables of the object “myframe” as we want and then we have to finish the method by returning myframe so that the changes are permanent.

Now that we sort of understand how to write this without being limited to using “extends” and using the same class names throughout to get it to compile the rest of the chapter becomes more practical for general use.

The basic idea is that by using my technique we can at any time create an object to make a frame without extending the Jframe class into our own.

To continue expanding your knowledge look at the code below. First by creating an object of the JFrame type, then setting the variables to make the frame object a certain size and visible, adding a JPanel object to the code, attaching the JPanel object to the JFrame object we made for ourselves and so on we can make the JFrame look a certain way and contain certain features…

import javax.swing.*;
public class HelloFrame {
  public static void main(String[] args) {
    JFrame myframe = new JFrame(“Mines of Moria GUI – J.Embs”);
    myframe = SetMyFrameUp(myframe);
   JPanel mypanel = new JPanel();
   myframe.add(mypanel);
   JLabel label1 = new JLabel(“Hello World??? Really? Is that all you got?”);
   myframe.add(label1);
  }
  public static JFrame SetMyFrameUp(JFrame myframe)
  {
  myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  myframe.setTitle(“Title : Hello World “);
  myframe.setSize(500,100);
  myframe.setVisible(true);
  return myframe;
  }
}

Or instead of making and adding a JLabel to the panel we can add a button instead (a button and label won’t appear on the same panel using this particular code so choose on or the other) like this..

JButton mybutton1 = new JButton(“Touch Me.”);
   mypanel.add(mybutton1);

I hope these tips help you to avoid using extensions when making JFrames where they may not be desirable.

On page 824 the code will not compile unless you change the line which reads

public ShowPic()

to

public static void ShowPic()

I don’t know if it’s just eclipse that is particular about that, but once I changed it the code compiled fine.

Leave a Reply