如何设置SWT按钮前景色?

SWT Button类有一个setForeground(Color)方法,但似乎没有效果(该方法实际上是在Button的超类上)。 javadoc说这个方法是一个提示,可能会被平台覆盖。 我的平台是Windows。

  • 这是否意味着无法在Windows上设置按钮前景色?
  • 它在其他平台上有效吗?
  • 有解决方法吗?

在Windows上, Buttons setForeground没有任何效果。

要解决此问题,请在Button添加PaintListener 。 在这个Listener的paintControl方法中,获取生成的事件的GC并使用它,使用您想要的颜色重写Button的文本。

事实上,您可以在Button绘制任何内容。

如果您需要具有样式SWT.CHECK的Button,您可以尝试使用不带文本的Button并添加Label元素。 例:

 chkAutorun = new Button(fCompositeLogin, SWT.CHECK); Label lblAutorun = new Label(fCompositeLogin, SWT.NONE); lblAutorun.setForeground(white); lblAutorun.setText("Autorun"); 

在Windows上,setForeground也不适用于Group。

如果您可以说服您的用户使用经典主题,setForeground将奇迹般地工作。

这是在SWT中按钮实现FOreground Color的代码,同时允许显示助记键,按Alt +“Mnemonic Key”启用;

 Button radioButton=new Button(parent,SWT.RADIO); StringBuffer sb = new StringBuffer("I am a Coloured radio button"); String name=null; String S = "I am a Coloured radio button"; String substr="C"; int i=S.indexOf(substr); sb.insert(i,"&"); S=sb.toString(); name=sb.substring(i, i+2); name=sb.toString(); String whiteSpace=" "; final String TName=S; for(int l=0;l<1000;l++) whiteSpace=whiteSpace.concat(" "); radioButton.setText(name+whiteSpace); radioButton.addPaintListener(new PaintListener(){ String name=TName; @Override public void paintControl(PaintEvent e) { // TODO Auto-generated method stub e.gc.setForeground(hex2Col("ffffcc")); int x=21; int y=21; e.gc.drawText(name, x,y,SWT.DRAW_MNEMONIC | SWT.TRANSPARENT); } }); 

注意:hex2Col是我自己的将hex颜色代码转换为颜色类型的方法

注意:这里ALT + C是我使用的助记键组合