Как создать прослушиватель для JMenuItem? [Дубликат]

0
задан liamslagle 6 December 2013 в 01:27
поделиться

2 ответа

Что мне кажется: у вас есть

JMenuBar menuBar = new JMenuBar();

JMenu file = new JMenu("File");
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ev) {
            System.exit(0);
    }
});

JMenu headMenu = new JMenu("Heads");

вне определения какого-либо метода, и нет способа вызвать этот код.

Попробуйте следующее:

public class Main extends JFrame{

  //initialize integer height/width values along with declaring 
  //Swing component variables
  private final int W = 500,
                    H = 500;

  private JMenu file, headMenu, bgMenu;
  private JMenuBar menuBar;
  private JMenuItem exitItem;

  //constructor
  public Main(){
    setTitle("Move the Head");
    setSize(W, H);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);

    initializeElements();

  }

  //Initializes the elements, this part is missing from your code above.
  public void initializeElements(){

    menuBar = new JMenuBar();
    file = new JMenu("File");
    exitItem = new JMenuItem("Exit");

    exitItem.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ev) {
        System.exit(0);
      }
    });

    headMenu = new JMenu("Heads");
    bgMenu = new JMenu("Backgrounds");

  }

  public static void main( String[] args ) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            Main f = new Main();
            f.setVisible(true);
        }
    });
  }
}
2
ответ дан Jason 25 August 2018 в 08:09
поделиться

Этот код в порядке. Вероятно, синтаксическая ошибка на соседней линии, которая испортила разбор. Либо предыдущая строка, либо что-то, что закручивает объявление exitItem.

0
ответ дан MattPutnam 25 August 2018 в 08:09
поделиться
Другие вопросы по тегам:

Похожие вопросы: