I wanted to know if it is possible to use/make a function in another Class to draw an image/oval and then call it in the paint public void in our main Class.
If I have
public class Trydraw{
public void drawrcircle(Graphics g){
g.setColor(Color.RED);
g.drawOval(0, 0, 20,20);
g.fillOval(0,0,20,20);
}
}
And then call it here this way
import java.awt.GridLayout;
import javax.swing.*;
import java.awt.*;
public class Display extends JPanel{
public static void main(String[]haha){
JFrame frame = new JFrame();
frame.setSize(800, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void paint(Graphics g){
super.paint(g);
Trydraw l = new Trydraw();
l.drawrcircle(g);
}
}
Thanks for your future help.
CodePudding user response:
Yes you can, if I get your question correctly. Your sample code works for me if I add
frame.add(new Display());
to the end of your
public static void main(String[] haha)
method.
With your snippet the paint(g)
method will never be called, because it will be executed with the initialization of the JPanel
which will be initialized with the initialization the Display
class (because of inheritance).
You probably want to create an instance of Display
, which automatically initializes the JPanel
with the overridden paint(g)
method, thus the new
Operator.
As the constructor of a JPanel
returns a JPanel
, the constructor of Display returns a type of JPanel
as well, which contains the red circle. This JPanel
needs to be added with the add
method to your original JFrame
.