Reputation: 9287
SWT does not support "Text over Image" in a Button. When the Image is set, hides the text. What could be the best approach to achieve this?
The best workaround i could think of was to "merge" the text with the image... does anyone know a good Java library do to this?
NOTE: I've found this custom implementation that simply draws the Text over the Image: https://github.com/jrobichaux/SquareButton/wiki. Why is this not implemented in SWT?? (anyway, i could not make this class work... and i really don't want this approach because i want the NATIVE Button look)
Upvotes: 2
Views: 2684
Reputation: 36884
Why is this not implemented in SWT?
SWT aims at looking native. To achieve this, SWT uses OS resources for the widgets. Consequently, the SWT Button
s look like the OS buttons. Buttons with text above or below images are not quite common.
I managed to achieve something that somehow works, but it's quite hacky. Maybe you can use it as a starting point:
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));
final Image image = display.getSystemImage(SWT.ICON_ERROR);
final String text = "Button";
final Button button = new Button(shell, SWT.PUSH);
GridData data = new GridData();
float fontHeight = shell.getFont().getFontData()[0].height;
data.heightHint = image.getImageData().height + (int)fontHeight + 20;
data.widthHint = 100;
button.setLayoutData(data);
button.addListener(SWT.Paint, new Listener() {
@Override
public void handleEvent(Event event) {
GC gc = event.gc;
int width = ((GridData)button.getLayoutData()).widthHint;
int height = ((GridData)button.getLayoutData()).heightHint;
Point textSize = gc.textExtent(text);
gc.drawText(text, width / 2 - textSize.x / 2, image.getImageData().height - image.getImageData().height / 2 - textSize.y, true);
gc.drawImage(image, width / 2 - image.getImageData().width / 2, height / 2 - image.getImageData().height / 2 + textSize.y / 2);
}
});
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
image.dispose();
display.dispose();
}
As you can see, I used GridData
to achieve the sizing of the button and a Listener
for SWT.Paint
to fill the button with the image and the text.
The result looks like this:
Upvotes: 5