Advertisement
RupeshAcharya60

JCheckBoxMenuItem and JRadioButtonMenuItem

Mar 24th, 2023
807
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | Source Code | 0 0
  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4.  
  5. class MenuExample extends JFrame {
  6.     public MenuExample() {
  7.         setTitle("Menu Example");
  8.         setSize(300, 200);
  9.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  10.  
  11.         JMenuBar menuBar = new JMenuBar();
  12.         setJMenuBar(menuBar);
  13.  
  14.         JMenu optionsMenu = new JMenu("Options");
  15.         menuBar.add(optionsMenu);
  16.  
  17.         JCheckBoxMenuItem checkBoxItem = new JCheckBoxMenuItem("Option 1");
  18.         optionsMenu.add(checkBoxItem);
  19.  
  20.         JRadioButtonMenuItem radioItem1 = new JRadioButtonMenuItem("Option 2");
  21.         optionsMenu.add(radioItem1);
  22.  
  23.         JRadioButtonMenuItem radioItem2 = new JRadioButtonMenuItem("Option 3");
  24.         optionsMenu.add(radioItem2);
  25.  
  26.         ButtonGroup radioGroup = new ButtonGroup();
  27.         radioGroup.add(radioItem1);
  28.         radioGroup.add(radioItem2);
  29.  
  30.         ActionListener listener = new ActionListener() {
  31.             public void actionPerformed(ActionEvent e) {
  32.                 JMenuItem item = (JMenuItem)e.getSource();
  33.                 String text = item.getText();
  34.                 boolean selected = item.isSelected();
  35.                 System.out.println(text + " is " + (selected ? "selected" : "deselected"));
  36.             }
  37.         };
  38.  
  39.         checkBoxItem.addActionListener(listener);
  40.         radioItem1.addActionListener(listener);
  41.         radioItem2.addActionListener(listener);
  42.     }
  43.  
  44.     public static void main(String[] args) {
  45.         MenuExample example = new MenuExample();
  46.         example.setVisible(true);
  47.     }
  48. }
  49.  
  50. public class GUI{
  51.     public static void main(String[] args) {
  52.         MenuExample example = new MenuExample();
  53.         example.setVisible(true);
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement