I have a WebView, which loads a local html file that I have saved within my project. I use the following to load the file:
InputStream is = Browser.class.getResourceAsStream(location);
String str = "";
int i;
while((i = is.read()) != -1){
str += (char)i;
}
str = str.replace("{placeholder_1}", value1);
str = str.replace("{placeholder_2}", value2);
webEngine.loadContent(str);
In the HTML I have a link to a css file. The HTML file and the css file are in the same directory, but the css file isn't loading when the page loads in the WebView. Here is how I am calling the css file from the HTML:
<link rel="stylesheet" href="main.css" />
Why is the file not loading? According to others, this is how they are doing it and it is working. Why is it not working for me, what am I doing wrong?
Here is the directory layout:
Putting the css file in the same directory as the html file, will work if
webView.getEngine().load(location);
is used. However it will not work for loadContent(). You need to explicitly define the css file location as:
(pseudo-code)
str = str.replace("href='main.css'",
"href='" + getClass().getResource("main.css") + "'");
The following thing is working for me
Project Structure
Application
|
src
|
package
|
WebViewLoadLocalFile.java
test.html
test.css
WebViewLoadLocalFile
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class WebViewLoadLocalFile extends Application {
#Override
public void start(Stage stage) throws Exception {
BorderPane borderPane = new BorderPane();
WebView webView = new WebView();
String url = getClass().getResource("test.html").toExternalForm();
webView.getEngine().load(url);
borderPane.setCenter(webView);
final Scene scene = new Scene(borderPane);
stage.setScene(scene);
stage.setHeight(300);
stage.setWidth(250);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
test.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Insert title here</title>
<link rel="stylesheet" href="test.css" />
</head>
<body>
Test HTML
</body>
</html>
test.css
body
{
background-color:#d0e4fe;
}
Related
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?
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");
I have a Webproject with JavaEE (Tomcat, Jsp, Servlets)
I want to Show a SWF in my Jsp Page (game.jsp). For doing this i Need a Servlet, which is this:
package src;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.SystemEnviroement;
/**
* Servlet implementation class ImageServlet
*/
#WebServlet("/ImageServlet")
public class ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ImageServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ServletContext sc = getServletContext();
String imageName = request.getParameter("imageName");
SystemEnviroement env = new SystemEnviroement();
String filename = env.gameFolder + "/" + imageName;
// Get the MIME type of the image
String mimeType = sc.getMimeType(filename);
if (mimeType == null) {
// sc.log("Could not get MIME type of " + filename);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Set content type
response.setContentType(mimeType);
// Set content size
File file = new File(filename);
response.setContentLength((int) file.length());
// Open the file and output streams
FileInputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
in.close();
out.close();
}
}
My game.jsp is this:
<%# page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%# page import="util.*"%>
<%# page import="constants.*"%>
<%# page import="java.io.IOException"%>
<!DOCTYPE html>
<html >
<head>
<jsp:include page='header.jsp'/>
<%
String gamename = (String) request.getAttribute("javax.servlet.forward.request_uri");
int index_name = gamename.lastIndexOf("/");
gamename = gamename.substring(index_name+1,gamename.length());
%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body style="background-color:#630592;
background-repeat:no-repeat;"
>
<div class="body">
<%
try {
//SystemEnviroment wird im Konstruktor gesetzt
SystemEnviroement en = new SystemEnviroement();
String datei = en.imageViewPath + gamename +".swf";
%>
<div class=gameswf>
<a> <embed src='<%=datei %>' > </embed> </a>
</div>
<%
}catch(IOException e){
e.printStackTrace();
}
%>
</div>
</body>
</html>
So i have debugged my Project, all thinks Looks well. But after calling the Servlet, the game.jsp doesn't Show the SWF File.
The htmltext(sourcecode) also Looks well, but the game.jsp doesn't Show the SWF File:
<div class=gameswf>
<a> <embed src='http://localhost:8080/Game/imageView?imageName=3-pandas.swf'> </embed> </a>
</div>
If i call this URL in my running web Project "http://localhost:8080/Game/imageView?imageName=3-pandas.swf", i can sell the SWF File and all is fine.
Do you have any idea why the jsp page doesn't Show my SWF File. If i go to the Internet explorer add ons, i can also see that Shockwave Flash Object is loading.
Thanks for helping !
This is the Image from ie 11 network monitoring feature from developer Tools:
I suggest you to create an html file (with html extension) and write the code you expect from the jsp to generate.
Once you make the swf work in html file, it will be a piece of cake to develop the proper jsp code in order to generate that html file.
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.
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.