Aleksandr Kravets Aleksandr Kravets - 5 months ago 35
Java Question

Swing: Resizing RadioButton

I need to implement font size switching in my app. But when I increase font's size RadioButtons remain same size and on small screen with high resolution my customer just can't hit it easily. Is there a way to resize RadioButton's round thing programmatically without diging into L&F and redrawing Icons manually (it's complicated since app targets multiple platforms with different UIs and each of them must have 7 icons).

Perfect solution could look like this:


  1. Extraction of native UI icon.

  2. Resizing it

  3. Setting resized icon as component's icon.



How to implement step 1? Is it possible?

EDIT: this is what i tried so far

public class IconImageSaver extends JFrame{

public IconImageSaver() {

setDefaultCloseOperation(EXIT_ON_CLOSE);
setBounds(0,0,100,100);
setVisible(true);

JRadioButton rad1 = new JRadioButton();
rad1.setBounds(10,10,40,40);
add(rad1);

Icon icon = UIManager.getIcon("RadioButton.icon");//(1) trying to get icon

int w = icon.getIconWidth(),h = icon.getIconHeight();
Image i = rad1.createImage(w, h);
Image i2 = rad1.createImage(w,h);
Graphics g = i.getGraphics();
Graphics g2 = i2.getGraphics();


g.setColor(Color.CYAN);
g.fillRect(0, 0, w, h);
rad1.setIcon(new ImageIcon(i));//setting icons
g2.setColor(Color.RED);
g2.fillRect(0, 0, w, h);
rad1.setPressedIcon(new ImageIcon(i2));//setting icons
}

public static void main(String[] args) {
new IconImageSaver();
}

}


At position (1) i'm trying to get icon image, but it returns only background color.
Can't understand why.
Setting icons for various states works as intended.

Answer

Some L&Fs (e.g. Nimbus, Aqua) support a large JComponent.sizeVariant, as discussed in Resizing a Component and Using Client Properties.

Addendum: I must use pure native L&F.

The rendering of a JRadioButton is determined by its associated ButtonUI delegate. The internals of delegates supplied by the native L&F are generally inaccessible and rely on host platform APIs. You have to use the available feature(s) of the user's chosen L&F or supply your own. If you can explain more about the underlying problem, it may help to suggest better alternatives.

Addendum: Absent developing a complete L&F, it may be possible to work with the radio button's parent, JToggleButton. Such buttons work well in a ButtonGroup, as shown here, and they can be decorated arbitrarily, as outlined here.

Comments