Creating and running a Java applet - java

I thought I would try my hand at applets - I made an applet using Eclipse. It runs fine using the Run As -> Java Applet.
I read a bit about running it outside Eclipse, so I did the following:
Made a folder.
Created New -> Java Project [applet_test].
Inside the project, I created New -> Other -> Visual Swing Class -> Applet [Number1] - that created Number1.class.
Added code and ran it as a Java applet - it ran fine.
Exported the project as a JAR file (not a runnable JAR file).
Wrote HTML using TextEdit (Mac's version of Windows' Notepad). The HTML follows, below...
I put the JAR file, HTML and .class file in the folder.
In Terminal (Mac's version of Windows command prompt window), I ran Appletviewer applet_testX2.html (that's the name of my HTML).
I could see a brief flash of the application name at the top of the screen (as would any other running application).
However, the application (which should display a Jpanel with a label and a button) did NOT appear. I also tried running it from Firefox and Safari. Only the HTML code appeared.
So, what am I doing wrong? And, more importantly, how do I do it correctly?
Code follows without imports statements:
<html>
<body>
<applet code="Number1.class" archive="applet_test.jar"
width=300
height=300>
</applet>
</body>
</html>
The Java code:
public class Number1 extends JApplet {
public Number1() {
}
private static final long serialVersionUID = 1L;
#Override
public void init() {
try {
EventQueue.invokeAndWait(new Runnable() {
#Override
public void run() {
initComponents();
}
});
}
catch (Exception ex) {
ex.printStackTrace();
}
}
private void initComponents() {
setSize(320, 240);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
JLabel lblAppletTest = new JLabel("Applet test 1");
panel.add(lblAppletTest);
JButton btnPushIt = new JButton("Push it");
panel.add(btnPushIt);
}
}
Firefox source view:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Style-Type" content="text/css">
<title></title>
<meta name="Author" content="BT">
<meta name="Generator" content="Cocoa HTML Writer">
<meta name="CocoaVersion" content="1038.35">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 16.0px Helvetica}
p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 16.0px Helvetica; min-height: 19.0px}
</style>
</head>
<body>
<p class="p1"><html></p>
<p class="p1"><span class="Apple-converted-space"> </span><body></p>
<p class="p1"><span class="Apple-converted-space"> </span><applet code="Number1.class" archive="applet_test.jar"</p>
<p class="p2"><br></p>
<p class="p1"><span class="Apple-converted-space"> </span>width=300</p>
<p class="p1"><span class="Apple-converted-space"> </span>height=300></p>
<p class="p1"></applet></p>
<p class="p1"></body></p>
<p class="p1"></html></p>
</body>
</html>

My guess is that here:
<applet code="Number1.class" archive="applet_test.jar"
you're not taking packages into consideration. For instance, if the package is myPackage.vol3 then the line should read
<applet code="myPackage.vol3.Number1.class" archive="applet_test.jar"
But if this doesn't help, you'll want to extract any error messages that the browser gives you and edit your original post to show us what they are.

Using Appletviewer
------------------
Write code of Applet.
If you installed tomcat in D:
code
-
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class MyApplet extends Applet
{
public void init()
{
System.out.println("init intilize");
GridLayout g=new GridLayout(4,6,0,0);
setLayout(g);
MyListener m=new MyListener();
for(int i=1;i<=12;i++)
{
Button b=new Button("ok"+i);
add(b);
b.addActionListener(m);
}
}//end of init
public void start()
{
System.out.println("applet started");
}//end of start
public void stop()
{
System.out.println("applet stop");
}//end of
public void paint(Graphics g)
{
g.drawString("Naveed",200,25);
g.drawOval(20,30,30,20);
System.out.println("applet paint");
}//end of start
public void destroy()
{
System.out.println("applet destroy");
}//end of start
}
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("button clicked");
}//end of actionPerformed
}
Now save this code in D:, not in sub folder.
First Compile it.
open the cmd
cd D:
type
`javac MyApplet.java -d classpath D:\Tomcat\common\lib\servlet.jar`
This will make a MyApplet.class file
Now make a html file.
<html>
<body>
<applet code="Number1.class" width=30 height=300 > </applet>
</body>
</html>
Save with the name of you want let's say app.html
run the html file now.
In the cmd window
appletviewer app.html
Output will be in front of you.

Related

Start: applet not initialized error in eclipse [duplicate]

I'm learning Java and reading this book: https://www.fca.pt/cgi-bin/fca_main.cgi/?op=2&isbn=978-972-722-791-4.
In this book, I have a Java applet exercise. I can run it in Eclipse in appletviewer and works well. but I'm having trouble integrating the applet into HTML.
Here's my java code:
package packageteste;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.util.Date;
public class Relogio extends Applet implements Runnable{
Date data;
Thread proc;
Font f = new Font("TimesRoman", Font.BOLD, 40);
public void start(){
proc = new Thread(this);
proc.start();
}
public void stop(){
proc = null;
}
#SuppressWarnings("static-access")
#Override
public void run() {
Thread th = Thread.currentThread();
while(proc == th){
data = new Date();
try{
th.sleep(500);
}catch(InterruptedException e){}
repaint();
}
}
public void paint(Graphics g){
g.setFont(f);
g.setColor(Color.GREEN);
g.drawString(data.toString(),20,60);
}}
And now here's my html code :
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<applet code = "packageteste.Relogio.class" width="700"></applet>
</body>
</html>
code = "packageteste.Relogio.class" must not include .class
If you have your applet built into a .jar file use the archive="..." attribute to tell the browser what .jar it is.
If you don't have a .jar make sure the class packageteste.Relogio can be found as Relogio.class in the packageteste directory.
See also here: How to specify correctly codebase and archive in Java applet?

JxBrowser 6.1 JavaScript Java Bridge API is not working

I think that there is a problem with the JavaScript Java Bridge API in JxBrowser 6.1 . I have tried a very simple code to call a method of a java class in Javascript. Here are the codes. In java, java is set as a property on javascript window object to an instance of Events class and then the html is loaded. In html, I simply call Close method of Events class. But when I click the Close button, java Close function doesn't get called and there is a message in console from JxBrowser saying :
Uncaught TypeError: Cannot read property 'Close' of undefined
which means that java property for window object is not defined.
Main.java:
public class Main extends Application {
private Browser browser;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Platform.setImplicitExit(false);
browser = new Browser();
JSValue window = browser.executeJavaScriptAndReturnValue("window");
window.asObject().setProperty("java", new Events());
BrowserView browserView = new BrowserView(browser);
StackPane pane = new StackPane();
pane.getChildren().add(browserView);
Scene scene = new Scene(pane, 330, 470);
primaryStage.initStyle(StageStyle.UNDECORATED);
primaryStage.setScene(scene);
primaryStage.show();
browser.loadURL(Main.class.getResource("templates/simple.html").toExternalForm());
}
}
class Events {
public void Close() {
System.out.println("close button clicked");
}
}
simple.html:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<button id="Close">Close</button>
<script>
document.getElementById('Close').onclick = function () {
window.java.Close();
}
</script>
</body>
</html>
Here is the article i've used to do this:
https://jxbrowser.support.teamdev.com/support/solutions/articles/9000013062-calling-java-from-javascript
Please correct me if i'm wrong.
Thanks in advance.
Please make sure that you load required web page before you access its JavaScript and register Java objects. For example:
browser.addLoadListener(new LoadAdapter() {
#Override
public void onFinishLoadingFrame(FinishLoadingEvent event) {
if (event.isMainFrame()) {
Browser browser = event.getBrowser();
JSValue value = browser.executeJavaScriptAndReturnValue("window");
value.asObject().setProperty("Account", new Account());
}
}
});
browser.loadURL("form.html");

Can't start applet's html in browser

I'm just begining to learn applet tehnology in universitaty. Need an advice or help. I can't ru applet's html in browser. On starting it I have only a message "ClassNoFoundExeption". Work with Firefox+Eclipse+Xubuntu. I guess I installed all what I need in browser.
My simple code:
Pack/Recs.java
package Pack;
import java.applet.*;
import java.awt.*;
public class Recs extends Applet {
private static final long serialVersionUID = 1L;
int a;
int b;
String tempStr;
public void start()
{
a = 50;
b = 50;
tempStr = "Hallo!";
}
public void paint(Graphics g)
{
g.drawString(tempStr, 10, 10);
g.drawOval(20, 20, a, b);
}
}
My html file:
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title>Java Applet</title>
</head>
<body>
<h3>Java Applet</h3>
<applet code="Pack.Recs.class" height="400" width="500">
<param name=width_a value=100>
<param name=height_a value=200>
Your browser does not support the <code>applet</code> tag.
</applet>
</body>
</html>
I found a solution! I moved *.java file from pack and leaved it in /src root.
In html I actualized path to class and runned html file from /bin folder.

Java applet will not execute in Safari

Beginner Java applet user. I'm not sure as to why my applet will not display in a page. I'm almost positive I have all necessary information. Is it possible that it will not show up due to using Safari? Will not show up in Chrome, either. Do you see what I'm missing? Thanks
EDIT: This >> Java Applet sandboxed in Safari? doesn't help, either.
Java program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color.*;
public class JNumberOne extends JApplet implements ActionListener
{
Font numberOneFont = new Font("Teen", Font.BOLD, 24);
JButton numberOneButton = new JButton("Who's Number One?");
JLabel numberOneMessage = new JLabel(" ");
Container con = getContentPane();
public void init()
{
numberOneMessage.setFont(numberOneFont);
con.add(numberOneButton);
con.setLayout(new FlowLayout());
con.setBackground(Color.WHITE);
numberOneButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
con.remove(numberOneButton);
numberOneMessage.setText("The 1992 Texas Rangers");
con.add(numberOneMessage);
con.setBackground(Color.YELLOW);
validate();
}
}
HTML for Applet
<!DOCTYPE html>
<html>
<head>
<style>
body{text-align:center; background:#00008B;opacity:.5;}
</style>
</head>
<body>
<object code = "JNumberOne.class" width=450 height=100></object>
</body>
</html>
Remove the quotes from the class name.
Replace
<body>
<object code = "JNumberOne.class" width=450 height=100></object>
</body>
With
<body>
<object code = JNumberOne.class width=450 height=100></object>
</body>

calling javascript function from within java applet - Firefox vs. IE

HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-15" />
<script type="text/javascript">
var foo;
function test(s)
{
foo = s;
alert(foo);
}
window.onload = function ()
{
foo = 'init';
document.getElementById('foo').doit();
alert(foo);
}
</script>
<body>
<applet id="foo" code="TestApplet.class"
archive="TestApplet.jar" width="0" height="0"></applet>
</body></html>
Java applet code:
public void doit ()
{
try {
getAppletContext().showDocument(
new URL("javascript:test(\"foobar\")"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
When I call this HTML page :
In IE (8) I get: First popup ("foobar"), second popup ("foobar").
In Firefox (19.2, 30.0) I get: First popup ("foobar"), second popup ("init").
Can anybody explain why? Obviously, foo is written by the applet only temporarily.
Many thanks in advance.

Categories