How do you open web pages in Java? - 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();
}

Related

Open a File with Desktop Application with Applet

somehow I want to open a file form a web application with the desktop application from client side.
My boss told me to use Applet. I've been through all the internet could provide me, but still can't find how to do it.
I've build a code program from java class to open the file directly but I can't make the applet running from JSP file.
Here's my code :
public static void main(String[] a) {
try {
URI uri = new URI("your/local/file/path");
Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}
if (desktop != null)
desktop.browse(uri);
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (URISyntaxException use) {
use.printStackTrace();
}
}
If somebody ever done it before, I'll be really thankful.
Normally, Applets do not have access to the local file system due to security issues. However, there are ways to grant file system access to applets. This article describes the procedure: https://www.developer.com/java/other/article.php/3303561/Creating-a-Trusted-Applet-with-Local-File-System-Access-Rights.htm. Altough I have not tested it myself and it is rather old, the article seems promising. I hope, this helps you.

Release java applet resources when browsing to a URL via code

I have a Java applet that presents a JButton that allows users to navigate to another URL (which has a feedback form).
Problem: when I navigate to the form in Safari from the applet, typing into the form is garbled or impossible (only every 10th keystroke or so is actually entered).
Manually terminating the Java Web Plug-in for Safari fixes this immediately. I assume that I am somehow not releasing resources properly in my applet. I am aware that cleanup should be performed in the stop() method, but I'm not sure what resources I am failing to release that could cause this kind of behavior.
Here is the code that browses to the URL:
final JButton btnLaunch = new JButton("Go to survey");
final myJApplet mj = this;
btnLaunch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String url ="www.mywebform.example";
try {
getAppletContext().showDocument(new URL(url));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
finally {
SwingUtilities.getWindowAncestor(btnLaunch).dispose();
mj.stop();
}
}
My best guess is that somehow Safari is mishandling resources by passing them to some Java ActionListener. However, including:
btnLaunch.removeActionListener(this);
in a finally block does not seem to help. I have other action listeners in my applet that I know are not explicitly destroyed, but I was under the assumption that generally this wasn't a problem as they are supposed to be disposed of automatically.
EDIT: Checking through my code, it seems I only have MouseListener or ActionListeners (on JButtons). So it is even more baffling that I'm having a keyboard issue. I tried manually removing them all in the stop method of the applet (which I manually call in the finally block), but it didn't help. MouseEvents and ActionEvents shouldn't continue to run upon navigating away from the page!
EDIT 2: Further information: having the applet open a new window which then contains a link to the final survey also does not work. However, making the link open in a new window (using html's target="_blank") seems to correct the problem. So for a work around, I have the applet direct users to a splash page which thanks them and then presents a link for the final survey. This is annoyingly kludgey, and doesn't answer the original question, but for now it seems like what I will be going with.

Java GUI - Web Browser and Opening Link

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();
}
}
}

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();
}
}

Create a simple form application to edit a textfile

I think I need to restate my question ...
I want to create a SIMPLE form application that edits certain areas of one very specific text file. Though I have some web development experience, I do not want to create a browser based application. Basically I want to give a Desktop application a try and I am looking for some help to get started including suggestions for the language of choice. The application should run on Mac OS X. Besides there's no restriction: Java, Cocoa, Python, even a some interactive shell script would be ok.
If you are interested in the details, continue to read here, but not that my question is not LaTex specific...:
I have an automatically generated report file that contains LaTex Code. Now I want to build a little application that creates a form field for every section and it's header. The document contains only a few hundred lines and the should work the following:
\section{ This is were the header text should go inside the document }
\normalsize{ This is where the normal text should go}
The header / normalsize pairs occur 5-6 times within the document. All I want is a little GUI that allows user to edit between the curly braces without seeing any TeX code. I know that there's LyX and other WYSIWYG approaches to LaTeX – I do not want to reinvent the wheel. I just want to protect the auto-generated code a litte from users and make it a little more comfortable to them.
EDIT:
here's my very first try. I guess I should use PlainDocument instead of directly sending it, but I´ll figure that out, since I got plenty of help from trashgod with the editor / Text Component links. The major problem is to single out the content from \section{} and \normalsize{} stuff. Probably I will some regexp here. I need to get a new text area for every appearance.
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileReader;
import javax.swing.*;
public class basicFrame extends JFrame {
// Declare Variables
JScrollPane bildlauf = new JScrollPane();
JTextArea txtfeld = new JTextArea();
public basicFrame() {
super();
// Main window
setTitle("ReportEditor");
setBackground(Color.LIGHT_GRAY);
// components
try {
File datei = new File("report.Rnw");
FileReader in = new FileReader(datei);
txtfeld.read(in, datei);
in.close();
} catch (Exception e) {
System.out.println("Error !");
}
// setLayout(new GridLayout(2,2));
// Scroll Shizzle
bildlauf.getViewport().add(txtfeld, null);
getContentPane().add(bildlauf, BorderLayout.CENTER);
//txtfeld.setSize(500,680);
//add(txtfeld);
//this.getContentPane().add(txtfeld);
// close
addWindowListener(new WindowLauscher());
}
// event handlers...
protected static final class WindowLauscher extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
public static void main(String[] args) {
//Fesnter erzeugen und anzeigen, die main Sache halt
basicFrame hf = new basicFrame();
hf.setSize(500, 700);
hf.setLocation(100, 100);
hf.setVisible(true);
}
}
Thx in advance for any suggestions!
The TeX on Mac OS X wiki recommends jEdit, which supports plugins. LaTeXTools might be a good start.
Addendum:
I do not want to reinvent the wheel.
All I want to do is create a form application.
Although these goals are somewhat contradictory, you can always parse the file and use a suitable JTextComponent for each editable section. Here's an overview of Using Text Components; see Text Component Features if you want to create your own editor kit, as discussed in Customizing a Text Editor.
Addendum: In addition to the tutorial, you might look at this text field layout example. Also, consider a two-column JTable, which would allow you to cleanly separate your document model from your form view.
Addendum: A few notes on your code.
Class names are usually capitalized, e.g. BasicFrame.
Don't extend JFrame if you're not changing it's behavior; JPanel is a good container for other components, and it can be displayed in a JFrame.
Always buid your GUI on the EDT.
Keep you view and model separate.

Categories

Resources