Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

1/22/09

JMenuItem not visible - JMenuItem behind Canvas

I was trying to make a GUI in java where I needed to have a JMenuBar (with some JMenuItems) and a Canvas. The problem I run into was that my JMenuItems were shown behind Canvas. I didn't know why so I searched the web to find the solution. I was not very lucky and for a few hours the only important "think" I found was that Canvas is heavyweight component (awt) and JMenuItem is lightweight (swing) component. And you only mix them if you know exactly what you are doing... So I "solved" that by only using awt components. How? It isn't difficult.
Just remove all J :-P
e.g.
JMenuItem = MenuItem
JMenuBar = MenuBar
setJMenuBar = setMenuBar
e.t.c
This can be done because swing has JMenuItem and awt has MenuItem e.t.c.

The line I had to change more was:

itemExit.setShortcut(
new MenuShortcut(
new KeyEvent
(this, 1 , 1 ,
KeyEvent.CTRL_MASK , KeyEvent.VK_X ,
KeyEvent.CHAR_UNDEFINED ).getKeyCode()
));

which became like this :

itemExit.setAccelerator(
KeyStroke.getKeyStroke (KeyEvent.VK_X, KeyEvent.CTRL_MASK)
);

or it could be:

itemExit.setShortcut(
new MenuShortcut(KeyStroke.getKeyStroke("X").getKeyCode())
);

That's all for now. That worked for me.
If you have any other similar problem please leave it as comment to help others too.
Thank you for visiting.

10/3/08

Java RMI and exceptions

Hello everyone. I know I had a lot of time to post in my blog but I was too busy. Sorry about that.

Now in this post I want to post some exceptions I had during trying to test an RMI application I was programming. I will post it as soon as I finish.

Firstly I wrote a policy file:

grant {
permission java.security.AllPermission;
};

and saved it in the same directory as policy.all
REMEMBER: I just wanted to test my application. This policy file should only be used for testing and not deployed.
I have all java files for this application in the folder C:\myRMIApp
I opened a console window and typed

cd C:\myRMIApp
javac *.java

After that I had all the classes files.
To run myapp I typed

java -Djava.security.policy=policy.all myRMIApp

where myRMIApp is the name of the class with main().
I got the following exception:

java.rmi.ConnectException: Connection refused to host: 127.0.0.1;
nested exception is:
java.net.ConnectException: Connection refused: connect

So I remembered that I had to run rmiregistry (I don't comment this :-P)
And this is what I did. I opened another console and executed rmiregistry. (I could use rmiregistry & in the same console)
Anw rmiregistry was running and I tried again to run my application so I typed the same command as above but I got another exception:

java.rmi.ServerException: RemoteException
java.rmi.UnmarshalException: error unmarshalling argument
nested exception is: java.lang.ClassNotFoundException:
myRMIAppServerInterface

I was looking my code for mistakes but I couldn't find anything wrong.
After a while I thought to try again with a little difference.
I executed rmiregistry form the C:\myRMIApp

For my big surprise this solved the above exception and I was able to test my application.
I looked the web but nobody else said that he solved this exception by running rmiregistry in the same directory so I decided to post it and probably help some people ou there having the same problem.
Thank you for visiting and reading. I'm waiting for your comments.

5/7/08

Simple Java Menu

This is another simple Java example on how to implement a console menu interface with the user.
The steps are really simple.
In a loop:
a) A String which contains the menu options is printed.
b) A number from keyboard is read.
c) Using switch - case statement the correct method is called.
The following Java code is showing the above steps.

import java.util.Scanner;

public class SimpleMenu {
public void start(){
Scanner keyboard = new Scanner(System.in);
int choice;
String menu = "Options\n";
menu+="1. Choice1\n";
menu+="2. Choice2\n";
menu+="3. Choice3\n";
menu+="4. Exit\n";
menu+="Select an option : ";
while(true) {
System.out.print(menu);
choice = keyboard.nextInt();
switch (choice) {
case 1: choice1(); break;
case 2: choice2(); break;
case 3: choice3(); break;
case 4: System.exit(0); break;
default:
System.out.println("Invalid choice.");
break;
}
}
}

private void choice1(){
System.out.println("Menu example choice 1");
}
private void choice2(){
System.out.println("Menu example choice 2");
}
private void choice3(){
System.out.println("Menu example choice 3");
}

public static void main(String[] args) {
new SimpleMenu().start();
}
}

4/8/08

Excecution time in Java

I am going to write my answer to the question " HOW DO I CALCULATE ELAPSED TIME IN JAVA ?"
As far as I now there are two simple ways to calculate the elapsed time - excecution time in JAVA programming language.
Java gives two methods ,nanoTime() and currentTimeMillis() both declared in class java.lang.System .
currentTimeMillis() returns the current time in milliseconds (long) and (as expected) nanoTime() returns the current value of the most precise available system timer in nanoseconds (long).
Below you can see an example of how to calculate the excecution time of a method. The example bellow calculate excecution time of a simple method which it's just a for loop which print numbers from 0 to 1000 but it can be any method you want.

First I used System.currentTimeMillis() to calculate the elapsed time and then System.nanoTime().

import java.lang.String;

public class time_example {

public static void print_num(){
for(int i = 0 ; i<=1000 ; i++) {
System.out.print(i+" ");
}
System.out.println();
}

public static void main(String args[]) {

long start,end;
start = 0; end = 0;

start = System.currentTimeMillis();
print_num();
end = System.currentTimeMillis();
System.out.println("Elapsed time (approximately)
in milliseconds = " +(end-start));

start = System.nanoTime();
print_num();
end = System.nanoTime();
System.out.println("Elapsed time (approximately)
in nanoseconds = " +(end-start));
}
}

And the output is :

0 1 2 3 4 5 ... 995 996 997 998 999 1000
Elapsed time (approximately) in milliseconds = 47
0 1 2 3 4 5 ... 995 996 997 998 999 1000
Elapsed time (approximately) in nanoseconds = 193986945

You may also want to see Elapsed Time in C.
I hope that this post was helpful and don't forget to post your comments. Thank you.

3/5/08

JAVA Chat Server and Client

It's simply a chat room. There are two parts. Client and server.
Client and server have their own "protocol" to communicate but user doesn't care. User uses the GUI to send and receive messages.
Server waits for any client to connect and then starts a new thread to deal with the client.
Client connects to server and can send and receive public or private messages with the other users.



Java chat ( Server and Client) can be downloaded from http://andpapad.googlepages.com or click here.
If you don't know how to run it just unrar - compile - run server - run as much clients as you want.
If you want to ask something just post it here and i will try to answer it.

3/3/08

Java Thread Example

You can see bellow two different programs which actually print all the numbers from 1-5000.

Count program one

class Count1 {
public static void main(String[] args) {
for (int i=0;i<=5000;i++) {
System.out.println(" i= "+i);
}
}
}

Count program two

class Count2 extends Thread {
int from,to;
public Count2(int from,int to) {
this.from=from;
this.to=to;
}

public void run() {
for(int i=from;i<=to;i++) {
System.out.println(" i = "+i);
}
}

public static void main(String[] args) {
for(int i=0;i<10;i++) {
Count2 t =new Count2(i*500,(i+1)*500);
t.start();
}
}
}


Now i must a say a few words.
Count program one it is just a for loop from 0 to 5000 and each time prints the value of the index i. Prints all the numbers in row.

Count program two also counts from 0 to 5000 but how? It creates ten threads and each one prints 500 numbers. The i thread prints from i*500 to (i+1)*500. Total from 0 to 5000. This time you are not sure about the result...

Now run these two programs and see the results. You will be surprised from the second program which almost every time gives different result.
Do you know why?

Another Java Keyboard example

This example is similar to the previous one but uses the class StringTokenizer.
Reads two numbers and prints the sum and then reads and prints anything you write.

import java.util.StringTokenizer;
import java.util.Scanner;

class TokenizerExample {

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Give 2 numbers followed by letters ");

int x = new Integer(keyboard.next());
int y = new Integer(keyboard.next());
System.out.println("x+y = " +(x+y));

StringTokenizer test;
test = new StringTokenizer(keyboard.nextLine());

while (test.hasMoreTokens()) {
System.out.println(test.nextToken());
}

}
}

Java System Properties

This java code prints some information about your system like Operating system, architecture e.t.c.

class SystemProperties{
public static void main(String[] args) {
System.out.print("User name : ");
System.out.println(System.getProperty("user.name"));
System.out.print("Operating System : ");
System.out.println(System.getProperty("os.name"));
System.out.print("OS version : ");
System.out.println(System.getProperty("os.version"));
System.out.print("Os Architecture : ");
System.out.println(System.getProperty("os.arch"));
System.out.print("Java Classpath : ");
System.out.println(System.getProperty("java.class.path"));
System.out.print("Java version : ");
System.out.println(System.getProperty("java.version"));
System.out.print("Java home : ");
System.out.println(System.getProperty("java.home"));
}
}

Java Keyboard example

This is a little Java program which asks user to input two numbers and prints the sum of the numbers. After that user enters two strings and the program checks if are the same. I suppose you know how to use this code but in case you don't just copy it to a file named demokeyboard.java , compile it (javac demokeyboard.java) and run it (java demokeyboard).

import java.util.Scanner;

class demokeyboard {
public static void main(String[] arg) {
//read from System.in = normally keyboard
Scanner keyboard = new Scanner(System.in);

System.out.print("Give two integers : ");
int x,y;
//read the two ints
x=keyboard.nextInt();
y=keyboard.nextInt();
System.out.println("You wrote "+x +" and "+y);
System.out.println("x plus y = "+(x+y));

System.out.print("\nGive a string : ");
//read two strings
String name=keyboard.nextLine();
name =keyboard.nextLine();
System.out.print("Give another string: ");
String name2 = keyboard.nextLine();
//compare the strings
if (name.equals(name2)) System.out.println("Same");
else System.out.println("Not Same");
}
}

2/29/08

Java Maze Solver

Java Maze Solver

Maze solver started


Maze solver running Best FS

Maze solver finished A*

DESCRIPTION

Maze solver is a simple application you can use to solve mazes.
You can load a maze file with a specific form and then select an algorithm and find the exit.
The maze file is a text file you can write using any text editor you like(e.g. notepad++). Maze solver ignores all the lines in the file since it reads a line with only the word "start". At the next lines you can have any characters. You can define the start with the letter 'S'. End with the letter 'E' , walls with the letter 'X' and paths with space ' '. Any other character will be considered as a wall. If you write more than one 'S' and 'E' only the first read will count. The rest will be walls. At the end you must write the word "end". Be careful. All the lines must be the same length. If you want spaces at the end you must write them.

Implemented in Java 1.6 but uses some Deprecated functions (suspend(),resume()). Although there is no problem at all because there is no use of locks.
The package contains seven classes.
The idea is that a "man" (thread) is trying to find the exit. The user selects from five algorithms which one to use.
Available option are :
DFS non recursive
DFS recursive
BFS
BestFS
A*

HOW TO START

There are two options.
1) Double click MazeSolver.bat (only windows)
2) Using command line
Linux users:
a) Open console and follow steps b and c for windows

Windows users:
a) Start - Run - write " cmd " - enter.
b) Using cd command go to the directory where compiled code is.
c) Run
java Gui
where
filename : A file containing a maze at the format descriped above
algorithm number : Which Algorithm to use. Specifically:
1 : Non Recursive DFS
2 : Recirsive DFS
3 : BFS
4 : BestFS
5 : A*

If you don't select an algorithm then you just load the maze file.
Else if you entered a valid value the algorithm will start immediately.
Of course you must have java installed at your computer.

MENU OPTIONS

1) File - Open : Load a maze file
2) File - Exit : Exit application
3) Help - Help : A little help
4) Help - About : About the application


BUTTONS

Start/Pause : Start / Pause algorithm
Step : Another step is shown
Open File : Load a maze file
Select Algorithm : Select which algorithm you want to run.
Slider : Using slider you can adjuct the delay between steps. Option available are from 50 miliseconds to 500 miliseconds.

COULOR CODE

White : Path
Black : Wall
Red : Solution path
Green : Search frontier
Blue : Closed set
Pink : Start
Orange: Exit


LOADING A MAZE FILE

Use the file - open file menu or the Open File button or just press CTRL + O
From the new window select the file you want and click open.
Sometime the file must be at the same directory with the code.


STARTING

After successful load select the algorithm you want form Select Algorithm list.
Step button will show a step. Start/Pause button starts and stops when the button is pressed again.
If you paused it you can run it again til the end by pressing Start/Pause. If you want to see step press Step.

EXITING

Select File - Exit or press CTRL + X or press the X button at the right up corner.


ADDITIONAL INFORMATION

While program runs you see some information at two linees up to the maze.
First line show the time since you started the algorithm til it finishes. If it finished successfuly you see next to it the real time in nanoseconds( 1 bilion nanoseconds = 1 second).
Second line shows:

Search frontier: X Y Closed set : Z Path: W
X : Current size of search frontier
Y : Max size of search frontier til now
Z : Current size of closed set
W : Path size in steps.
Last one is showed when solution is found.

If an algorithm is running you cannot load another maze file or start other algorithm. You have to wait until it finishes.

Maze solver can be downloaded from http://andpapad.googlepages.com or click here.
If you want the source code you can send me an e-mail at my email( andpapad@gmail.com ).