I have a web page with an applet as the only element that looks something like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>...</title>
</head>
<body>
<applet style="padding:1px; border:1px solid gray" mayscript="mayscript" codebase="..." name="AppletName" code="..." archive="..." width="600" height="500" alt="Alt Text">
<param name="initial_focus" value="true"/>
Alt Text
</applet>
</body>
</html>
When the page initially loads, focus is set in the applet and I can tab through and interact with the applet just fine. However, if I leave the browser window and then come back to it, I can no longer regain focus on the applet just using the tab key.
Pressing F5 to reload the page fixes the page so that the Applet regains focus, but this solution is unacceptable.
How do I solve this problem? Thanks.
Tentative solution:
//Dean Edwards/Matthias Miller/John Resig
function init() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// kill the timer
if (_timer) clearInterval(_timer);
window.onfocus = function() {
if(!document.AppletName.isActive())
document.AppletName.requestFocus();
};
}
/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
/* for Internet Explorer */
/*#cc_on #*/
/*#if (#_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*#end #*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
init(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = init;
Note that the key part for detecting whether the applet needs focus and requesting it if so is (this only works if mayscript is enabled):
if(!document.AppletName.isActive())
document.AppletName.requestFocus();
The rest of the code is just attaching the window on focus handling after the page is loaded (using the script JQuery.ready is based off of).
Better solutions welcome.
Related
Very new to Wicket but have very basic Java. I am not understanding how "result" is not been used as I have used it in an AjaxButton function
The quickfix says to provide a getter and setter, which I did (have removed now) but still nothing happened when I click the OK button
CalcPage.java:
public class CalcPage extends WebPage{
private int num;
private int result; // error:The value of the field CalcPage.result is not used
private Label r;
public CalcPage() {
Form<Void> f = new Form<Void>("f");
add(f);
f.add(new TextField<Integer>("num", new PropertyModel<Integer>(this, "num")));
AjaxButton ok = new AjaxButton("ok") {
#Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
result = 2 * num;
target.add(r);
}
#Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
}
};
f.add(ok);
r = new Label("r", new PropertyModel<Integer>(this, "result"));
add(r);
}
}
CalcPage.html
<html xmlns:wicket="http://wicket.apache.org">
<head>
<meta charset="utf-8" />
<title>Apache Wicket Quickstart</title>
<link href='https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:regular,bold' rel='stylesheet' type='text/css' />
<link rel="stylesheet" href="style.css" type="text/css" media="screen" title="Stylesheet" />
</head>
<body>
<form wicket:id="f">
<input type="text" wicket:id="num"/>
<input type="submit" value="OK" wicket:id="ok"/>
</form>
Result: <span wicket:id="r"></span>
</body>
</html>
Hoping (according to book Enjoying web development with Wicket) to double the input but when I click on OK and nothing happens.
Also in code I am getting a compile error with #Override, once this is removed I can compile and load webpage. Are they related??
Wicket Ajax Debug window info:
INFO: focus removed from
INFO: focus set on
INFO: focus removed from
INFO: focus set on wicketDebugLink
INFO: focus removed from wicketDebugLink
INFO: focus set on ok2
INFO: Received ajax response (69 characters)
INFO:
INFO: Response processed successfully.
INFO: refocus last focused component not needed/allowed
ETA I changed from private to public and that error is gone but clicking ok still doesn't work and new error has come:
The method onSubmit(AjaxRequestTarget, Form) from the type new AjaxButton(){} is never used locally
You need to call r.setOutputMarkupId(true) if you want to update a Component via Ajax.
1) if javac (or your IDE) says that #Override does not override anything then most probably you have a typo somewhere and you need to fix it, i.e. to properly override the method from super
2) never leave #onError() empty. As a minimum add some basic logging in it to notify you that there is a validation error. Maybe #onSubmit() is not called at all. The best would be to have a FeedbackPanel in the page and you should update it in #onError() - target.add(feedbackPanel)
3) Check the browser's Dev tools Console for JavaScript errors. I'd expect Wicket complaining that it cannot find an HTML element with id rXY (where XY is a number) because of the missing r.setOutputMarkupId(true)
Version 8 of wicket doesn't have the "form" parameter so it can be deleted:
new code
AjaxButton ok = new AjaxButton("ok") {
#Override
protected void onSubmit(AjaxRequestTarget target) {
result= 2*num;
target.add(r);
}
So I have been searching for a way to get current location in java (not using any Android APIs) and something that is quite accurate. What I have so far is running an HTML file inside of Java and what I want to do is retrieve the GPS coordinates from a google API (html file).
What I have so far:
HtmlRun.java
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class HtmlRun {
public static void main(String[] args) throws IOException {
File htmlFile = new File("findLocation.html");
Desktop.getDesktop().browse(htmlFile.toURI());
}
}
findLocation.html
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBTQzs7iZUtr7v-VbvAWhAql5LiQ9zZrFE&callback=initMap">
</script>
</body>
</html>
When I run this, it opens up my default app for html files and everything is sorted... but how could I retrieve the information I need? (GPS coordinates)
It occurs over here:
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
But I don't know how to retrieve that data back into my Java application.
This here:
public static void main(String[] args) throws IOException {
File htmlFile = new File("findLocation.html");
Desktop.getDesktop().browse(htmlFile.toURI());
}
is just opening the html doc in a web browser, after that you have no control AT ALL about what is happening with the web content, the user can even click all the buttons/ pois in the map and you will never get access to that information.
What you need is a webserver that SERVES the content of that app, you can implement REST/full services or even WebSockets to exchange the data between Browser and server
I want to add progress bar when the applet is loaded on all browsers (Google Chrome, Mozilla Firefox , Internet Explorer , Safari, Opera) . I try to make this with javascript and html body onload method. I use below code..
<html>
<head>
<title>Your Title Here</title>
</head>
<script src="/jquery.js" type="text/javascript">
</script>
<script src="/jquery.browser.js" type="text/javascript">
</script>
<script language="JavaScript" type="text/javascript">
//if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
//alert("firefox");
//}
function init() {
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isFirefox = typeof InstallTrigger !== 'undefined';
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor')>0;
var isChrome = !!window.chrome && !isOpera;
var isIE = /*#cc_on!#*/false || document.documentMode;
if(isIE == 11)
{
if(document.applets[0].visibility="visible")
{
alert("Loading On Internet Explorer");
document.all.loading.style.visibility="hidden";
}
}
if(isChrome == true)
{
//alert("Google Chrome");
if(document.applets[0].visibility="visible")
{
alert("Loading On Google Chrome");
document.all.loading.style.visibility="hidden";
//alert("Loading On Google Chrome");
//alert("internet explorer");
//alert("Loading...");
//document.writeln( "User Agent = " + navigator.userAgent );
//document.loading.visibility="hidden";
//document.all.loading.style.visibility="hidden";
}
}
if(isFirefox == true)
{
//alert("mozilla firefox");
if(document.applets[0].visibility="visible")
{
alert("Loading On Mozilla Firefox");
document.all.loading.style.visibility="hidden";
//alert("internet explorer");
//alert("Loading...");
//document.writeln( "User Agent = " + navigator.userAgent );
//document.loading.visibility="hidden";
//document.all.loading.style.visibility="hidden";
}
}
if(isSafari == true)
{
//alert("Safari");
if(document.applets[0].visibility="visible")
{
alert("Loading On Safari");
//alert("internet explorer");
//alert("Loading...");
//document.writeln( "User Agent = " + navigator.userAgent );
//document.loading.visibility="hidden";
//document.all.loading.style.visibility="hidden";
}
}
}
</script>
<style type="text/css">
#loading {
position:absolute;
left:150;
top:200;
}
#myapplet {
position:absolute;
left:10;
top:10;
visibility:hide;
}
</style>
<body onLoad="init()">
<div id="loading">
<p>Loading applet, please wait.</p>
</div>
<applet archive="app1.jar" code="app1.class" align="baseline" width="620" height="442">
<p>Requires a browser that supports Java.</p>
</applet>
</div>
</body>
</html>
Above code works true on internet explorer but not work true on firefox and chromium. Progress Bar disappear when install plugin pop up message is shown in mozilla firefox before applet fully loaded. This progress bar must disappear after applet fully loaded. How can i do this with mozilla firefox and google chromium correctly. Should i use different codes for each browsers..
"I want to add progress bar when the applet is loaded on all browsers". With using javascript and html u can't understand applet is loaded on browsers. You are dealing unnecessary things. I suggest you to read this discussion.How To Show Progress Bar When The Java Applet Load On Web Browser
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.
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.