解決SWT Button設置背景顏色不可用的問題

 

在做Eclipse 的一個項目時遇到org.eclipse.swt.widgets.Button設置背景色,不起作用。

遇到問題後在網上找了好久,終於找到一段修正代碼,不可直接使用,於是將其更改爲如下方法。

本想重寫swt的Button類,結果任務在身,遇到問題就放棄了,有能力的可以試試。

或許該方法還可以繼續優化,大家繼續啊。

 

使用方法:正常使用SWT Button,只是在設置背景設以後,記得調用下面的方法,即可,測試通過。

 

 

/***

* Just to fix button's backgroundColor,may be it is on test.

* @param button

*/

private void fixSetBackground(Button button) {

Color foreground = button.getForeground();

Color background = button.getBackground();

int x = 0;

int y = 0;

Rectangle rect = button.getBounds();

int width = rect.width;

int height = rect.height;

String text = button.getText();

if (width == 0)

width = 1;

if (height == 0)

height = 1;

button.setImage(new Image(button.getParent().getDisplay(), width,height));

Image original = button.getImage();

GC gc = new GC(original);

gc.setForeground(foreground);

gc.setBackground(background);

gc.drawRectangle(x, y, width, height);

gc.fillRectangle(x, y, width, height);

Font font = button.getFont();

FontData fontData = font.getFontData()[0];

int fontSize = fontData.getHeight();

gc.setFont(button.getFont());

int ximg = (x + width) / 2 - fontSize * text.length() / 3;

int yimg = (y + height) / 2 - fontSize * 3 / 4;

gc.drawText(text, ximg < 4 ? ximg : 4, yimg < 4 ? yimg : 4,

SWT.DRAW_TRANSPARENT | SWT.DRAW_MNEMONIC);

gc.dispose();

}

 

 

原文:https://bugs.eclipse.org/bugs/show_bug.cgi?id=23837

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章