How to set SWT button foreground color?

2020-01-29 02:17发布

The SWT Button class has a setForeground(Color) method but it seems to have no effect (the method is actually on Button's superclass). The javadoc says that this method is a hint and may be overridden by the platform. My platform is Windows.

  • Does this mean that it is not possible to set button foreground color on Windows?
  • Does it work on other platforms?
  • Is there a workaround?

标签: java colors swt
4条回答
冷血范
2楼-- · 2020-01-29 02:48

This is the code to Implement FOreground Color in Buttons in SWT with allowing Mnemonic key to be Shown also and Enabled by Pressing 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);

    }

});

Note: hex2Col is my own method to Convert hex Color Code to Color Type

Note: Here ALT+C is Mnemonic Key Combination i have Used

查看更多
再贱就再见
3楼-- · 2020-01-29 02:56

On Windows, setForeground for Buttons has no effects.

As a workaround, add a PaintListener to your Button. On this Listener's paintControl method, get the generated event's GC and, with it, re-write the text of your Button using the color you want.

You can, in fact, draw anything over your Button.

查看更多
劳资没心,怎么记你
4楼-- · 2020-01-29 02:56

On windows, setForeground doesn't work for Group either.

If you can convince your users to use the Classic Theme, setForeground will miraculously work.

查看更多
forever°为你锁心
5楼-- · 2020-01-29 02:57

If you need Button with style SWT.CHECK you can try use Button without text and add Label element. Example:

chkAutorun = new Button(fCompositeLogin, SWT.CHECK);
Label lblAutorun = new Label(fCompositeLogin, SWT.NONE);
lblAutorun.setForeground(white);
lblAutorun.setText("Autorun");
查看更多
登录 后发表回答