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.