Reputation: 3086
Is there a way in Java to give a label a highlight effect?
For example, say I have a label with a picture set to it, and I want to highlight it whenever the mouse cursor enters it.
I tried to look around in google and the only tip I could find is to use label.setBackground(display.getSystemColor(SWT.COLOR_YELLOW));
but this obviously will not highlight the label, let alone a label with a picture on it.
because first of all, it is too yellow, and second, it will appear as if the color is behind the picture (well, because it is setBackground() of course).
I'm looking for a much brighter yellow color that will also be transparent, so the image will be seen.
Hope my intentions are clear enough.
Upvotes: 1
Views: 1044
Reputation: 36894
You could add a Listener
to SWT.MouseEnter
and SWT.MouseExit
and keep track of whether the mouse is hovering over the Label
and then repaint it with a custom Listener
for SWT.Paint
:
private static boolean hovering = false;
public static void main(String[] args)
{
final Display display = new Display();
Shell shell = new Shell(display);
shell.setText("StackOverflow");
shell.setLayout(new FillLayout());
final Label label = new Label(shell, SWT.NONE);
final Image image = display.getSystemImage(SWT.ICON_ERROR);
Listener mouseHover = new Listener()
{
@Override
public void handleEvent(Event e)
{
hovering = e.type == SWT.MouseEnter;
label.redraw();
}
};
label.addListener(SWT.MouseEnter, mouseHover);
label.addListener(SWT.MouseExit, mouseHover);
label.addListener(SWT.Paint, new Listener()
{
@Override
public void handleEvent(Event e)
{
int x = label.getBounds().width / 2 - image.getBounds().width / 2;
int y = label.getBounds().height / 2 - image.getBounds().height / 2;
e.gc.drawImage(image, x, y);
if(hovering)
{
e.gc.setAlpha(50);
e.gc.setBackground(display.getSystemColor(SWT.COLOR_YELLOW));
e.gc.fillRectangle(label.getBounds());
}
}
});
shell.pack();
shell.setSize(100, 100);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
Looks like this:
Upvotes: 3