hellojavaworld
hellojavaworld

Reputation: 21

how to creat a hyperlink url string in a Java MessageDialog?

a simple MessageDialog(or MessageBox,any method can open a dialog )like follows: MessageDialog.openInformation(shell, "Test", "Get help form this link www.google.com"); is there any way to make www.google.com a hyperlink? click the url and open browser.

Upvotes: 1

Views: 1981

Answers (1)

DA.
DA.

Reputation: 849

thats not possible out of the box. I created a class of my own, named MyMessageDialog to do this:

https://gist.github.com/andydunkel/8914008

Its basically all the source code from MessageDialog. Then I overwrote the createMessageArea method and added a Link instead of a label and added an event listener:

protected Control createMessageArea(Composite composite) {
    // create composite
    // create image
    Image image = getImage();
    if (image != null) {
        imageLabel = new Label(composite, SWT.NULL);
        image.setBackground(imageLabel.getBackground());
        imageLabel.setImage(image);
        //addAccessibleListeners(imageLabel, image);
        GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.BEGINNING)
                .applyTo(imageLabel);
    }
    // create message
    if (message != null) {
        linkLabel = new Link(composite, getMessageLabelStyle());
        linkLabel.setText(message);

        linkLabel.addSelectionListener(new SelectionAdapter(){
            @Override
            public void widgetSelected(SelectionEvent e) {
                   System.out.println("You have selected: "+e.text);
                   try {
                    //  Open default external browser 
                    PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser().openURL(new URL(e.text));
                  } 
                 catch (PartInitException ex) {
                    // TODO Auto-generated catch block
                     ex.printStackTrace();
                } 
                catch (MalformedURLException ex) {
                    // TODO Auto-generated catch block
                    ex.printStackTrace();
                }
            }
        });

        GridDataFactory
                .fillDefaults()
                .align(SWT.FILL, SWT.BEGINNING)
                .grab(true, false)
                .hint(
                        convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH),
                        SWT.DEFAULT).applyTo(linkLabel);
    }
    return composite;
}

The MessageDialog can be called with HTML code in it now:

MyMessageDialog.openError(parent.getShell(), "Hehe", "<a href=\"http://google.com\">Google.com</a> Test");

Not a very optimal solution, but it works:

enter image description here

Andy

Upvotes: 1

Related Questions