0

I’m following a Java tutorial but it isn’t working.

Question 1: why does the setMnemonic not work on my Mac, is it because Mac uses Option instead of Alt

Question 2: why does the action listener not work on my JMenu

The mnemonic did work on my JMenuItem, also actionlisyener worked on JMenuItem too, but not JMenu

I tried using UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); to use the windows feel and look on Mac

Thanks for any help!

I have this:





import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

public class MyFrame extends JFrame implements ActionListener {

    JMenu fileMenu;
    JMenu editMenu;
    JMenu helpMenu;

    JMenuItem loadItem;
    JMenuItem saveItem;
    JMenuItem exitItem;

    MyFrame() {

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(500, 500);
        this.setLayout(new FlowLayout());

        JMenuBar menuBar = new JMenuBar();

        fileMenu = new JMenu("File");
        editMenu = new JMenu("Edit");
        helpMenu = new JMenu("Help");

        loadItem = new JMenuItem("Load");
        saveItem = new JMenuItem("Save");
        exitItem = new JMenuItem("Exit");

        fileMenu.addActionListener(this);
        editMenu.addActionListener(this);
        helpMenu.addActionListener(this);

        fileMenu.setMnemonic(KeyEvent.VK_F); //alt+F打开file
        editMenu.setMnemonic(KeyEvent.VK_E);
        helpMenu.setMnemonic(KeyEvent.VK_H);

        fileMenu.add(loadItem);
        fileMenu.add(saveItem);
        fileMenu.add(exitItem);

        menuBar.add(fileMenu);
        menuBar.add(editMenu);
        menuBar.add(helpMenu);

        this.setJMenuBar(menuBar);
        this.setVisible(true);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == fileMenu) {
            System.out.println("File menu opened");
        }
        if (e.getSource() == editMenu) {
            System.out.println("Edit menu opened");
        }
        if (e.getSource() == helpMenu) {
            System.out.println("Help menu opened");
        }
    }
} 


I tried using UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); to use the windows feel and look on Mac

The tutorial was done on windows

  • UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()) Doesn’t set the “windows” look and fell, it sets the “metal” (aka cross platform) look and feel and I, personally, wouldn’t use it, instead preferring the system look and feel, as using the system look and feel reduces the entry acceptance level for a user - when it “looks” different, it’s another hurdle for the user to get over – MadProgrammer Mar 26 '23 at 02:56

0 Answers0