emclondon 38 Junior Poster in Training

how do I schedule the timer? I've tried once but I couldn't do it right :(

public java.util.Timer _myTimer;
_myTimer.schedule(new java.util.TimerTask (){public void run(){resetState();}},5000);

--


also, I was wondering if it was possible to an instance of a class?


for example:

class x
{

     public x v;
     public z w;

     public x()
     {
        // blah
        w.show();
     }

     public x getInstance()
     {
           return v; 
     }
}

class y
{
     public x a;
     public y()
     {
        a = new x();
     }
     public static void main(String[] args)
     {
         new y();
     }
}

class z
{
     public x b;
     public z()
     {
        b = new x();
     }
     public void show()
     {
          System.out.println(b.getInstance());
     }
}

can this be done?

in simple words: I have 3 classes, 1st class has object of 2nd class. I need to access variables of 2nd class in 3rd class.. how is it possible?

emclondon 38 Junior Poster in Training

Hi James, im doing this project as a part of my assignment. and it requires my application to be three-tiered and must be using java.util.Timer

how do I make this application three-tiered? I have tried separating the actionlistener into a new class and have failed miserably.. any pointers which way I should follow now?

emclondon 38 Junior Poster in Training

ah I see, Thanks for the help!
also I need to use the timer provided in java.util instead of the javax.swing one...

I was wondering if this is the right way to do it?

public java.util.Timer _myTimer;
_myTimer.schedule(new java.util.TimerTask (){public void run(){resetState();}},5000);

that code doesn't work.. :/

this is what Im trying to do. I'm rewriting the following code by using a java.util Timer!

_myTimer = new Timer(5000,new ActionListener()
		{ 
			public void actionPerformed(ActionEvent e)
			{
				resetState();
			}
		}
		); 

.......
......
 public void resetState()
{
        _myTimer.stop();

}

what mistake am I doing here?

emclondon 38 Junior Poster in Training

ok, one LAST question (I Hope)

I am coding this program in JCreator, and when I compile and run the program using JCreator, the program runs fine. but when I manually go to the directory and try running the application, I get a ClassNotFoundException.

c:\jcreator>java myLoader
Exception in thread "main" java.lang.NoClassDefFoundError: myLoader
Caused by: java.lang.ClassNotFoundException: myLoader
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: myLoader.  Program will exit.

I can see that the classes have been neatly stacked in a folder called uniKEY.

and when I navigate to the classes folder (uniKEY folder), and try running the program with same command I get this error

c:\jcreator>java myLoader
Exception in thread "main" java.lang.NoClassDefFoundError: myLoader (wrong name:
 uniKEY/myLoader)
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClassCond(Unknown Source)
        at java.lang.ClassLoader.defineClass(Unknown Source)
        at java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.access$000(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: myLoader.  Program will exit.

how do I run this manually from command line? I want to make a batch file for the application to start up.

thanks.

emclondon 38 Junior Poster in Training

ah I get it, I have eliminated the loop now.
and yes, that sequence of loading is my idea too. i.e., start myLoader then myUI then myFunctions.

but the action listener class is in myFunctions class which needs to have access to variables of myUI class.

how do I create a reference of myUI class in myFunctions so that I can use the buttons (which belong to myUI)??
how do I set a reference of myUI class in myFunctions class.

emclondon 38 Junior Poster in Training

this is what I get when Iry to compile the app.

Exception in thread "main" java.lang.StackOverflowError
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:244)
    at javax.swing.UIDefaults.getUI(UIDefaults.java:751)
    at javax.swing.UIManager.getUI(UIManager.java:989)
    at javax.swing.JPanel.updateUI(JPanel.java:109)
    at javax.swing.JPanel.<init>(JPanel.java:69)
    at javax.swing.JPanel.<init>(JPanel.java:92)
    at javax.swing.JPanel.<init>(JPanel.java:100)
    at uniKEY.myUI.<init>(myUI.java:37)
    at uniKEY.myFunctions.<init>(myFunctions.java:30)

and the last 2 lines

at uniKEY.myUI.<init>(myUI.java:37)
    at uniKEY.myFunctions.<init>(myFunctions.java:30)

repeat continuously for 10-15 times or more.

myUI.java

public myUI()
    {                //  <--------------------- Line # 102

myFunctions.java

class myFunctions implements ActionListener
{
	myUI myUIObj = new myUI();    //  <--------------------- Line # 30
class myUI extends JPanel
{
	myFunctions _myFObj = new myFunctions();    //  <--------------------- Line # 37

these are the errors which I am having.. how do I eliminate the errors?

emclondon 38 Junior Poster in Training

ah my bad, didn't read your question properly. I didnt have the myFunctions object initialized!

I have added it in myUI class and the NPE vanished! thanks!

myUI.java

class myUI extends JFrame
{
     myFunctions myFObj = new myFunctions();
     public myUI
     {
           // blah blah...
     }
}

myFunctions.java

class myFunctions implements ActionListener
{
     myUI myUIObj;   -------  ???????

     public myUI
     {
           // blah blah...
          loadDB();
     }

     public loadDB()
     {
           // blah blah   ----- WORKS FINE!
     }
     public void actionPerformed(ActionEvent e)
     {
    	if(e.getSource() == myUIObj._button[0])
    	{
           // blah blah
        }
     }	
}

Im facing a new problem now.. when my Frame's up and running and when I click a button, it gives me an nullpointer error again! at

(e.getSource() == myUIObj._button[0])

and then When I try to Initialize the myUIObj it gives me a stackoverflow error.


how do I fix this now?

emclondon 38 Junior Poster in Training

my 'myUI' class is the main frame of my application. It needs to get input from user and process the input and give out result in form of images.

I have separated the UI and logic in two separate classes called myUI class (which contains UI) and myFunctions class (which contain logic).

the 1st thing my application does when the myUI loads up is read a text file and store it in the memory somewhere so the password can be used to verify user input. so the logic for fetching text file, reading it and storing passwords is written in myFunctions class.

and when I compile and run the program, the myLoader class starts up and creates a frame and loads up the UI (by calling myUI class) but in order to load up the text file and read password I need to call up the loadDB method present in myFunctions class right?

So THATS why I initialized an object of myFunctions class so as to call up the function in my myUI class.


------

have you understood now?

emclondon 38 Junior Poster in Training

Where are you initializing the `_myFObj` object? If the root exception cause is `_myFObj.loadDB();` throwing an exception, then it's pretty clear that `_myFObj` is NULL.

exactly, I don't know why is it null. all I need is to call loadDB() present in myFunctions class from myUI class. The only way I can think of doing is to create an object of myFunctions class inside myUI class and call the loadDB() method.

but I dont understand why the object is null.


Another alternative I could think of is by placing the loadDB() in the constructor of myFunctions() and by calling the constructor from myUI()

class myFunctions()
{
     public myFunctions()
     {
          loadDB();
          // other code
     }
}
class UI
{
     public myUI()
     {
          // other code
          new myFunctions();
     }
}

but I dont think this is of any good to me.
------

also when I removed the loadDB() and _myFOBj from myUI, the application runs fine!
but all my action listening is written in myFunctions how can I again assign the listening and not create any errors?


how do i fix this issue?

emclondon 38 Junior Poster in Training

you're welcome.

If I were you, I'd read the 1st and 2nd Wiki articles and find more related articles as such. the 3rd article is bit advanced and is of a bit complex.

emclondon 38 Junior Poster in Training

ok, I have made some minor modifications to the program and brought back the state's part to myUI, but the problem still exists! and the problem is SILLY!

I cant call the constructor of the myLoader class! it gives me a null pointer exception

public class myLoader extends JFrame
{
     private myUI _myUIObj;

     public myLoader()
     {
          _myUIObj = new myUI();   <---------------------------- HERE
     }

     public static void main(String[] args)
     {
          new myLoader();   <---------------------------- HERE
     }
}

the null pointer occours at new myLoader(); I dont know how to break down this statement to debug the problem. so I cant fix it myself.

Simiarly, I cant instantiate an object of myUI class from myLoader class and cant call the object of myUI class / cannot instantiate an object of myFunctions class and cannot use the object. it gives me an null pointer when I do the both.

how do I fix this?

class myUI extends JPanel
{
    myFunctions _myFObj;
	 
    public myUI()
    {
         // OTHER CODE HERE...
         _myFObj.loadDB();      <---------------------------- HERE
    }
}
emclondon 38 Junior Poster in Training

Hello mate,

thanks for the reply. The same code was used earlier and it didn't give my any errors.
It only started acting strange since I partitioned the code form UI. The three areas where the NPE occours are in my loader, and in my main frame of my application.

my Loader has cannot load up an instance of my main frame nor its own constructor. I dont know why. How do I debug this issue? Im expecting a frame to be generated from my loader and a panel to be generated from my UI class. neither of them work :/

similarly, in the constructor of my UI class I try setting up the state of the application by calling up methods in different class and setting up state variables and instantiating the default state class. but that one doesnt work too.

===================================

I dont know how to design this application properly now.


I have a Loader Class which generates a frame and Calls up UI Class to build UI which calls up the Functions Class and gets its functionality.


My simple query is where do I put my States? I know they dont go in loader so Its either in UI or functions class. In my old program, I had my states all set up and working fine in a single file (UI) now If only I could know where to put all the state's stuff, it …

emclondon 38 Junior Poster in Training

you can start off by reading this:
http://en.wikipedia.org/wiki/Software_development
http://en.wikipedia.org/wiki/Software_development_process
http://en.wikipedia.org/wiki/Software_development_methodology

If you are into reading the book, then the best authors I can suggest are
Pressman R. S., Somerville, I. and Cockburn, A.

emclondon 38 Junior Poster in Training

no one? :(?

emclondon 38 Junior Poster in Training

also I am trying to rip apart the application to separate the coding and the UI.

I have tried separating the UI part from functionality part. I have created a new class called myFunctions and dumped all the variables and functions related to functionality of the application.

now I'm stuck with a stupid Null Pointer Errors again! which I can't fix!.

so I request you to have a look here and please do let me know how to fix this.

File 1: State.java

/**
 * @(#)State.java
 *
 *
 * @author
 * @version 1.00, 2010/7/18
 */
 
 package uniKEY;

/**
 * This interface acts as an interface for the mechanism of state pattern used.
 */
 
interface State
{
	/**
	 * This method sets the state using the parameters passed.
	 *
	 * @param _myUIObj An instance of main application
	 * @param _myState state of the application
	 *
	 */
	void setStates(myFunctions _myFObj, States _myState);
}

File 2: closedState.java

/**
 * @(#)closedState.java
 *
 *
 * @author
 * @version 1.00, 2010/7/18
 */
 
package uniKEY;

/**
 * This class contains an implemented method which is used to change the state of the application depending upon the type of object and state passed.
 */
 
class closedState implements State
{
	
	/**
	 * This holds an Instance of myImage class
	 *
	 * see uniKEY.myImage
	 */
	 
	myImage _myIObj;

	/**
	 * This method sets the state based on the parameters passed to it. 
	 *
	 * @param _myUIObj An instance of main application
	 * @param _myState current …
emclondon 38 Junior Poster in Training

Hi, thanks for the write up, from what I can gather from your write up is this:

- I have a method to change the state in my application
- I have an interface with 3 implemented classes
- When I validate, based on the result, I pick a state (yes/no) and call my method to change the application state...
- but, my method would in-turn call one of the implemented classes based on the state I picked (result) and then would change the state.
- so, finally the state gets changed by an external method (implemented class).

now I think I get it. Thanks for the help :)

emclondon 38 Junior Poster in Training

It seems that you are still struggling with the concept behind using the state pattern otherwise you wouldn't have asked this question. Read the wiki article again along with this article.

I still don't get it :(

let me build an image of state patterm in my mind which would clear a few things up.

I have an Interface and 3 Classes inheriting from the Interface.
My main method only talks with the Interface which in turn directs me to one of the classes depending on the objects of classes I created (?).

is my assumption right?

emclondon 38 Junior Poster in Training

Hello, thanks for your reply, but that code is a bit confusing to me.. so I made a few changes to it..

I have taken 4 different files: openState, lockedState, defaultState and State

package uniKEY;

interface State
{
	public void setState(myUI obj, int i); 
}

State.java

package uniKEY;

class defaultState implements State
{
	public void setState(myUI obj, int i)
	{
		if(i == 1)
		{
			obj.setStatus("OPEN");
			obj.setState(new openState());
		}	
		else if(i == 2)
		{
			obj.setStatus("LOCKED");
			obj.setState(new lockedState());
		}		
	}
}

defaultState.java

package uniKEY;

class openState implements State
{
	public void setState(myUI obj, int i)
	{
		if(i == 0)
		{
			obj.setStatus("DEFAULT");
			obj.setState(new defaultState());
		}	
	}
}

openState.java

package uniKEY;

class lockedState implements State
{
	public void setState(myUI obj, int i)
	{
		if(i == 0)
		{
			obj.setStatus("DEFAULT");
			//obj.setState(new defaultState());
		}	
	}
}

lockedState.java

and my application has been modified to have

...
	...
	private State state;
	private String status;
	...
	...
	setState(new defaultState());
	...
 	public void setStatus(String ss)
 	{
 		this.status = ss;	
 	}
	...

myUI.java

I was wondering if I could take up 3 static ints in my UI and use them as enums?

...
    private static final int DEFAULT = 0;
    private static final int OPEN = 1;
    private static final int LOCKED = 2;
    ...

myUI.java

following the above change, in my methods, I have used the setState as setState(myUI obj, int i) where obj is an object of myUI and the integer i is the static int

they would …

emclondon 38 Junior Poster in Training

yes it is, according to my theory..

I just need to separate the logic of my program from the UI. and when I do that, I want a component in UI to behave differently based on my input.

by default the behaviour of the component (say panel) would be to display a black image on the frame at all times. and when the input from user is collected and compared with the one in the database, the component changes its default behaviour. e, it displays another image instead of black one. this can also be called as a change in state. similarly based on the output data generated by my custom functions, the behaviour of component changes to display different images...

the basic aim here is to achieve this is by using state pattern.

I have an interface with a function, and 3 classes implementing interface...each class doing its own work. now I have to call up interface by making an object of it. then I utilize the function in my frame to call up different class via interface. thats what im assuming.. :/

emclondon 38 Junior Poster in Training

anyone?

emclondon 38 Junior Poster in Training

from my understanding state pattern is a collective way of organising code of an application whose' object changes state frequently.

following is a generic image of state pattern as hosted on wikipedia:


so according to that image, I have a interface called state and classes called as openState, lockedState, unlockedState.
the main and sole purpose of these states are to draw images on my window when called.

I dont know what to do, I have my draw function. I dont understand how to let the app know which draw to draw and when does it draw. I dont understand the contept of context class, dont even know what is it, but an assuming that its n current image or something...

more info on state parrern with examples can be found here.. http://en.wikipedia.org/wiki/State_pattern

any help now?

emclondon 38 Junior Poster in Training

yes that worked fine. thank you very much :)

Norm can you help me out with state pattern?

emclondon 38 Junior Poster in Training

strangely, that code gives me an error :/
the compiler says that it cant find the class TimeListener.

_myTimer = new Timer(5000,new TimerListener()
		{ 
			public void actionPerformed(ActionEvent e)
			{
				resetState();
			}
		}
		);

strange :/

emclondon 38 Junior Poster in Training

ok this is what I have done,

I used a timer in my myUI.java file

private Timer _myTimer;

inside myUI class

and init'd the variable with an instance of an action listener class

_myTimer = new Timer(5000,new TimerListener());

inside myUI constructor

and added a class (nested) which had the functionality of enabling the buttons back to normal state and changing the image back to default one.

private class TimerListener implements ActionListener
	{ 
		public void actionPerformed(ActionEvent e)
		{
			resetState();
		}
		public void resetState()
		{
			_click=0;
			for(int i=0;i<12;i++)
			{
				_button[i].setEnabled(true);
			}
			_myLight.flipImage("wait");
			_myTimer.stop();
		}
	}

inside myUI class

the application is working fine, like a charm, but I wanted to know, whether if this is the right way of doing this? or is there any other way to do this? if there is please do let me know, if there isn't then I am a step closer to completion now.

The last part of my question is the state pattern. I am to implement State pattern in this applicaion. From my gatherings and readings I have figured it out that this pattern is used to reduce coding at places where the program exhibts various states.

my application exhibts 3 states.

  1. Waiting
  2. Go
  3. Stop

the waiting state displays black image on the panel, whilst the go and stop displays green and red respectively.

I am told that a state pattern needs an interface; I cant figure out what my interface …

emclondon 38 Junior Poster in Training

lovely, now is there any way to use a timer to call resetState() after 5 seconds?

I have tried looking at the Timer class and many other threads on the forum. and I got a few different methods.. but they need a new action listener and stuff which would make the code complex (i think). Even If I wanted to do that how could I do that?

Timer _t = new Timer(5000, new ActionListener() { /* for loop to enable buttons again ? */});

If I place this code in stead of resetState() in check() in myUI.java

will that work? If it doesnt, what other alternative way could you suggest me?

emclondon 38 Junior Poster in Training

Hello guys, I am stuck again with a new problem.

I need help with 3 things:

1. Timer
2. State Pattern
3. Disabling the button on JFrame

lets go with the easiest one in the list, the Disabling of button one.

I have an app with buttons, and I need to disable all the buttons on it for certain period of time. Lets forget the time part.. I just want to disable the buttons on the frame.

BEFORE YOU GO ON SUGGESTING ME THE FUNCTION, I ALREADY HAVE TRIED "button.setEnabled(false);" AND IT DOESNT WORK! I dont know why :/

here's my source code:

myloader.java

/**
 * @(#)loader.java
 *
 *
 * @author 
 * @version 1.00 2010/6/24
 */
package uniKEY;

import java.*;
import java.awt.*;
import javax.swing.*;
import java.lang.*;

public class myLoader extends JFrame
{
	private myUI _uiobj;
	
	public myLoader()
	{
		_uiobj = new myUI();
		setSize(180,300);
		setTitle("UniKEY");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setLocationRelativeTo(null);
		setResizable(false);
		setVisible(true);
		getContentPane().add(_uiobj);
	}
	
    public static void main(String[] args)
    {
		new myLoader();
    }
}

myUI.java

/**
 * @(#)ui.java
 *
 *
 * @author 
 * @version 1.00 2010/6/24
 */

package uniKEY;
import java.*;
import java.awt.*;
import java.awt.image.*;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;

class myUI extends JPanel implements ActionListener
{
	private JPanel _mainpanel;
	private JPanel _lightpanel;
	private JButton _button[];
	private JPanel _keypadpanel;
	private String _dbPass;
	private String _userPass;
	private String _clickValue;
	private int _click = 0;
	private JLabel _imagelabel; 
  	private Light _myLight;  
  	private Timer _timer;
  	private static final int WAIT = 0;
  	private static final int YES = 1;
	private …
emclondon 38 Junior Poster in Training

ok, I've done some googling and fixed the problem myself.

so far this is my new ui.java

/**
 * @(#)ui.java
 *
 *
 * @author 
 * @version 1.00 2010/6/24
 */

package uniKEY;
import java.*;
import java.awt.*;
import java.awt.image.*;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;

class ui extends JPanel implements ActionListener
{
	private JPanel _mainpanel;
	private JPanel _lightpanel;
	private JButton _button[];
	private JPanel _keypadpanel;
	private String _dbPass;
	private String _userPass;
	private String _clickValue;
	private int _click = 0;
	private JLabel _imagelabel; 
	private ImageIcon _myImage;
    private String _mypath;
    
    public ui()
    {
    	_clickValue= null;
		_userPass= null;
    	loadDB();
   		renderLayout();
   		renderFrame();
    }

	public void renderLayout()
	{
    	_mainpanel = new JPanel();
    	_keypadpanel = new JPanel();
    	_lightpanel = new JPanel();
    	_button = new JButton[12];
		_mainpanel.setLayout(new BorderLayout());
		_keypadpanel.setLayout(new GridLayout(4,3,0,0));
		_lightpanel.setLayout(new FlowLayout());
						
		for (int i=0; i<=9; i++)
		{
			_button[i]= new JButton(String.valueOf(i));
			_button[i].setPreferredSize(new Dimension(55,55));
		}
		
		_button[10] = new JButton("*");
		_button[0] = new JButton("0");
		_button[11] = new JButton("#");
		
		for (int i=1; i<=3; i++)
		{
			_keypadpanel.add(_button[i]);	 	
		}

		for (int i=4; i<=6; i++)
		{
			_keypadpanel.add(_button[i]);	 	
		}
		
		for (int i=7; i<=9; i++)
		{
			_keypadpanel.add(_button[i]);	 	
		}

		_keypadpanel.add(_button[10]);
		_keypadpanel.add(_button[0]);
		_keypadpanel.add(_button[11]);

		for(int i=0;i<12;i++)
		{
			_button[i].addActionListener(this);
		}
		setImage("wait");
	}

	private void setImage(String param)
	{
		_mypath = "C:/Users/sunny/Desktop/"+param+".jpg";
		_myImage = new ImageIcon(_mypath);
		_imagelabel = new JLabel(resizeImage(_myImage));
		_lightpanel.add(_imagelabel);		
	}
	
	private ImageIcon resizeImage(ImageIcon _myImage)
	{
		Image _img = _myImage.getImage();
		Image _newimg = _img.getScaledInstance(50, 38,Image.SCALE_SMOOTH); 
		ImageIcon _newIcon = new ImageIcon(_newimg); 
		return _newIcon;
	}
    
    public void renderFrame()
    {
		_mainpanel.add(_keypadpanel,BorderLayout.NORTH);
		_mainpanel.add(_lightpanel,BorderLayout.SOUTH);
		this.add(_mainpanel);
    }
    
	public void loadDB()
	{
		try
		{
			FileInputStream _fis = new FileInputStream("C:/Users/sunny/Desktop/myfile.txt"); 
			DataInputStream _dis = new DataInputStream(_fis); …
emclondon 38 Junior Poster in Training

ok I have used this

_mypath = "C:/Users/sunny/Desktop/wait.jpg";
	_myImage = new ImageIcon(_mypath);

instead of this

_mypath = "C:/Users/sunny/Desktop/wait.jpg";
        _myImage = new ImageIcon(getClass().getResource(_mypath));

and one of the NPE vanished..
Lovely!

now, coming to the other error, it says that there is an error at renderLayout();
what error can it be? Its a custom function which doesnt return or hold any values.

emclondon 38 Junior Poster in Training

yep the path for the file is valid. The file exists, and I can open the file by pasting the path in start > run

dont know why java is showing it a null :/

emclondon 38 Junior Poster in Training

norm, I posted the FULL code of my application here http://www.daniweb.com/forums/post1279061.html#post1279061 an hour ago.

maybe you have missed it and are still working with old code.

emclondon 38 Junior Poster in Training

Hi norm, I dont see any errors on line number 82, I have an error on line number 86.
and when I write the println statement above line 82 I get this

--------------------Configuration: uniKEY - JDK version 1.6.0_20 <Default> - <Default>--------------------
i =0
i =1
i =2
i =3
i =4
i =5
i =6
i =7
i =8
i =9
i =10
i =11

the value of i is an integer and not null.. what do I do now?

emclondon 38 Junior Poster in Training

ok here is my code...

/**
 * @(#)loader.java
 *
 *
 * @author 
 * @version 1.00 2010/6/24
 */
package uniKEY;

import java.*;
import java.awt.*;
import javax.swing.*;
import java.lang.*;

public class loader extends JFrame
{
	private ui _uiobj;
	
	public loader()
	{
		_uiobj = new ui();
		setSize(180,300);
		setTitle("UniKEY");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setLocationRelativeTo(null);
		setResizable(false);
		setVisible(true);
		getContentPane().add(_uiobj);
	}
	
    public static void main(String[] args)
    {
		new loader();
    }
}

loader.java

/**
 * @(#)ui.java
 *
 *
 * @author 
 * @version 1.00 2010/6/24
 */

package uniKEY;
import java.*;
import java.awt.*;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;

class ui extends JPanel implements ActionListener
{
	private JPanel _mainpanel;
	private JPanel _lightpanel;
	private JButton _button[];
	private JPanel _keypadpanel;
	private String _dbPass;
	private String _userPass;
	private String _clickValue;
	private int _click = 0;
	private JLabel _imagelabel; 
	private ImageIcon _myImage;
    private String _mypath;
    
    public ui()
    {
    	_clickValue= null;
		_userPass= null;
    	loadDB();
   		renderLayout();
   		renderFrame();
    }

	public void renderLayout()
	{
    	_mainpanel = new JPanel();
    	_keypadpanel = new JPanel();
    	_lightpanel = new JPanel();
    	_button = new JButton[12];
		_mainpanel.setLayout(new BorderLayout());
		_keypadpanel.setLayout(new GridLayout(4,3,0,0));
		_lightpanel.setLayout(new FlowLayout());
						
		for (int i=0; i<=9; i++)
		{
			_button[i]= new JButton(String.valueOf(i));
			_button[i].setPreferredSize(new Dimension(55,55));
		}
		
		_button[10] = new JButton("*");
		_button[0] = new JButton("0");
		_button[11] = new JButton("#");
		
		for (int i=1; i<=3; i++)
		{
			_keypadpanel.add(_button[i]);	 	
		}

		for (int i=4; i<=6; i++)
		{
			_keypadpanel.add(_button[i]);	 	
		}
		
		for (int i=7; i<=9; i++)
		{
			_keypadpanel.add(_button[i]);	 	
		}

		_keypadpanel.add(_button[10]);
		_keypadpanel.add(_button[0]);
		_keypadpanel.add(_button[11]);
		
		for(int i=0;i<12;i++)
		{
			_button[i].addActionListener(this);
		}
		
		_mypath = "C:/Users/sunny/Desktop/wait.jpg";
		_myImage = new ImageIcon(getClass().getResource(_mypath));
		_imagelabel.setIcon(_myImage);
		_lightpanel.add(_imagelabel);
	}
	
    public void renderFrame()
    {
		_mainpanel.add(_keypadpanel,BorderLayout.NORTH);
		_mainpanel.add(_lightpanel,BorderLayout.SOUTH);
		this.add(_mainpanel);
    }
    
	public void loadDB()
	{
		try …
emclondon 38 Junior Poster in Training

OK, I have added setVisible(true) in Init(); I still get the NPE :(
and when I remove the image code from my program, It refuses to run. and when I put back the setVisible(true) in myui.java the app runs
without any problem.

Exception in thread "main" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(ImageIcon.java:167)
    at myui.renderLayout(myui.java:82)
    at myui.<init>(myui.java:35)
    at theloader.<init>(theloader.java:21)
    at theloader.main(theloader.java:32)

Process completed.

it gives this message and it quits.

emclondon 38 Junior Poster in Training

ok here is what i have done,

import java.*;
import java.awt.*;
import javax.swing.*;
import java.lang.*;

public class theloader extends JFrame
{
	private myui obj;
	
	public theloader()
	{
		obj = new myui();
		setVisible(true);
		setSize(400,400);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		getContentPane().add(obj);
	}
	
    public static void main(String[] args)
    {
		new theloader();
    }
}

theloader.java

import java.*;
import java.awt.*;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.*;
import java.awt.event.*;

class myui extends JPanel
{
	private JPanel thepanel;
	private JPanel toppanel;
	private JButton abutton;
	private JPanel bottompanel;
	private JLabel imagelabel; 
		
	public myui()
    	{
   		Init();
    	}

	public void Init()
	{
    		thepanel = new JPanel();
    		bottompanel = new JPanel();
    		toppanel = new JPanel();
    		abutton = new JButton("click");
		thepanel.setLayout(new FlowLayout());
		bottompanel.setLayout(new FlowLayout());
		toppanel.setLayout(new FlowLayout());
		bottompanel.add(abutton);
		imagelabel.setIcon(new ImageIcon(getClass().getResource("C:/Users/dw106/Desktop/wait.jpg")));
		toppanel.add(abutton);
		bottompanel.add(imagelabel);
		thepanel.add(toppanel);
		thepanel.add(bottompanel);
	}
               
}

myui.java

i dont know whats the problem here, but this isnt working for me :(

emclondon 38 Junior Poster in Training

Android has this thing called "Dalvik" which is its own version of Java Virtual Machine. Dalvik doesnt support most of the common J2SE and J2ME classes (like Frame, Panels, etc, etc.). So, an android developer would find it hard to develop applications for Other OS (linux/mac/win) becuase he/she would have to learn the core/advanced concepts from the scratch

lond story short: It is very easy for a Java Programmer to develop applications for Android, but vice versa, is not that easy as the programmer has to learn advance java concepts from scratch.

emclondon 38 Junior Poster in Training

hello guys, I am trying to add an image to java panel.

I have tried Paint, ImageIcon and every other sort of methods and failed. can someone explain me how do I add an image onto a panel?

thanks for your time.
cheers!

emclondon 38 Junior Poster in Training

I really want to do this using state pattern as to develop my understanding in patterns.

I will then divide the application into 3 states. ready/stop/go.

-ready would display black color.
-stop would display red color.
-go would display green color.

now I have made an interface called state.
i have a method declaration in it.
i then have 3 different classes implementing the method and having the same method.
the method just returns path of the image.

on form_load i'll call up ready method (not sure how) which would display ready image on form. and when authentication occurs, i would then call up respective methods which would change the image respectively and then return back to ready state with ready image.

any ideas how to do it?

emclondon 38 Junior Poster in Training

hey guys thanks for your massive help.
thanks to you guys I could finish this simple demo finally.

and here's my 100% working code

Form1.Designer.cs file:

namespace DD
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.button3 = new System.Windows.Forms.Button();
            this.button4 = new System.Windows.Forms.Button();
            this.button5 = new System.Windows.Forms.Button();
            this.button6 = new System.Windows.Forms.Button();
            this.button7 = new System.Windows.Forms.Button();
            this.button8 = new System.Windows.Forms.Button();
            this.button9 = new System.Windows.Forms.Button();
            this.button10 = new System.Windows.Forms.Button();
            this.button11 = new System.Windows.Forms.Button();
            this.button12 = new System.Windows.Forms.Button();
            this.signal = new System.Windows.Forms.PictureBox();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            ((System.ComponentModel.ISupportInitialize)(this.signal)).BeginInit();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(12, 12);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(50, 50);
            this.button1.TabIndex = 0;
            this.button1.Text = "1";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button_Click);
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(68, 12);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(50, 50);
            this.button2.TabIndex = 1;
            this.button2.Text = "2";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button_Click);
            // 
            // button3 …
emclondon 38 Junior Poster in Training

I dont get this concept of utilizing same event handler.. maybe I must do some research on it before i can actually use it. but for now I will do this my way and change it later when I do understand what actually is happening.
--

nick, do you suggest me to validate password as soon as the user enters? wouldn't that be complex to implement? the only way I can think of to achieve it is to using some kind of observer to keep a count of button clicks made and limit the clicks to 4. is there an alternative that you can think of?

I have removed ArrayList as a whole and am working with strings now. the following is my code

{
        private string buttoncontent;
        private string userPass = null;
        private int click = 3;
        private string dbPass = null;

        public Form1()
        {
            InitializeComponent();
            authorize();
        }

and the buttons are

private void button1_Click(object sender, EventArgs e)
        {
            buttoncontent = button1.Text;
            if (click > 0)
            {
                processInput(buttoncontent);
            }
            else
            {
                check();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            buttoncontent = button2.Text;
            if (click > 0)
            {
                processInput(buttoncontent);
            }
            else
            {
                check()
            }
        }

and so on for different buttons...

private void authorize()
        {
            StreamReader sr = new StreamReader("C:\\Users\\dw104\\Desktop\\myfile.txt");
            dbPass = sr.ReadLine();
        }

        private void processInput(string value)
        {
            userPass += value;
            click--;
        }

and this is where the checking takes place. I have tested this code on a console application which …

emclondon 38 Junior Poster in Training

hello nick, thanks for the prompt reply. I have replaced the code and it works fine now.

i still need a bit of help here.. In my constructor, I have a custom function something like this:

private ArrayList passList = new ArrayList(3);
        public Form1()
        {
            InitializeComponent();
            passList.Capacity = 0;
            authorize();
        }

where the code unfolds to

private void authorize()
        {
            int i = 0;
            StreamReader srobj = new StreamReader("C:\\Users\\dw104\\Desktop\\myfile.txt");
            for (i = 0; i < 3; i++)
            {
                passList.Add((char)srobj.Read());
            }
        }

the above method authorize reads content of a file myfile.txt character by character and dumps it into an arraylist. and as its being called in the constructor, the dumping of data begins on program execution (which means my password will be read from file on program start).

now I have an arraylist (as mentioned earlier in previous post) filled with user input. all I have to do now is to compare the data of the both array lists. This is how I intend to do it.

private bool compare(ArrayList userInput, ArrayList db)
        {
            foreach (object i in userInput)
            {
                foreach (object j in db)
                {
                    if (i.Equals(j))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            return false;
        }

however I feel I am doing something really stupid here, and I dont know what it is. Is this the right way to do the things?

also, in my previous post. Is there an alternative and efficient method of writing the code …

emclondon 38 Junior Poster in Training

Hello guys, im stuck working on a simulation program. I am working on a program which mimics a door's security key panel. In case if you have been wondering what a door's security key panel is.. its a keypad on the door which unlocks the door upon entering a proper password (in this case a combination of 0-9 and * & # symbols.

I've created a form and added 12 buttons on it. Whose Text reads 1,2,3,4,5,6,7,8,9,*,0,#. Also I have added a picture box whose default image is a black image. Now according to my simulation, all I need is to enter a 4 character password and if i enter the password right, the picture box's image would change (to green if correct or red if wrong password resp.)

I dont know how you professionals do it. But I have come up with an idea of mine to capture the sequence of key presses.

this is how I do it:

on click() event on every button, I assign a value of the button respective to the text of the button pressed.

for eg: lets assume button1 has its Text "1, and button2 has its Text "2"... so its event would be something like..

private value;

private void button1_click(object sender, EventArgs e)
{
     value ="1";
}

private void button2_click(object sender, EventArgs e)
{
     value ="2";
}

private void button3_click(object sender, EventArgs e)
{
     value ="3";
}

and so on..

I made a custom function …

ddanbe commented: Well documented question! +6
emclondon 38 Junior Poster in Training

Hi guys, thanks for your suggestions. Unfortunately, none of them worked out for me.

class myclass
{
 myfunctions mfo = new myfunctions();
private void passengerWeight_TextChanged(object sender, EventArgs e)
        {
            try
            {
                double pw = Convert.ToDouble(passengerWeight.Text);
                double lw = Convert.ToDouble(luggageWeight.Text);
                double tw = pw + lw;
                double fare = mfo.getFare(tw);
                fareBox.Text = Convert.ToDouble(fare);
             }
            catch(Exception myw)
            {
                MessageBox.Show(myw.Message.ToString());
            }
        }
}

I have also tried using

double.Parse(passengerWeight.Text);

I still get the same error.. which is "Input String was not in a correct format".. and about the Double.TryParse(string); im unsure of how to use it as i have never used it. so its kinda new to me.

__________________________________________________________________


and about the dateTimePicker control. Im afraidi must have not interpreted the proper logic myself. i will read the case study and will try to solve it myself ..

appreciate the help guys :)

thanks a lot!

emclondon 38 Junior Poster in Training

hello guys and girls, im new to this forum.. so please be gentle :)

Im developing this application to improve my ability to develop applications in c#.. so far i've fingured out that im not that good at it.

I fetched out my old college coursework case study to work on, and I have found an interesting one.. a ticket booking application for a ferry which writes data to text file (csv).

so far i have developed the UI. it has

  • tabControl with 4 tabs
  • 1st tab has 7 TextBox Controls, 1 Button Control, 2 dateTimePicker Controls
  • 2nd tab has a dataGrid Control and a Button

for time being, the 3rd and 4th tab are empty.

i have created a separate class file called functions.cs
it holds all my functions (like calculating fare, writing to file, reading to file)

the route of the ferry is fixed, so 2 of the textbox(s) are un editable and have a value by default.

I am new to dateTimePicker control. I should say its a marvellous time saving control!

1 of the date time picker (its called current date) is set to the current rundate (for eg: if today is 3rd April 2010, then the control shows 3rd April 2010.. and if you run the application on 12th Devember 2011, the control would show 12th december 2011 and so on.. i think you get my point here)

the problem i …