Search code examples
javaswingjcheckboxjmenu

show message on console on selecting check box menu item


When the user ticks the check box menu item, I want to show some message to the user on console. How can I do that? For now when the user checks the checkbox message is displayed only on the frame. How can I display some message on the console too?

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import javax.swing.BorderFactory;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;

public class CheckBoxMenu extends JFrame {

    private JLabel statusbar;

    public CheckBoxMenu() {

        initUI();
    }

    private void initUI() {

        createMenuBar();

        statusbar = new JLabel("On Progress...");
        statusbar.setBorder(BorderFactory.createEtchedBorder());
        add(statusbar, BorderLayout.SOUTH);

        setTitle("JCheckBoxMenuItem");
        setSize(360, 250);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void createMenuBar() {

        JMenuBar menubar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");

        JMenu viewMenu = new JMenu("View");
        JCheckBoxMenuItem sbarMi = new JCheckBoxMenuItem("Show Statusbar");

        sbarMi.setSelected(true);

        sbarMi.addItemListener((ItemEvent e) -> {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                statusbar.setVisible(true);
            } else {
                statusbar.setVisible(false);
            }
        });

        viewMenu.add(sbarMi);

        menubar.add(fileMenu);
        menubar.add(viewMenu);

        setJMenuBar(menubar);
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(() -> {
            CheckBoxMenu ex = new CheckBoxMenu();
            ex.setVisible(true);
        });
    }
}

Solution

  • You could just use a System.out.println call in your listener, or use a logger.

    sbarMi.addItemListener((ItemEvent e) -> {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            statusbar.setVisible(true);
            // Using System.out
            System.out.println("On Progress...");
            // Or using a logger (defined somewhere else, using Logger.getLogger or a logging framework.)
            logger.info("On Progress.");
        } else {
            statusbar.setVisible(false);
        }
    });