Home arrow static arrow Java Programming [Archive] - functions in applet classes
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - functions in applet classes
This topic has 9 replies on 1 page.

Posts:26
Registered: 6/14/04
functions in applet classes  
Jun 24, 2004 10:31 PM



 
hi guys
can u tell me whether functions other than init(),paint(),action(),etc(which are the basic functions) are allowed in an applet class.
Thanks!
avichal167
 

Posts:1,135
Registered: 1/16/04
Re: functions in applet classes  
Jun 24, 2004 11:02 PM (reply 1 of 9)



 
hi guys
can u tell me whether functions other than init(),paint(),action(),etc(which are the basic
functions) are allowed in an applet class. Thanks! avichal167

Yes...
You can add your own methods to your applet class to do the things that you need it to do...

For more information you can look at this from the Java Tutorial...
http://java.sun.com/docs/books/tutorial/applet/index.html

There is more stuff in the tutorial regarding applets among other things...

- MaxxDmg...

- ' He who never sleeps...
 

Posts:1,135
Registered: 1/16/04
Re: functions in applet classes  
Jun 24, 2004 11:07 PM (reply 2 of 9)



 
Here is a simple example...
import java.applet.Applet;import java.awt.Graphics;import java.awt.Color; public class SimpleApplet extends Applet{   public void init() {        setBackground(Color.cyan);  }  public void start() {        System.out.println("starting...");  }  public void stop() {        System.out.println("stopping...");  }  public void destroy() {        System.out.println("preparing to unload...");  }  public void paint(Graphics g){        g.setColor(Color.blue);        g.drawRect(0, 0,                   getSize().width -1,                   getSize().height -1);        g.setColor(Color.red);        g.drawString(theMessage(), 15, 25);// calls theMessage method for the message  }  public String theMessage(){ // my own simple method  		 return "I am a method in this class";  }}


Have fun...

- MaxxDmg...

- ' How should I know, I just wrote the thing... '
 

Posts:26
Registered: 6/14/04
Maxx--What about this?Re: functions in applet classes  
Jun 24, 2004 11:30 PM (reply 3 of 9)



 
He Maxx,then what's wrong in this one:
(Please tell me something about "exceptions" which I should give in the paint() method.)


I have written this code for a GUI which checks for 4 types of punctuation errors in .txt files.
The code compiles correctly and the Gui also appears nicely but when I Give a pathname in the space provided(also using the escape sequence '
' for the '\' character ) it does not generate the "errors.txt"
file whhich it is supposed to do.

The code is as follows:

import java.io.*;
import java.awt.*;
import java.applet.*;
public class textcopy extends Applet
{

public void init()
{
Choice ch=new Choice();
ch.addItem("Click Next to continue.");
ch.addItem("Framework Properties");
Label l1=new Label(" ");
Label nm=new Label("Please specify the errors that you want to be checked for in the file:");
Label a1=new Label("Write the pathname here:");
ta=new TextArea(1,20);
B=new Button("OK");
Checkbox b1=new Checkbox("Punctuation errors");
Checkbox b2=new Checkbox("Finding whether a key string is misspelt");
Label l2=new Label("Please select the key string from one of these:");
add(a1);
add(ta);
add(B);
add(l1);
add(nm);
add(b1);
add(b2);
add(l2);
add(ch);
}

TextArea ta;
Button B;String str="";
public boolean action(Event e,Object obj)
{
if(e.target instanceof Button)
{
repaint();
return true;
}
return false;

}
public void paint(Graphics g)
{
String s=ta.getText();
try{
FileReader fin=new FileReader(s);
PrintWriter fout=new PrintWriter(new BufferedWriter(new FileWriter("errors.txt")));
parse(fin,fout);

fin.close();
fout.close();

}
catch(IOException e){}

}

//This is the code for the parser ------it is perfectly correct--so you dont need to check this.

public static void parse(FileReader fin,PrintWriter fout)throws IOException
{
String str="Punctuation Errors:\n"; /*Heading*/
fout.println(str);
fout.println("========================================================");

int i=0,j=0,k=0,l=0;
j=fin.read();
do{
do{
i=j;
j=fin.read();
}while((!((char)i=='('&&(char)j=='R'))&&(j!=-1));
if(j==-1)break;

j=fin.read();
j=fin.read();
j=fin.read();
j=fin.read();
j=fin.read();
j=fin.read();
j=fin.read();
char refnum[]=new char[5];
l=0;
while((char)j!=')')
{
j=fin.read();
if((char)j!=')')
refnum[l++]=(char)j;
}
fout.write("REF. NUM: ");
for(int a=0;a<l;a++)fout.write(refnum[a]);fout.write(": ");
j=fin.read();
l=0;
do{

i=j;
j=fin.read();
if((char)i=='\n')
{
k++;
//'k' gives the line no. and finally the no. of lines and neglects the lines before first occurence of "Ref Num
}
if(((char)i==',')&&((char)j!=' '))

{
l++;
String st=l+". error at line number "+ (k+1) + ": There should be "+
"a space after comma(,) \n";
fout.println(st);
}

if(((char)i=='.')&&((char)j!=' '))

{
l++;
String st=l+". error at line number "+ (k+1) + ": There should be "+
"a space after period(.) \n";
fout.println(st);
}

if(((char)i=='.')&&((char)j=='.'))
{
l++;
String st=l+". error at line number "+ (k+1) + ": There should not be "+
"two periods(.) together \n";
fout.println(st);
}

if(((char)i==' ')&&((char)j=='.'))
{
l++;
String st=l+". error at line number "+ (k+1) + ": There should not be "+
"a space before a period(.) \n ";
fout.println(st);
}
}while((!((char)i=='-' && (char)j=='T')) && j!=-1);
fout.println(" ");

/*if(l==0)
fout.println("No errors!!!!");*/
if(j==-1)break;

}while(j!=-1);
}
}

The html file I made for this is as follows:


<html>
<body bgcolor="Red">
<center>

Welcome to qch

<applet code=textcopy.class width=800 height=400 >
</applet>
</center>
</body>
</html>

N.B.:I have not used main() in the above program becoz it would not have been a pure GUI program

Please see what I did wrong in the above code.
Thanks in advance
Avichal

 

Posts:1,135
Registered: 1/16/04
Re: Maxx--What about this?Re: functions in applet classes  
Jun 25, 2004 1:05 AM (reply 4 of 9)



 
Okay... Lets see...
Well the code looks fine, but...

I am getting these errors while running the Applet, using AppletViewer from the command console and looking at the Java Console ( right click on Java Coffee cup icon in System Tray) when running the applet in my web browser...
.appletviewer textcopyhtml.htmlException in thread "AWT-EventQueue-1" java.security.AccessControlException: access denied (java.io.FilePermission  read)        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:264)        at java.security.AccessController.checkPermission(AccessController.java:427)        at java.lang.SecurityManager.checkPermission(SecurityManager.java:524)        at java.lang.SecurityManager.checkRead(SecurityManager.java:863)        at java.io.FileInputStream.<init>(FileInputStream.java:100)        at java.io.FileInputStream.<init>(FileInputStream.java:66)        at java.io.FileReader.<init>(FileReader.java:41)        at textcopy.paint(textcopy.java:51)        at sun.awt.RepaintArea.paintComponent(RepaintArea.java:248)        at sun.awt.RepaintArea.paint(RepaintArea.java:224)        at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:248)        at java.awt.Component.dispatchEventImpl(Component.java:4009)        at java.awt.Container.dispatchEventImpl(Container.java:2019)        at java.awt.Component.dispatchEvent(Component.java:3781)        at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)        at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:234)        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)         at java.awt.EventDispatchThread.run(EventDispatchThread.java:110) .

If you notice a couple key words pop up in the error message...

java.security.AccessControlException: access denied (java.io.FilePermission read)
java.security.AccessControlContext.checkPermission(AccessControlContext.java:264)
java.security.AccessController.checkPermission(AccessController.java:427)
java.lang.SecurityManager.checkPermission(SecurityManager.java:524)
java.lang.SecurityManager.checkRead(SecurityManager.java:863)

This is because Applets runs in a "SandBox" which is a restricted and secure environment and are not given "full" access to the underlying system for security purposes...
Imagine you visit a website where once the Applet loads in your browser, it starts to erase, copy files to ( like a possible virus or spyware) or from you computer like your address books or other sensitive files...
That would would be bad, so Applets are restricted...

There is a way that you can create a "Signed Applet" that would be allow your File IO operations, but unfortunately, I am not well versed enough in Applets at this time to give you any assistance on doing so...

So your best bet for now is either reading up in Applets or make it a standalone application...

N.B.:I have not used main() in the above program becoz it would not have been a pure GUI program

Not sure on what you mean with this...
main() has nothing to do with a program being "pure" GUI or not... Applets run in a web browser, but you not limited to the Web browser when it comes to GUIs...
standalone application can have a GUI also...

- MaxxDmg...

- ' He who never sleeps... '
 

Posts:1,135
Registered: 1/16/04
Re: Maxx--What about this?Re: functions in applet classes  
Jun 25, 2004 2:12 AM (reply 5 of 9)



 
N.B.:I have not used main() in the above program becoz it would not have been a pure GUI program

For example... This is a GUI program...
import java.awt.*;import javax.swing.*;import java.io.*;public class GUISample extends JFrame {   	private JTextArea jtxArea; 	public GUISample(){	   	super("GUI Sample");		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		jtxArea = new JTextArea(15,20);		jtxArea.setEditable(false);		getContentPane().add(jtxArea);		pack();		setVisible(true);	}	public void readAndDisplay(){	    try{	        File afile = new File("test.txt");	       	FileInputStream fis = new FileInputStream(afile);		   	try{		   		byte[] strBuff = new byte[(int)afile.length()];		   		fis.read(strBuff);		   		try{		   			jtxArea.setText(new String(strBuff));		   			fis.close();		   		}catch(NullPointerException npe){jtxArea.setText("Null Pointer Exception");}	 	   	}catch (IOException ioe){jtxArea.setText("IO Exception");}	 	}catch (FileNotFoundException fnfe){ jtxArea.setText("File Not Found");}	}	public static void main(String[] args){ // main ()	   	GUISample gspl = new GUISample();		gspl.readAndDisplay();		}}

You will need a file called test.txt with some text like below...
This is a test... Have fun...- MaxxDmg...

and place it in the same folder\directory as the GUISample class if you want to run it properly, but if you noticed, there are a lot of try and catch clauses that display error messages in the GUI if there are any IO problems...

Its a very basic application, no buttons, can't edit but its a GUI program...

- MaxxDmg...

- ' He who never sleeps... '
 

Posts:26
Registered: 6/14/04
Maxx,a questionRe: Maxx--What about this?Re: functions in applet classes  
Jun 25, 2004 2:47 AM (reply 6 of 9)



 
He Maxx,I put both the files in a particular folder and in the command prompt typed:
appletviewer GUISample.java
and also tried out typing
appletviewer GUISample.class
after compiling but just the prompt is coming back with no output.
I want to know how do you run the program
 

Posts:26
Registered: 6/14/04
I am sorry Maxx Re: Maxx--What about this?Re: functions in applet classes  
Jun 25, 2004 2:59 AM (reply 7 of 9)



 
He Maxx,I'm sorry for asking such a silly question.Actually,I should have seen that the program contains main().So I should have used

java GUISample
for compilation. Anyways this is the place when you will understand what I meant by perfect GUI.-----I DONT WANT THE USER OF THIS GUI TO USE THE COMMAND PROMPT TO USE MY PROGRAM.IT SHOULD JUST BE LIKE AN ICON FOR AN HTML FILE IN WHICH IF U CLICK THEN YOUM WILL STRAIGHTAWAY SEE THE GUI.THAT IS ALSO THE REASON FOR MY WRITING THE HTML FILE ALONG WITH THE PROGRAM.
I hope I am clear.Thank you very much for your concern and please keep helping me.I will try out with the forum to see if anybody knows anything about Signed Applets.
Thanks again.
-Waking you up again---
--Avichal
 

Posts:1,135
Registered: 1/16/04
Re: I am sorry Maxx Re: Maxx--What about this?Re: functions in applet classes  
Jun 25, 2004 3:40 AM (reply 8 of 9)



 
Well, you can create a shortcut for you standalone application...
For example in XP...
Right Click on the Desktop (or Folder Window) and create a new Shortcut
then type in the "Target " field the following where C:\YourFolder is the path to you app's class file...
and GUISample is your app's main class name, and it's case sensitive...
example...
javaw.exe -classpath C:\YourFolder GUISample

then click Apply... Now you have a working Shortcut to your application...
Notice that I am using the -classpath switch to indicate the path to GUISample and GUISample has the extension omitted... if you type GUISample.class then you will get an error, just GUISample with no .class extension...
and make sure in the "Start In" field has the path to your class also... i.e. C:\YourFolder

For info check on Java.exe and Javaw.exe... ( though it does not tell you how to create shortcuts)
http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/java.html

Or you can create an executable Jar file... which works just like an exe file...
Here is a link to the Tool docs for Jar.exe
http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/jar.html
at the bottom of that page will be additional links that can be a guide for that process...

Hope this helps...

- MaxxDmg...
- ' How should I know, I just wrote the thing...'
 

Posts:26
Registered: 6/14/04
THANKS MAXX Re: Maxx--What about this?Re: functions in applet classes  
Jun 25, 2004 4:20 AM (reply 9 of 9)



 
HE MAX!!--GUESS WHAT?-IT WORKED!!!
NOW I WILL CHECK OUT WHETHER I REALLY REQUIRE THE USE OF SIGNED APPLETS OR NOT BECAUSE IF I AM USING MAIN,THEN THE FILE READING AN D WRITING CAN BE DONE USING CALLS FROM MAIN.I AM NOT SURE BUT I WILL TRY TO WORK IT OUT THAT WAY.
THANKS FOR YOUR CONSTANT SUPPORT.
AVICHAL
 
This topic has 9 replies on 1 page.