Java GUI - Web Browser and Opening Link - java

I am creating a game and I made a Launcher. I have seen on other games made out of Java (Like MineCraft) have a webpage on the launcher. I was woundering how to put a webpage on a Java Swing GUI panel. I would also like to know how to open their browser up to a link with a button.
Thanks,
Blockquote

To open a url in the system's web browser you can use java.awt.Desktop.browse(URI). This allows you to keep your Java code platform independent, and even allows you to check to see if an operation is supported before trying to use it.
To load a web page within Java, I've had some success using the JavaFX WebView.

import java.awt.Desktop;
import java.net.URI;
class URLBrowsing
{
public static void main(String args[])
{
try
{
// Create Desktop object
Desktop d=Desktop.getDesktop();
// Browse a URL, for example www.facebook.com
d.browse(new URI("http://www.facebook.com"));
// This open facebook.com in your default browser.
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}

Related

How to implement printing in chrome pacakaged app created from GWT Application.?

I have integrated the GWT application with Chrome packaged app with help of DirectLinkerinstaller like the code below:
public class CSPCompatibleLinker extends DirectInstallLinker {
#Override
protected String getJsInstallLocation(LinkerContext context) {
return "com/google/gwt/core/ext/linker/impl/installLocationMainWindow.js";
}
}
But now I want to call print function from Chrome packaged app. When I call window.print() it allows me to print current window, but I need to open a new separate window and print that.
Could you anyone please help me in this?
I can't answer anything about GWT or DirectLinkerinstaller, but here's an answer about Chrome Apps, assuming that's what you're asking about:
You use the chrome.app.window.create API to create a window. Then, you can call the print method for that window.
In my apps, I seldom want to print what's in a window, but rather something I've generated specifically for printing. For that, I create a PDF with jsPDF (Google it), which works well. Then I display the PDF in a window, and let the user print the PDF (or save it).

Opening a web browser and controlling it as a Virtual User

I am trying to open a browser and then simulate a user in Java. Previously I would have accomplished this with simple Applescript, with something like this
tell application "Safari"
activate
open location "http://google.co.uk"
delay 1
do JavaScript "
document.getElementById('gbqfq').value ='software is hard';
" in document 1
end tell
So it opens Safari, then types into Google's query box.
In Java, so far I have
import javax.script.*;
public class VirtualUser {
public static void main(String[] args) throws Exception {
Runtime.getRuntime().exec("open /Applications/Safari.app");
Thread.sleep(1000);
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
engine.eval("print('Hello World')");
}
}
Which opens Safari (Google homepage), and prints Hello World in the IDE (verification that JS is working within Java?)
In the Java example, how can I then further enter text into Google's search bar? And is utilising JavaScript within Java the best/only solution for this?
I've had some luck with Selenium in the past. It automates a browser and you can run commands exactly like you are describing. Definitely go check it out.

Java SE: Open Web Page and Click a Button

I have a Java 7 program (using WebStart technology, for Windows 7/8 computers only).
I need to add a function so that my program clicks a button on a page with known URL (https).
Some people suggest WebKit SWT, but I went to their site and they say that the project was discontinued. (http://www.genuitec.com/about/labs.html)
Other people say that JxBrowser is the only option but it looks like it's over $1,300 which is crazy. (http://www.teamdev.com/jxbrowser/onlinedemo/)
I'm looking for something simple, free, lightweight, and able to open HTTPS link, parse HTML, access a button through DOM and click it. Perhaps some JavaScript too, in case there are JS handlers.
Thanks for your help.
You may be looking for HtmlUnit -- a "GUI-Less browser for Java programs".
Here's a sample code that opens google.com, searches for "htmlunit" using the form and prints the number of results.
import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.html.*;
public class HtmlUnitFormExample {
public static void main(String[] args) throws Exception {
WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage("http://www.google.com");
HtmlInput searchBox = page.getElementByName("q");
searchBox.setValueAttribute("htmlunit");
HtmlSubmitInput googleSearchSubmitButton =
page.getElementByName("btnG"); // sometimes it's "btnK"
page=googleSearchSubmitButton.click();
HtmlDivision resultStatsDiv =
page.getFirstByXPath("//div[#id='resultStats']");
System.out.println(resultStatsDiv.asText()); // About 309,000 results
webClient.closeAllWindows();
}
}
Other options are:
Selenium: Will open a browser like Firefox and operate it.
Watij: Also will open a browser, but in its own window.
Jsoup: Good parser. No JavaScript, though.
Your question is kind of difficult to understand what you want. If you have a webstart app and want to open a link in the browser, you can use the java.awt.Desktop.getDesktop().browse(URI) method.
public void openLinkInBrowser(ActionEvent event){
try {
URI uri = new URI(WEB_ADDRESS);
java.awt.Desktop.getDesktop().browse(uri);
} catch (URISyntaxException | IOException e) {
//System.out.println("THROW::: make sure we handle browser error");
e.printStackTrace();
}
}

How to use HTML and CSS as a Java application GUI?

I want to design new Git client with a clean GUI.
Is it possible to use the power of HTML, CSS and JavaScript in a java application?
I would like to use Java + JGit for models, Java for controllers and HTML + CSS + JavaScript for views.
I don't want a client-server model. I would like to integrate Java and HTML nicely. A DOM event would fire events directly to a Java controller. This way it would be possible to create rich offline application.
You can embed web browser component into your Java Swing/JavaFX Desktop application that displays GUI built with HTML5+CSS+JavaScript. You can see an article that describes how to do this at https://jxbrowser-support.teamdev.com/docs/tutorials/cross-desktop-apps.html
One of the Java Swing/JavaFX libraries that allows embedding Chromium into Java applications is JxBrowser. Using JxBrowser API you can load any web page and work with its DOM and JavaScript. You can even call Java methods from JavaScript code and vice versa. For example:
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.JSFunctionCallback;
import com.teamdev.jxbrowser.chromium.JSObject;
import com.teamdev.jxbrowser.chromium.JSValue;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
public class JavaScriptJavaSample {
public static void main(String[] args) {
Browser browser = new Browser();
browser.addLoadListener(new LoadAdapter() {
#Override
public void onFinishLoadingFrame(FinishLoadingEvent event) {
if (event.isMainFrame()) {
Browser browser = event.getBrowser();
JSObject window = (JSObject)
browser.executeJavaScriptAndReturnValue("window");
window.setProperty("MyFunction", new JSFunctionCallback() {
#Override
public Object invoke(Object... args) {
for (Object arg : args) {
System.out.println("arg = " + arg);
}
return "Hello!";
}
});
JSValue returnValue = browser.executeJavaScriptAndReturnValue(
"MyFunction('Hello JxBrowser!', 1, 2, 3, true);");
System.out.println("return value = " + returnValue);
}
}
});
browser.loadURL("about:blank");
}
}
It's not really feasible. Rich clients in Java are done using Swing or SWT.
If you want to use HTML/CSS for your user interface, you need to use the server/client model. It can be as simple as creating a local server and launching a browser that connects to it, but it would still be that model.
If you absolutely need to have HTML/CSS as your UI framework and can't go to a server/client model, your best bet is probably looking at something like Google Native Client, but that uses C/C++ bindings on the backend. I haven't used Native Client so I can't personally give much more information on that front.
Edit to add:
One option is to embed a native browser into your Swing app using something like: http://djproject.sourceforge.net/ns/
There are some pure Java HTML renderers, however, they most likely won't be fully HTML5/CSS3 compliant, let alone possibly have Javascript bugs as well.
See here for some of those options: Pure Java HTML viewer/renderer for use in a Scrollable pane
Like #Reverand Gonzo says, you will need some form of server/client. But you could easily embed a Jetty server into a Java app and then use GWT for your client code.
You can bring in the power of HTML,CSS,JavaScript into your Swing app using JFXPanel to embed JavaFX WebView. Have a look at the SimpleSwingBrowser demo in this link:https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/swing-fx-interoperability.htm
WebView allows to call JavaScript functions from Java and vice versa. It is also a nice way to enhance your legacy Java app with web technologies.
JavaFX 2.2 brought this functionality to providing a user interface component (GUI) that has web view and full browsing functionality.
For more details, see Adding HTML Content to JavaFX Applications.
Use Angular.js with HTML and rest of the things as same in Java, just use classes for business logic, no need to write code for awt/swing. Angular with spring boot are rapid development in Java for webapp with less code in Java without swing use to create best webapp .

How do you open web pages in Java?

Is there a simple way to open a web page within a GUI's JPanel?
If not, how do you open a web page with the computer's default web browser?
I am hoping for something that I can do with under 20 lines of code, and at most would need to create one class. No reason for 20 though, just hoping for little code...
I am planning to open a guide to go with a game. The guide is online and has multiple pages, but the pages link to each other, so I am hoping I only have to call one URL with my code.
Opening a web page with the default web browser is easy:
java.awt.Desktop.getDesktop().browse(theURI);
Embedding a browser is not so easy. JEditorPane has some HTML ability (if I remember my limited Swing-knowledge correctly), but it's very limited and not suiteable for a general-purpose browser.
There are two standard ways that I know of:
The standard JEditorPane component
Desktop.getDesktop().browse(URI) to open the user's default browser (Java 6 or later)
Soon, there will also be a third:
The JWebPane component, which apparently has not yet been released
JEditorPane is very bare-bones; it doesn't handle CSS or JavaScript, and you even have to handle hyperlinks yourself. But you can embed it into your application more seamlessly than launching FireFox would be.
Here's a sample of how to use hyperlinks (assuming your documents don't use frames):
// ... initialize myEditorPane
myEditorPane.setEditable(false); // to allow it to generate HyperlinkEvents
myEditorPane.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ENTERED) {
myEditorPane.setToolTipText(e.getDescription());
} else if (e.getEventType() == HyperlinkEvent.EventType.EXITED) {
myEditorPane.setToolTipText(null);
} else if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try {
myEditorPane.setPage(e.getURL());
} catch (IOException ex) {
// handle error
ex.printStackTrace();
}
}
}
});
If you're developing an applet, you can use AppletContext.showDocument. That would be a one-liner:
getAppletContext().showDocument("http://example.com", "_blank");
If you're developing a desktop application, you might try Bare Bones Browser Launch.
haven't tried it at all, but the cobra HTML parser and viewer from the lobo browser, a browser writen in pure java, may be what you're after. They provide sample code to set up an online html viewer:
import javax.swing.*;
import org.lobobrowser.html.gui.*;
import org.lobobrowser.html.test.*;
public class BareMinimumTest {
public static void main(String[] args) throws Exception {
JFrame window = new JFrame();
HtmlPanel panel = new HtmlPanel();
window.getContentPane().add(panel);
window.setSize(600, 400);
window.setVisible(true);
new SimpleHtmlRendererContext(panel, new SimpleUserAgentContext())
.navigate("http://lobobrowser.org/browser/home.jsp");
}
}
I don't know if such a built-in exists, but I would use the Runtime class's exec with iexplore.exe or firefox.exe as an argument.
Please try below code :
import java.awt.Desktop;
import java.net.URI;
import java.net.URISyntaxExaception;
//below is the code
//whatvever the url is it has to have https://
Desktop d = Desktop.getDesktop();
try {
d.browse(new URI("http://google.com"));
} catch (IOException | URISyntaxException e2) {
e2.printStackTrace();
}

Categories

Resources