Rahul Tripathi
Rahul Tripathi

Reputation: 555

How to remove border of SWT Button so that it seems like a Label

I have created a button on which Image is Set in SWT. I want to remove border of button. So it looks like a label. Please help anyone.

Below Code Snippet:

breakNodeButton = new Button(this, SWT.TRANSPARENT);
breakNodeButton.setBackground(new Color(getDisplay(), 204, 204, 204));
Image breakNodeLabelImg = ...
breakNodeButton.setImage(breakNodeLabelImg);

Upvotes: 2

Views: 4829

Answers (2)

ZhekaKozlov
ZhekaKozlov

Reputation: 39536

You can use an SWT.FLAT ToolBar with a single ToolItem:

ToolBar toolBar = new ToolBar(parent, SWT.FLAT);
ToolItem item = new ToolItem(toolBar, SWT.PUSH);
item.setText("Button text"); // Remove if you don't need text
item.setImage(display.getSystemImage(SWT.ICON_INFORMATION)); // Remove if you don't need image

That's it!

Upvotes: 4

Rüdiger Herrmann
Rüdiger Herrmann

Reputation: 20985

As Greg suggested, you can use a PaintListener to override the appearance of the button.

For example:

Button button = new Button( shell, SWT.PUSH );
button.addPaintListener( new PaintListener() {
  @Override
  public void paintControl( PaintEvent event ) {
    event.gc.setBackground( event.display.getSystemColor( SWT.COLOR_GREEN ) );
    event.gc.fillRectangle( event.x, event.y, event.width, event.height );
    Image image = event.display.getSystemImage( SWT.ICON_QUESTION );
    event.gc.drawImage( image, 0, 0 );
  }
} );

The paint code will draw the question mark image in the top-left corner on top of a green background.

Note that the computeSize() method of the button still consults the (empty) text and image to compute the preferred size of the button.

As this probably isn't the size you want, you should set the buttons image to the one you are using in the paint code or advise the layout to use a pre-computed size, e.g. by setting suitable GridData or RowData

Alternatively you can use a Label and add a MouseListener to emulate the selection listener of a Button. However, a Label, by default, cannot gain keyboard focus through tab traversal and thus might not serve as a full replacement for a Button.

Upvotes: 5

Related Questions