For the "About" dialog of my application,
I have a JLabel which I have defined using html tag as follows:
JLabel myEmail = new JLabel(
"<html><br><font size=2><a href=mailto:abc.pqr#xyz.com>abc.pqr#xyz.com</a>" +
"</font></html>");`
I want that on clicking this JLabel, the default email client (say Outlook) gets opened with the To field populated as abc.pqr#xyz.com and subject as a predefined text (say, Hi!).
How to do that?
Here is a snippet on how you could do this:
String address = "abc.pqr#xyz.com"; // global
JLabel label = new JLabel("<html><br><font size=2><a href=#>" + address + "</a></font></html>");
label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
Desktop.getDesktop().mail(new URI("mailto:" + address + "?subject=Hello"));
} catch (URISyntaxException | IOException ex) {
// ...
}
}
});
For demonstration purposes, the address variable is global here but you should use a concrete MouseAdapter subclass to pass in the associated email address. Best to steer clear of attempting to parse the HTML.
Unfortunately, HTML links within a JLabel are not "clickable" by default. Please, see this topic: How to add hyperlink in JLabel. It contains everything you may need to know about this topic.
Or if you do not mind using an extra library, you can consider using the JXHyperLink from the SwingX project
Related
Okay, I have this program I am writing and would love some oversight please.
This program of sorts, uses a JList and JListSelectionListener to output a number of images onto, 1/2 vertically-split JPanes. Of these JPanes, as mentioned beforehand; one displays the images and in the bottom JPanel, a JEditorPane reads text. For the JEditorPane, I have an HTML doc. styled and being read from. This in theory, is my description of each image. Except, I cannot redirect the JEditorPane as too, read from aforementioned HTML files whose URLs or paths are accessed via a String Array[].
Main Points/Questions (tldr;)
How do I have this JEditorPane read from a different HTML file each time a new image is selected from the JList?
Should I be using a JTextPane or something else instead? Only, too my knowledge, styling might be in-or-out of the question. So, what am I doing wrong or differently and should be?
Code
private String[] fileName = { "htmlDoc1", "htmlDoc2", "htmlDoc3", "htmlDoc4" };
protected JScrollPane createEditorList() {
JEditorPane editorPane = createEditorPane(fileName[list.getSelectedIndex()]);
JScrollPane editorScrollPane = new JScrollPane(editorPane);
editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
editorScrollPane.setPreferredSize(new Dimension(250, 145));
editorScrollPane.setMinimumSize(new Dimension(10, 10));
return editorScrollPane;
}
private JEditorPane createEditorPane(String file) {
JEditorPane editorPane = new JEditorPane();
editorPane.setEditable(false);
java.net.URL helpURL = Bobbleheads.class.getResource("/images/bobbleheads/" + file + ".html");
if (helpURL != null) {
try {
editorPane.setPage(helpURL);
} catch (IOException e) {
System.err.println("Attempted to read a bad URL: " + helpURL);
}
} else {
System.err.println("Couldn't find file: " + fileName);
}
return editorPane;
}
public void valueChanged(ListSelectionEvent e) {
JList<?> list = (JList<?>) e.getSource();
updateLabel(imageNames[list.getSelectedIndex()]);
createEditorPane(fileName[list.getSelectedIndex()]);
}
Thank you too everyone, contributing any way possible!
Crunching in a few methods solved this Java singleton. With the outstanding help from AJNeufeld, Andrew Thompson & Stack Overflow of course!
Heres how:
Original methods for change:
protected JScrollPane createEditorList() {
private JEditorPane createEditorPane(String file) {
and the public void valueChanged(ListSelectionEvent e) { method were replaced with and replicated into these newer code blocks.
Code:
New, rescripted methods:
protected JScrollPane makeAEditorPane() {
JScrollPane editorScrollPane = new JScrollPane(makeAEditorList());
editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
editorScrollPane.setPreferredSize(new Dimension(250, 145));
editorScrollPane.setMinimumSize(new Dimension(10, 10));
return editorScrollPane;
}
protected JEditorPane makeAEditorList() {
editorPane = new JEditorPane();
editorPane.setEditable(false);
return editorPane;
}
private void feedEditor(String name) {
URL helpURL = Bobbleheads.class.getResource("/images/bobbleheads/" + name + ".html");
if (helpURL != null) {
try {
editorPane.setPage(helpURL);
} catch (IOException e) {
System.err.println("Attempted to read a bad URL: " + helpURL);
}
} else {
System.err.println("Couldn't find file: TextSampleDemoHelp.html");
}
}
public void valueChanged(ListSelectionEvent e) {
JList<?> list = (JList<?>) e.getSource();
updateLabel(imageNames[list.getSelectedIndex()]);
feedEditor(htmlDocs[list.getSelectedIndex()]);
}
Understanding what has changed:
Of the two original methods, three new methods were deduced. createEditorList() & createEditorPane(String file) became makeAEditorPane(), makeAEditorList() & feedEditor(String name). Simply by splitting up the components editorScrollPane & editorPane during formation thanks to, #AJNeufeld.
Very next, the new method feedEditor(String name), did exactly what its name implies. Feeds the initiation of our URL here, allocating a HTML file for the editorPane to derive and load thanks to, #Andrew Thompson.
Accessing the method: feedEditor(htmlDocs[list.getSelectedIndex()]);, inside of the valueChanged(ListSelectionEvent e) method, paved the way for an event to occur. An event between a JList known as list.
Wrapping things up...
Now, the event brought a change in the URL discussed on earlier. Here, it is relatively simply put; allowing for switching between JList selections, activates HTML files located as project resources.
That's it! Thank you everybody and stay safe.
I'm trying to implement a history-button in my Browser class (created in eclipse), and I want the links in the button to be clickable. Here is my code that gets initiated when the user presses the button History:
private void showMessage() {
try {
String message = new String();
message = history.toString();
JOptionPane.showMessageDialog(null, message);
} catch (NullPointerException e) {
System.out.println("Something is wrong with your historylist!");
}
}
In the code above, history is a list with all the webpages that has been previously visited.
I have tried using the method presented here:
clickable links in JOptionPane, and I got it to work. The problem is, this solution only lets me predefine URL:s, but I want my list history to be displayed, and the URLs in it to be clickable.
For example, if I have visited https://www.google.com and https://www.engadget.com, the list will look like this: history = [www.google.com, www.engadget.com], and both links should be separately clickable.
This is the function that should be called when someone presses the history-button. It uses a JEditorPane with a HyperlinkListener. The string html in the code below adds the needed html-coding so that the HyperlinkListener can read and visit the webpages.
public void historyAction() {
String html = new String();
for (String link : history) {
html = html + "" + link + "\n";
}
html = "<html><body" + html + "</body></html>";
JEditorPane ep = new JEditorPane("text/html", html);
ep.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
loadURL(e.getURL().toString());
}
}
});
ep.setEditable(false);
JOptionPane.showMessageDialog(null, ep);
}
I returned my JEditorPane in my program to a website, like google example,
but it doesn't show correctly the page, well without its css style.
uh,
check my code :
JEditorPane editorPane = new JEditorPane() {
public boolean getScrollableTracksViewportWidth() {
return true;
}};
editorPane.setEditable(false);
HTMLEditorKit kit = new HTMLEditorKit();
Document doc = kit.createDefaultDocument();
editorPane.setDocument(doc);
editorPane.setEditorKit(kit);
try {
editorPane.setContentType("text/html");
editorPane.setPage("http://www.google.fr/");
}catch (IOException e) {
editorPane.setContentType("text/html");
editorPane.setText("<html>We can't load this page</html>"
+ e.getMessage() + " ");
}
editorPane.setBounds(295, 265, 491, 474);
editorPane.setBorder(new LineBorder(new Color(0, 0, 0)));
pan.add(editorPane);
I just want to show a website in a java component to show news and others information,
can anyone help me please?
A JEditorPane only supports basic HTML.
For full support you can use the default browser of your system. Check out the section from the Swing tutorial on How to Integrate with the Desktop Class for a working example that uses the "BROWSE" functionality.
I am just a beginner and i wanted to create a web browser in java using swing. now here are the three things that i m not able to do:
Dont know how to load a web page in a frame. here is my code for that:
AddressField.getText();
try {
URI uri=new URI(AddressField.getText());
URL url=uri.toURL();
InputStream in=url.openStream();
} catch (URISyntaxException ex) {
Logger.getLogger(MyBrowser.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(MyBrowser.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MyBrowser.class.getName()).log(Level.SEVERE, null, ex);
}
I want to put a backward button to get back to previous page. I tried to do that but i doesnt worked well. i need a good code to get back button in function. here is the code for its action listener:
ActionListener ab = new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
int i= store.size();
loadURL(store.get(i-2).toString());//store is object of ArrayList
}
};
I also want to put an option to open a new tab and also show record of history of pages visited.
hoping for positive responses. every help will be appreciated. thank you
a) From this example it looks like you can just get the webEngine from the WebView instance and load the URL.
final WebView browser = new WebView();
final WebEngine webEngine = browser.getEngine();
// that should do it...
webEngine.load(url.toExternalForm());
b) There seems to be history support built-in.
You'll just need to navigate between items...
c) As stated previously, Web History support seems to be built-in. For tabs, you'll likely need to have a TabPane (each tab with its one WebView component).
I have a Java Applet that interacts with the Java Plugin to show a document (just a URL) in a named browser window:
public class TestApplet extends Applet {
#Override
public void init() {
super.init();
final JButton showButton = new JButton("Show Google!");
showButton.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
getAppletContext().showDocument(new URL("http://google.com"), "Some Window Title");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
}
});
add(showButton);
}
}
This has worked historically but starting with Java 7 and Java 6u27, the window fails to open in Internet Explorer (tested in IE 8). If I use _blank as the window title (target) instead of Google, the window opens correctly (albeit in a new window each time).
I've tracked down this bug that was fixed for 6u27:
Vista/IE7 further showDocument focus issue with named targeted windows
Has anybody else experienced the same behaviour? Have you found a workaround (other than using "_blank")?
Edit
Updated the example. I wasn't actually using "Google" as the target, I was using "Some Window Title" (sorry!). It seems like this problem is unique to targets with spaces in the name.
It seems like this problem is unique to targets with spaces in the name.
Two possible solutions:
Replace the " " with "%20"
Don't use a space in the name of the target! (Though I thought that would be a 'no brainer'.)
Try this code, it should work.
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(info));