Is there any way to make labels selectable in SWT?
Asked Answered
F

1

7

Is there any way to make labels selectable in SWT? or are there any other widgets in SWT that are selectable and can be used as labels? I am building a calendar.

Forwhy answered 5/8, 2014 at 8:28 Comment(5)
What do you mean by "selectable"? You can add a Listener for MouseDown or MouseUp to the Label.Ceceliacecil
Yes exactly I want to add listener to label. How can I do that?Forwhy
So do you want to actually select the text (to copy it somewhere) or do you want to check for click events?Ceceliacecil
I want to check for click events.Forwhy
If you want to check for click events, then why did you accept an answer suggesting to use a StyledText?Ceceliacecil
G
8

I think you want to select the Label text to clipboard.

You can use Text Widget as Label but caret will appear when user clicks on it. If you don't want caret then use StyledText and set caret to null.

Example:

package testplugin;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class SWTHelloWorld {

public static void main (String [] args) {
    Display display = new Display ();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout());
    Label labelWidget = new Label(shell, SWT.NONE);
    labelWidget.setText("Hello");

    Text textWidget = new Text(shell, SWT.NONE);
    textWidget.setText("Hello");

    //Set background color same as its container
    textWidget.setBackground(shell.getBackground());
    //Make editable false
    textWidget.setEditable(false);

    StyledText styledTextWidget = new StyledText(shell, SWT.NONE);
    styledTextWidget.setText("Hello");  
    styledTextWidget.setBackground(shell.getBackground());
    styledTextWidget.setEditable(false);
    //Set caret null this will hide caret
    styledTextWidget.setCaret(null);

    shell.pack();
    shell.open ();
    shell.setSize(200, 300);
    while (!shell.isDisposed ()) {
        if (!display.readAndDispatch ()) display.sleep ();
    }
    display.dispose ();
}
}

You can refer these links to listen mouse,keyboard,focus etc etc listeners on various widgets.

Gounod answered 5/8, 2014 at 9:30 Comment(4)
I think even a simple Text would be sufficient here.Ceceliacecil
How we can hide caret on Text widget?Gounod
You can't. But that wasn't a requirement.Ceceliacecil
I had to use StyledText, I tried using simple Text but couldn't get rid of the border which made it look more like a button than a label. And the caret was an eye-sore too. But StyledText works nicely.Stipitate

© 2022 - 2024 — McMap. All rights reserved.