I'm having trouble detecing a specific menuitem with an action listener. I don't know how to fix it since the menuitems im planning on using all have the same title, so I can't detect using title strings.

I've tried using actionlistener implemented in the class itself, as well as a private class with implementation.

private JMenuBar menuBar;
private JMenu p;
private JMenuItem pic;      
public void createMenu(){
      JMenuBar menuBar = new JMenuBar();
      JFrame frame = new JFrame();
      frame.setTitle("Menu");
      frame.setSize(400,400);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setJMenuBar(menuBar);

      JMenu p = new JMenu("Pawn");   
      p.addMouseListener(new mouse());
      menuBar.add(p);

      JMenuItem pic = new JMenuItem("Picture");
      pic.addActionListener(new actor());
      p.add(pic);
}
private class actor implements ActionListener{        
     public void actionPerformed(ActionEvent e){
         System.out.println("Click");  
         System.out.println(e.getSource());
        if(e.getSource()==pic){
          System.out.println("Detected");   
        }

      }
    }

What I expected to happen is that it will recognize't both sides of the if statement as the same, but clearly it's not equal and I don't know how to fix this problem.

The following is output:

Click
javax.swing.JMenuItem[,1,3,77x21,invalid,alignmentX=0.0,alignmentY=0.0,[email protected],flags=264,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=2,bottom=2,right=2],paintBorder=true,paintFocus=false,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=Picture]

0 Answers