如何在 Java 中显示 JRadioButtonMenuItem?\
awtjavaobject oriented programmingprogrammingswing
在 Java 中,JRadioButtonMenuItem 是 JMenuItem 类的子类。JRadioButtonMenuItem 是菜单项,它是菜单项组的一部分,其中组中 只有一个项目可以选择,并且所选项目显示其选中状态。我们可以将多个单选按钮菜单项添加到 ButtonGroup 对象以形成按钮组。如果按钮组中的一个单选按钮菜单项被选择,则所有其他单选按钮菜单项将未选择。
语法
public class JRadioButtonMenuItem extends JMenuItem implements Accessible
示例
import javax.swing.*; import java.awt.*; public class JRadioButtonMenuItemTest extends JFrame { private JMenuBar mb; private JMenu m; private JRadioButtonMenuItem m1, m2, m3, m4; private ButtonGroup bg; public JRadioButtonMenuItemTest() { setTitle("JRadioButtonMenuItem Test"); setLayout(new FlowLayout()); bg = new ButtonGroup(); mb = new JMenuBar(); m = new JMenu("Menu"); m1 = new JRadioButtonMenuItem(); m2 = new JRadioButtonMenuItem(new javax.swing.text.DefaultEditorKit.BeepAction()); m3 = new JRadioButtonMenuItem("Item 3"); m4 = new JRadioButtonMenuItem("Item 4",true); m1.setText("Item 1"); m1.setFont(new Font("Tahoma",Font.PLAIN,11)); m1.setSelected(true); m2.setAccelerator(KeyStroke.getKeyStroke("ctrl 2")); m3.setEnabled(false); bg.add(m1); bg.add(m2); bg.add(m3); bg.add(m4); m.add(m1); m.add(m2); m.add(m3); m.add(m4); mb.add(m); setJMenuBar(mb); setSize(400, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String args[]) { new JRadioButtonMenuItemTest(); } }