Vertical text align of radio buttons in java

I have been doing some GUI java code in both swing and SWT recently and find text alignment a niggling annoyance of mine. Often you want to align components with the text line vertically of combo or check boxes.

Here is the code for determining the width in pixels for the two most popular GUI libraries in java. Both are cross platform/look-and-feel solutions.

Swing

JRadioButton radio = new JRadioButton();
int raddioButtonOffset =
    UIManager.getIcon("RadioButton.icon")
        .getIconWidth()
    + radio.getIconTextGap()
    + radio.getInsets().left;

SWT

// get the width of a space
GC gc = new GC(parent);
int spaceWidth = gc.getAdvanceWidth(' ');
gc.dispose();

// create radio widget to get widths
Button radioButton = new Button(parent, SWT.RADIO);
Point baseSize =
    radioButton.computeSize(SWT.DEFAULT, SWT.DEFAULT);
radioButton.setText(" ");
Point withSpaceSize =
    radioButton.computeSize(SWT.DEFAULT, SWT.DEFAULT);
radioButton.dispose();

int radioButtonOffset =
    withSpaceSize.x
    - ((withSpaceSize.x - baseSize.x) / 2)
    - spaceWidth;


Leave a Reply

:D :) :( :o 8) :eek: ;-( :grin: :wink: :arrow: :idea: :?: :!: :evil: O:) :-| :-* :-(( :poke: :love: :tired: :emotion: :party: :clown: :worried: X( :p