您的位置:首页 > 编程语言 > Java开发

解决SWT Button设置背景颜色不可用的问题

2010-07-06 16:46 495 查看
 

在做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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息