Question

I'm trying to add ActionListener to JMenuItem in my java menu.

Here is a screenshot of the menu:

enter image description here

I want to add ActionListener to "Rectangle" JMenuItem in order to show up the rectangle shape upon clicking on the "Rectangle" menu item. I tried many times to add the ActionListener but I fail every time.

Here is my code:

Class "menubar.java" :

import javax.swing.*;

public class menubar extends JFrame{

public menubar(){
    JMenuBar menubar = new JMenuBar();
    setJMenuBar(menubar);

    JMenu shape = new JMenu("Shape");
    menubar.add(shape);

    JMenuItem rect = new JMenuItem("Rectangle");
    shape.add(rect);

    JMenuItem star = new JMenuItem("Star");
    shape.add(star);

    JMenu color = new JMenu("Color");
    menubar.add(color);

    JMenuItem black = new JMenuItem("Black");
    color.add(black);

    JMenuItem orange = new JMenuItem("Orange");
    color.add(orange);
}

public static void main(String[] args) {
    menubar gui = new menubar();
    gui.setTitle("Menu Bar");
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    shapes SPS = new shapes();
    gui.add(SPS);
    gui.setSize(500,300);
    gui.setVisible(true);
    gui.setLocationRelativeTo(null);
}
}

Class "shapes.java" :

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class shapes extends JPanel{
int midX = 220;
int midY = 90;
int radius[] = {60,20,50,20};
int nPoints = 16;
int[] X = new int[nPoints];
int[] Y = new int[nPoints];

public void paintComponent(Graphics gphcs){
super.paintComponent(gphcs);
this.setBackground(Color.WHITE);

gphcs.setColor(Color.BLUE);
gphcs.fillRect(20,35,100,30);

gphcs.setColor(Color.RED);
gphcs.drawString("Welcome to Java", 20, 20);

for (int i=0; i < nPoints; i++) {
       double x = Math.cos(i * ((2 * Math.PI) / nPoints)) * radius[i % 4];
       double y = Math.sin(i * ((2 * Math.PI) / nPoints)) * radius[i % 4];

       X[i] = (int) x + midX;
       Y[i] = (int) y + midY;
}
gphcs.setColor(Color.GREEN);
gphcs.fillPolygon(X, Y, nPoints);
}
}

I would be very thankful if anybody helped me with this issue.

Thanks for your time..

Was it helpful?

Solution

One way that you can add an ActionListener to your container is :

public class JMenuClass extends JFrame implements ActionListener

Then, for each JMenuItem that you need a listener, you would do

item.addActionListener(this)

At the bottom of your class, you would need to add your actionPerformed methods, or however you want to implement it.

Cheers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top