Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1563
  • Last Modified:

How to put a hyperlink to SWT Label Text in Java

Hi,
How can I add a hyperlink to JAVA SWT  Label text.

When I click on this text in the label, I want the defaul browser to navigate to this site.


This is the code I haver and I want the "Help" to be link to a website:

        GridData gridDataBanner2 = new GridData(GridData.HORIZONTAL_ALIGN_END);
        CLabel banner2 = new CLabel(shell, SWT.CENTER);
        Color MtGreen = new Color (shell.getDisplay(), 240,240,240);
        banner2.setBackground(MtGreen); 
        
        FontData fontData2 = banner2.getFont().getFontData()[0];
        Font fontBanner2 = new Font(shell.getDisplay(), new FontData(fontData2.getName(),8, SWT.NORMAL));
        banner2.setFont(fontBanner2);
        banner2.setForeground(shell.getDisplay().getSystemColor(SWT.COLOR_WHITE));
        

        banner2.setText("Help");
        banner2.setForeground(shell.getDisplay().getSystemColor(SWT.COLOR_BLUE));
        banner2.setLayoutData(gridDataBanner2);

Open in new window



Thanks,
0
Tolgar
Asked:
Tolgar
1 Solution
 
TolgarAuthor Commented:
Any ideas?
0
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
I don't think SWT has anything "in-built" to do this, but you should be able to fake it. It looks like you have already started on that, setting the color of the text used. You might also want to make it underlined.

Then you need to make it act like a link. For that it probably should change cursor when hover over it, so...
banner2.setCursor(display.getSystemCursor(SWT.CURSOR_HAND));

Open in new window


And make it DO something when you click it...
banner2.addMouseListener(new MouseAdapter() {
    public void mouseUp(MouseEvent event) {
        if (event.button == 1) {   // Left button pressed & released
            Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
            if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
                try {
                    desktop.browse("http://address.of.your.website.here.com");
                } catch (Exception e) {
                    // Handle any exceptions appropriately
                }
            }
        }
    }
}

Open in new window

(Note the above should work for Windows, but it's probably OS dependant and I don't have any others to test on, so I will leave that up to you to try it on others if you need.)

(Also note, that Desktop is not a SWT class, you would need to   import java.awt.Desktop;    at the top of your .java file to use it)
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now