Reputation: 4060
This is the code I have in a file called Test2.java in a package called test2 in a project called Test2;
package test2;
import javax.swing.JFrame;
public class Test2 {
public static void main(String[] args) {
JFrame mainWindow = new HtmlWindow("<html>"
+ "<a href=\"http://stackoverflow.com\">"
+ "blah</a></html>");
mainWindow.setVisible(true);
}
}
In the same package I have this code in a file called HtmlWindow.java ;
package test2;
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JLabel;
class HtmlWindow extends JFrame {
public HtmlWindow(String refreshGrid) {
super("blah");
setSize(300, 100);
Container content = getContentPane();
String labelText = refreshGrid;
JLabel coloredLabel = new JLabel (labelText, JLabel.CENTER);
content.add(coloredLabel, BorderLayout.NORTH);
}
}
When I run the project, I get a window with the word "blah" in the expected location, blue and underlined, but the cursor does not change when I hover over the word, nor does anything happen when I click on it.
My questions are as follows;
Upvotes: 5
Views: 1590
Reputation: 52185
It does not seem that just by doing a hyper link you will get your usual web browser behaviour. According to examples on line, what is usually done is to implement an ActionListener
on the JLabel
and call Desktop.getDesktop().browse(new URI("..."));
.
The problem with this call is that it does not seem to work with all operating systems. What you could do would be to see if you can open the link in a browser from command line, if you can do this, you should be able to do what you need by using the exec
method from the Process
class. This will however, most likely be platform dependant.
That being said, it is of my opinion that labels should be used to depict text (even though I think that upon seeing a link, the user sort of knows what will happen, so I think that in this case, we can call it as an exception). If you want to have a component which triggers and action you could use a JButton
instead.
Upvotes: 3
Reputation: 115338
Swing is not a fully functioned browser. It supports simple HTML including links but do not change the cursor style automatically. As far as I know you have to do it programmatically, i.e. add mouse listener to your label and change the cursor style when your mouse is over your label. Obviously you can write your own class LinkLabel
that implements this logic and then use it every time you need.
Upvotes: 4