I am having some trouble trying to get a JApplet to display in a Browser [IMG]http://javafaq.nu/images/smiles/icon_sad.gif[/IMG] . The applet does compile and does come up (displays) in a Microsoft Windows window frame, but does not display in a browser. I have several components that I place in JPanels and successfully place those in JPanels and finally into a JFrame.

Additionally, I am using a FileReader to extract some information that is then displayed. The program compiles and runs, but does not display in a internet browser (neither Firefox 1.5.05, IE 7.05, nor Samba). I would still like to have the option to read in multiple files, so if anyone could show me how to do this, that would be great.

I am questioning both my init() method and my paint(Graphics g) method. I have included a very simplistic version of the file (modified) that has many of the same features. (With this simplified version, it has the same problem as the more complex program in that it doesn't show up in a browser.)

If anyone would be willing to help me out, I would appreciate it. I have included the .java file, the .html file, and the .txt file that displays the information. Please let me know what I can do to allow this program to display in a Browser.

///////////////////////////////////////////
The text file

Save the text as 'HelloWorld.txt' the
file should be one line of text.

(Below the forward slashes)
//////////////////////////////////////////

Hello@@@@@@@%%%%%%%%%%%%%%%%%%%%%%% Fellow Java Programmers&&&&&&&&&&&&&&&&&&&&&&&&&, Thank**********You(((((((((((((((((((( *************For Your @@@@@@@@Help!***********

//////////////////////////////////////////////
End of Text file
//////////////////////////////////////////////


///////////////////////////////////////////////

Here is the coding for the HTML file

(Copy the file below the forward slashes)

Just for verification, would you please
include the directory information that I
would need to save this in (ie same
directory, an upper or sub directory)
///////////////////////////////////////////////

<head>
</head>

<body>
	<applet code="HelloWorld.class">
	</applet>

</body>


<!--Thanks for your help! -->

/////////////////////////////////////////////////

End HTML file

/////////////////////////////////////////////////

/////////////////////////////////////////////////

Just in Case the Java file doesn't load

Save this as HelloWorld.java
/////////////////////////////////////////////////

/**
 *
 * @author Bob Smith
 */


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.filechooser.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.JApplet;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;


public class HelloWorld extends javax.swing.JApplet
{
    FileReader fr;//can be removed
    BufferedReader br;//dido
    StringTokenizer st;//dido
    //ChangeLine
    String temp="", line="";//line="Thanks TAs";
    JLabel label;
    JPanel panel, radio_Pan, combo_Pan, button_Pan, check_Pan;
    JRadioButton rb1=new JRadioButton("Option1"), rb2=new JRadioButton("Option2");
    JComboBox combo=new JComboBox();//I don't ever fill this, I just wanted it for display
    JCheckBox ch1=new JCheckBox ("ch1"), ch2=new JCheckBox("ch2");
    JButton yes=new JButton("Yes"), no=new JButton ("No");
    JFrame frame = new JFrame("Hello World");


    /*Creates a new instance of HelloWorld */
    public HelloWorld() 
    {
        stuff();
    }
    public void stuff()//sets up the JApplet
    {
        try
        {
        
        
        //From here to next comment, will need to be commented if the filereader is removed
            fr=new FileReader("HelloWorld.txt");
            br=new BufferedReader (fr);
            temp=br.readLine();
            st=new StringTokenizer(temp, " \t\r\n%@&(*");
            
            while(st.hasMoreTokens())
            {
                line+=st.nextToken() + " ";
            }
            System.out.println(line);
       //From here to previous comment, will need to be commented if the filereader is removed


            label=new JLabel (line);
            label.setForeground(Color.red);
            panel=new JPanel();
	    button_Pan=new JPanel();
	    radio_Pan=new JPanel();
	    combo_Pan=new JPanel();
	    check_Pan=new JPanel();

	    button_Pan.setLayout(new BoxLayout( button_Pan, BoxLayout.X_AXIS));
	    button_Pan.add(yes);
	    button_Pan.add(no);

	    combo_Pan.add(combo);

	    radio_Pan.add(rb1);
	    radio_Pan.add(rb2);
	    
	    
	    check_Pan.add(ch1);
	    check_Pan.add(ch2);
	    




	    
            panel.setLayout(new BorderLayout());
            panel.add(label, BorderLayout.CENTER);

	    panel.add(button_Pan,BorderLayout.SOUTH);
	    panel.add(radio_Pan, BorderLayout.WEST);
	    panel.add(combo_Pan,BorderLayout.EAST);
	    panel.add(check_Pan, BorderLayout.NORTH);
            
            
            setContentPane(panel);
            
            frame.getContentPane().add(panel);
            frame.setSize(400, 400);
            frame.pack();
            frame.setVisible(true);
            frame.validate();
        }
// 	catch (Exception e)
// 	{
// 	}
////////////////////////////////////////////
//These catches will need to be commented out if the filereader is removed
        catch(FileNotFoundException fnfe)
        {
            System.out.println(fnfe.toString());
        }
        catch (IOException ioe)
        {
            System.out.println(ioe.toString());
        }
        catch (NoSuchElementException nsee)
        {
            System.out.println(nsee.toString());
        }

    }
    public void paint(Graphics g)
    {
        frame.paint(g);
        panel.paint(g);
        label.paint(g);
        
        
        super.paint(g);
        this.paint(g);
    }
    
    
    public void init() 
    {
        
        this.setBackground(Color.white);
        this.setSize(400, 400);
        Container contentPane = this.getContentPane();
        //contentPane.setLayout(new BorderLayout());
        //contentPane.add(panel, BorderLayout.CENTER);
    }
    
    public static void main(String[] args) throws IOException 
    {
        HelloWorld hw = new HelloWorld();
        hw.init();
        
    }
    
    
}

////////////////////////////////////////////////////////////////////

End of Java file

////////////////////////////////////////////////////////////////////


Thanks for your help!

Recommended Answers

All 10 Replies

Member Avatar for iamthwee

You need the .class file in the same directory as well!

I've tested it using internet explorer, something comes up, but it goes mad.
Firefox refuses to work. The code probably has a few bugs in there?

You can't do that unless the Applet is signed.

You can't do that unless the Applet is signed.

What do you mean by signed? How do I make something signed? Why does the file compile and display in a Windows window frame, but not in the browser?:confused: Your thoughts would be appreciated.:D

Signed means that the Applet has access to the browsers local machine.

Due to security risks associated with Applets, applets are NOT ALLOWED TO ACCESS THE LOCAL MACHINE. However, if the applet is Signed then it is allowed to access the local machine.

I do not know about how to get an Applet Signed, but i'm sure there are plenty of pages on the triple W that will tell you how to do it.

Signed means that the Applet has access to the browsers local machine.

Due to security risks associated with Applets, applets are NOT ALLOWED TO ACCESS THE LOCAL MACHINE. However, if the applet is Signed then it is allowed to access the local machine.

I do not know about how to get an Applet Signed, but i'm sure there are plenty of pages on the triple W that will tell you how to do it.

What about if I don't use any IO, I still do not know how to display a JApplet using panels and other components:sad: . Try it if you would like; comment out my IO (I commented so that it could easily be done), and then see if the JApplet will display. This is what I meant in my original posting saying I thought that there was a problem with my init() and paint(Graphics g) methods.

If someone knows how to sign an Applet (see previous responses) and/or display a JApplet with panels, frames, and other components, please let me know. That would be really cool. :cool:

Member Avatar for iamthwee

What about if I don't use any IO, I still do not know how to display a JApplet using panels and other components

Try coding an extremely trivial applet. You should be able to get it to work with your browser.

All you have to do is provide the class file.

If someone knows how to sign an Applet (see previous responses) and/or display a JApplet with panels, frames, and other components, please let me know. That would be really cool.

To be honest, it looks more trouble than it's worth.

http://www.suitable.com/docs/signing.html

You'll have to consider various conditions depending on which browser you're using, if you intend to release the code into the public domain.

Try coding an extremely trivial applet. You should be able to get it to work with your browser.

All you have to do is provide the class file.

The coding for what I have posted seems to be a trivial applet, but for some reason unkown to me, I have not been able to get a JApplet to display with panels (or other components for that matter) in a browser. (I have had limited sucess with JApplets that draw various items, but not with the JComponents.) Would someone be willing to post an example of both the HTML and java coding needed to make and display in a browser a JApplet with 1 JPanel, 1 JLabel, and 1 JButton. I don't care if the button does anything:eek: , I just would like to see a working example of a java program that makes a JApplet display in a browser. I have tried repeated times with various versions of JApplets, and so far I have had no sucess getting the JApplet to display in a browser. Additionally, the internet postings of JApplets that I have seen are ones that use the draw() method. If someone could send me the coding for how to do this, I would appreciate it.:cheesy: (As you can tell by the coding in the first posting of this thread, I have tried with the class file from the program posted, but to no avail.)

As always, Thank you to everyone that has offered help!

Member Avatar for ede

ı look at your applet code and noticed you added main(). in Applets no need a main method. applets start with method init(). same Threads start with run() method.

ı wrote a sample applet code. ı wish it will be useful.

and as other friends point out to be able to show applets in local machine some security operations must done. but ı have not enough information about this. however recently ı did a change in JDK where there is a file named java.policy. if you add like following permission you may succeed.

grant {
  permission java.io.FilePermission "HelloWorld.txt", "read, write, delete, execute";
};

but this may be dangerous!

here's code ı wrote. and ı test it successfully.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;

public class appletDemo extends JApplet implements ActionListener {
    private demoPanel panel;

    private JPanel panel2;

    private JLabel label;

    private JTextArea area;

    private JButton button;

    public void init() {
        Container c = getContentPane();
        c.setLayout(new BorderLayout());
        panel = new demoPanel();
        panel.setBackground(Color.decode("#98CCFF"));
        panel.setBorder(BorderFactory.createTitledBorder("JPanel"));
        panel2 = new JPanel();
        panel2.setLayout(new BorderLayout());
        panel2.setBackground(Color.decode("#D1E8FF"));
        panel2.setBorder(BorderFactory.createTitledBorder("JTextArea Panel"));
        area = new JTextArea();
        panel2.add(new JScrollPane(area));
        JPanel p = new JPanel();
        label = new JLabel("Press button to show content");
        p.add(label);
        button = new JButton("FILE READ");
        button.addActionListener(this);
        p.add(button);
        c.add(p, BorderLayout.NORTH);
        c.add(panel, BorderLayout.SOUTH);
        c.add(panel2, BorderLayout.CENTER);

    }

    public void fileRead() {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(
                    new FileReader(
                            "C:\\Documents and Settings\\feytullah\\Desktop\\HelloWorld.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String line = "";
        while (true) {
            try {
                line = reader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (line == null)
                break;
            area.append(line + "\n");
        }
    }

    public void actionPerformed(ActionEvent e) {
        fileRead();
    }

    public class demoPanel extends JPanel {

        public Dimension getPrefferedSize() {
            return new Dimension(400, 100);
        }

        public void paint(Graphics g) {
            // Call super class constuctors
            super.paint(g);
            g.drawString("JApplet demo!!!", 25, 25);
        }
    }

}

ı look at your applet code and noticed you added main(). in Applets no need a main method. applets start with method init(). same Threads start with run() method.

ı wrote a sample applet code. ı wish it will be useful.

and as other friends point out to be able to show applets in local machine some security operations must done. but ı have not enough information about this. however recently ı did a change in JDK where there is a file named java.policy. if you add like following permission you may succeed.

grant {
permission java.io.FilePermission "HelloWorld.txt", "read, write, delete, execute";
};

but this may be dangerous!

Thank you for your help and for answering one question that I had by the example code that you sent me. First, I was able to see that the JApplet works in an Applet Viewer, and I thank you for the program. Second, I was able to get the panels to display in a browser (this was very helpful to see an example that did load in a browser).

There is a difference in performance between the Applet Viewer version and the Browser version, in that I couldn't get the information that was in the *.txt file to display when the applet was displayed in a Browser.:sad:

Does anyone know how to read in and also write a file from a JApplet while the applet is displayed in a browser? In a previous posting, someone mentioned that the applet would have to be signed. IF THIS IS TRUE could someone tell me how to/refer me to a site that is very easy to follow -- being as I have never done this before:surprised .

Additionally, if someone could tell me how to use the command mentioned above:

grant {
permission java.io.FilePermission "HelloWorld.txt", "read, write, delete, execute";
};

With the instructions on how to use this, additionally could someone mention the security risks involved?

Thanks for your help!

--sciocosmist

Member Avatar for ede

as you know applets are executed on client machines(loaded and run by browsers). Although
local codes are trusted to have full access system resources(like local file
system,sockets,etc.) applets are untrusted and can access only the limited resources
provided inside the sandbox(sandbox -> original java security model).by default file
operations are not allowed,too.Because malicious code can do some undesired operations such
as sending some user information through intenet to unwanted individuals.in short any file
operation like reading,writing,deleting can done by applets if allowed! I do not have
adequate information under what circumstances applets are allowed to access system
resources. however java editors create own security policies. thus they can execute applets.
so we easily do any system operations but browsers are restricted.
as i know, together with concept of "signed applet", "correctly digitally signed applet
is treated as if it is trusted local code if the signature key is recognized as trusted by
the end system that receives the applet" (exactly i took last sentence inside quotation
marks from an source).Unsigned applets still run in the sandbox.
there is a file named java.policy inside the JRE (lib\security\java.policy). if you open
the file and add required permissions you can view applet through browser.

permission java.io.FilePermission "HelloWorld.txt", "read, write, delete, execute";

With this line we allow all operations on file "HelloWorld.txt". if you say "i'd like to
allow access permission to all files" it's enough to write "*" instead of
"HelloWorld.txt".via an program called policytool.exe (inside JDK) you can create policy
files.
i'd like just to point out, my English is not enough to write detailed explanation about
this issue. and of course not sufficient information about java security policy. java is
really used in many areas.
are you concerned with java for a long time or new java learner? if you ask i'm
interested approximately for two years. actually i took java lesson at university. and it
seems a good programming language but i'm still worried what i can do with java. this year i
think to do "thesis" using java.
that's all for now. bye

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.