Transparent Background in Java SWT Label
Is there anyway in Java SWT that I can place a label on top of another label and then have the label on top to have a transparent background?
I am doing this in a class that extends Composite as I want to create a custom SWT "fancy button" out of 2 labels开发者_Python百科. So the label below will be the lable that consist of only an image while the one on top will be the label with the text of the "fancy button". But the label on top has to have a transparent background so as to not cover the image below it.
Currently, the label on top is covering the label below.
Any idea how I could do this?
Thanks!
Instead you could try doing the following to get the same result.
- Create a label
- Assign an image to the label using a shell
- Then use "setText()" to write something on the label.
The Text will appear above the image. You will be able to see the image.
( Showing only relavent code ) Example of Label with text/image.
Image image = new Image(display, "c:\\picture.jpeg");
Shell shell = new Shell(SWT.NO_TRIM);
shell.setBounds(10,10,200,200);
shell.setBackgroundImage(image);
shell.setBackgroundMode(SWT.INHERIT_DEFAULT);
Label label = new Label(shell, SWT.NONE);
label.setText("LAbel text here. ");
Since you want to make buttons. You can use the same logic, using the "Button" api as well. You can create a button with an image and then set any text above it.
( Showing only relavent code ) Example of Button
Button button = new Button(shell, SWT.PUSH);
button.setImage(image);
button.setText("Click Me");
I hope this is what you are trying to do.
instead of doing
drawString("text", x, y)
do
drawString("text", x, y, true)
it will make the background transparent, as per the documentation
Writing a text (as label) without background seems to be simple possible only in a Canvas using the GC class for the paint routine. I have written an inheritance of Canvas for that:
public class SwtTransparentLabel extends Canvas {
String text = "";
Font font = null;
public SwtTransparentLabel(Composite parent, int style) {
super(parent, style | SWT.TRANSPARENT);
addPaintListener(paintListener);
}
public void setText (String string) {
text = string;
}
public void setFont (Font font) {
this.font = font;
}
/**The listener for paint events. It is called whenever the window is shown newly. It does the work for graphic output. */
protected PaintListener paintListener = new PaintListener() {
@Override public void paintControl(PaintEvent e) {
GC gc = e.gc;
if(font !=null){ gc.setFont(font); }
//no: gc.setAlpha(100); //... experience, not necessary
gc.drawString(text, 0, 0, true);
}
};
}
That works similar as org.eclipse.swt.widgets.Label.
I am yet trying to improve the solution (setAlignment is missing). You may visit results on www.vishia.org/Java
精彩评论