在此代码段中,您将看到如何定义JRadioButton标签位置。默认情况下,标签将显示在按钮的右侧。在下面的代码中,您将看到一些将标签放置在左侧,顶部和底部的示例JRadioButton。
要定义标签位置,我们使用setHorizontalTextPosition()和setVerticalTextPosition()方法的组合,并使用SwingConstants接口中可用常量之一指定位置。
package org.nhooo.example.swing;
import javax.swing.*;
public class RadioButtonLabelPosition {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
// 创建带有右侧标签的JRadioButton
JRadioButton button1 = new JRadioButton("Button One");
button1.setHorizontalTextPosition(SwingConstants.RIGHT);
// 创建带有左侧标签的JRadioButton
JRadioButton button2 = new JRadioButton("Button Two");
button2.setHorizontalTextPosition(SwingConstants.LEFT);
// 创建JRadioButton,底部的标签居中。
JRadioButton button3 = new JRadioButton("Button Three");
button3.setVerticalTextPosition(SwingConstants.BOTTOM);
button3.setHorizontalTextPosition(SwingConstants.CENTER);
// 创建JRadioButton,标签的顶部居中。
JRadioButton button4 = new JRadioButton("Button Four");
button4.setVerticalTextPosition(SwingConstants.TOP);
button4.setHorizontalTextPosition(SwingConstants.CENTER);
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
frame.add(panel);
frame.setSize(300, 300);
frame.setVisible(true);
}
}这是上面代码片段的屏幕截图结果: