Hey ppl,

i am trying to do this exercise from my java book, but i cant do anything right apparently :(

Write an application that asks the user to enter an integer n, and then draw an n by n grid on the panel. whenever the user clicks inside one of the grid squares on the panel, color that grid square in black.

I tried this:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class EXCP1014
{
    public static void main(int n)
    {
        MainFrame frame = new MainFrame(n);
        frame.setTitle("The Big Grid");
        frame.setVisible(true);
    }
}

class MainFrame extends JFrame
{
    public MainFrame(int n)
    {
        setSize(600,600);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        
        for (int i = 0; i < n * n; i++)
        {
            getContentPane().add(new MyPanel().addActionListener(new PanelListener()));
        }
        
        getContentPane().setLayout(new GridLayout(n,n));
        
    }
    
    class PanelListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            setBackground(Color.black);
            repaint();
        }
    }
}

class MyPanel extends JPanel
{
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
    }
}

but i get an error at the code inside te for loop:

cannot find symbol: method addActionListener(MainFrame.PanelListener)

Please help!!

JPanel does not have an addActionListener() method.

Perhaps you should use JButtons or use a MouseListener for your panel instead of ActionListener.

This article has been dead for over six months. Start a new discussion instead.