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;
- Is it possible to put hyperlinks in jLabels?
- If so, am I doing something wrong, or is the programme not running properly?
- If not, what is a good alternative? The reason I am not using JButtons, is that eventually I want to create a grid of an arbitrary number of hyperlinks, and I want the hyperlinks to be images, and whilst JButtons can have images on them, I don’t want the hyperlinks to look like “buttons”. I suppose I could use a non-editable JEditorPane?
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
LinkLabelthat implements this logic and then use it every time you need.