Search code examples
javabuttonjpanelpaintcomponent

Adding buttons on a paintComponent drawn shape


My program is consist of two classes(test and paintClass) in different files. In the paintClass class I draw a 5x5 square board by using paintComponent method. I want to add buttons in each small square in the big square. When I run the code I don't get any buttons. I want to have 25(5x5) buttons by using jpanel on a shape drawn by paintComponent. Is this possible? If it is, how I can do it?

EDIT : The problem was the loop. Number had a default value of 0 so the loop didn't work. I defined number at the beginning. It solved the problem. Also one of the invervals were wrong. I changed j = 0 with j = 1.

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

public class test
{

   public static void main(String[] args) 
   {

       JFrame frame = new JFrame("buttons");
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(250,250);
       PaintClass paint = new PaintClass();
       paint.repaint();
       f1.getContentPane().add(paint);
       frame.pack();
       frame.setVisible(true);
    }
}



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

public class PaintClass extends JPanel
{
    private Graphics g;
    private int interval,side,number;
    private JButton button;

    public PaintClass() 
    {
        number = 5;
        button = new JButton();
        setLayout(new GridLayout(5,5));
        for(int i = 0; i <= number - 1; i++)
        {
            for(int j = 1; j <= number - 1; j++)
            {
                button = new JButton();//ADDED
                button.setBounds(i * interval, 0, interval, interval);
                add(button);
            }
            button = new JButton();//ADDED
            button.setBounds(0, i * interval, interval, interval);
            add(button);
        }
    }

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        this.repaint();
        side = 250;
        number = 5;
        interval = side / number;
        g.drawRect(0,0, side, side);

        for(int i = 0; i <= number - 1; i++)
        {
            for(int j = 0; j <= number - 1; j++)
            {
                 g.drawLine(i * interval, 0, i * interval, side);
            }
            g.drawLine(0, i * interval, side, i * interval);
        }

    }   
}

Solution

  • Choose one or the other: either add the buttons using the GridLayout, or paint the buttons using paintComponent. If the former, you should a) define the loop constraint (right now it is 0) b) create a new JButton for every loop (your code currently reuses the instance) and c) register the appropriate ActionListener to respond to events. If the latter, you need to register the appropriate listener (like MouseListener) to respond to user generated events.