0

I'm trying to make it so that after clicking on the button, a figure is added to the canvas. But I can't correctly implement the listener method in the OvalDrawTool class.

package com.company;

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

public class TestFrame extends JFrame{
    public final OvalDrawTool odt = new OvalDrawTool();

    public static void main(String[] args){
        new TestFrame().start();
    }

    public void start(){
        setLayout(new BorderLayout());

        JPanel buttonsPanel = new JPanel();
        JButton buttonOval = odt.getButtonOval();
        buttonsPanel.add(buttonOval);

        add(buttonsPanel, BorderLayout.NORTH);
        setSize(500,500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

}

I do not understand how should I create a Graphics object and pass it in actionPerformed method

package com.company;

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

public class OvalDrawTool implements ActionListener{
    public JButton getButtonOval() {
        JButton buttonOval = new JButton();

        buttonOval.setPreferredSize(new Dimension(100, 50));
        buttonOval.setText("Oval");
        buttonOval.addActionListener(this);
        return buttonOval;
    }

    public void paintOval(Graphics g) {
        g.setColor(Color.green);
        g.fillOval(100, 100, 50, 50);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        paintOval();
    }
}

I moved the figure drawing method into a separate class since I want to add more other shapes.

dmnvch
  • 7
  • 1
  • 2
    Maintain "a `List` and let your implementation of `paintComponent()` iterate through the list to render the shapes;" examples are cited [here](https://stackoverflow.com/a/27792312/230513) and [here](https://stackoverflow.com/a/11944233/230513). – trashgod Nov 09 '21 at 17:00
  • Do you custom painting on a JPanel by overriding `paintComponent()`, If you only want to draw one shape have `paintComponent()` paint it or skip it , controlled by a boolean flag. Clicking the button should change the flag to `true` and call `repaint()`. For more info see: [Performing Custom Painting](https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) – c0der Nov 09 '21 at 18:23

0 Answers0