The following example illustrates creating JRadioButtonMenuItem in swing for beginners. This example covers all the constructors and important methods of JRadioButtonMenuItem class.
import javax.swing.*;
import java.awt.*;
class JRadioButtonMenuItemExample extends JFrame
{
JMenuBar mb;
JMenu m;
JRadioButtonMenuItem m1,m2,m3,m4,m5,m6,m7,m8;
ImageIcon i1;
ButtonGroup bg;
public JRadioButtonMenuItemExample()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
setTitle("JRadioButtonMenuItem Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
bg=new ButtonGroup();
mb=new JMenuBar();
m=new JMenu("Menu");
i1=new ImageIcon("imageicon.png");
m1=new JRadioButtonMenuItem();
m2=new JRadioButtonMenuItem(new javax.swing.text.DefaultEditorKit.BeepAction());
m3=new JRadioButtonMenuItem(i1);
m4=new JRadioButtonMenuItem(i1,true);
m5=new JRadioButtonMenuItem("Item 4");
m6=new JRadioButtonMenuItem("Item 5",true);
m7=new JRadioButtonMenuItem("Item 5",i1);
m8=new JRadioButtonMenuItem("Item 6",i1,true);
// Set text
m1.setText("Item 1");
m1.setIcon(i1);
m1.setMnemonic('1');
m1.setFont(new Font("Tahoma",Font.PLAIN,11));
m1.setSelected(true);
// Set a shortcut
m2.setAccelerator(KeyStroke.getKeyStroke("ctrl 2"));
// disable m4
m4.setEnabled(false);
// Set tooltip text
m2.setToolTipText("This produces beep");
bg.add(m1);
bg.add(m2);
bg.add(m3);
bg.add(m4);
m.add(m1);
m.add(m2);
m.add(m3);
m.add(m4);
m.add(m5);
m.add(m6);
m.add(m7);
m.add(m8);
mb.add(m);
setJMenuBar(mb);
setSize(400,400);
setVisible(true);
}
public static void main(String args[])
{
new JRadioButtonMenuItemExample();
}
}
No comments:
Post a Comment