简体   繁体   中英

java swing radio buttons with vertical text

Trying to get radio buttons that look like this in java with swing:

 *  *  *
 O  A  O
 F  U  N
 F  T
    O

...where the * is the radio button

The letters can either be right side up or on their side, I don't really care. I just want the buttons at the top and the letters below each button in a narrow column.

Tried rotating with graphics in the paint() method but it messes up when I mouse over it, redrawing the buttons without rotation. Seems what I need is something like BoxLayout but that will also rotate by 90 deg. Or maybe another layer between the JPanel and the buttons.

public class OffAutoOn extends JPanel {

    public OffAutoOn ()
    {
        JRadioButton b1 = new JRadioButton ("OFF");
        JRadioButton b2 = new JRadioButton ("AUTO");
        JRadioButton b3 = new JRadioButton ("ON");

        ButtonGroup bg = new ButtonGroup ();
        bg.add (b1);
        bg.add (b2);
        bg.add (b3);

        setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
        add (b1);
        add (b2);
        add (b3);
    }

    @Override
    public void paint (Graphics g)
    {
        Graphics2D g2d = (Graphics2D) g;
        AffineTransform at = g2d.getTransform ();
        try {
            int w = getWidth ();
            int h = getHeight ();
            g2d.rotate (Math.PI / 2, w / 2, h / 2);
            super.paint (g);
        } finally {
            g2d.setTransform (at);
        }
    }
}

You can use HTML to create vertical text for the button and then you can change the default position of the text relative to the icon.

For example:

String text = "<html>A<br>u<br>t<br>o</html";
JRadioButton button = new JRadioButton( text );
button.setHorizontalTextPosition(JRadioButton.CENTER);
button.setVerticalTextPosition(JRadioButton.BOTTOM);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM