[英]Drawing with functions on JFrame or JPanel java
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.我想知道是否可以在另一个类中使用/制作一个函数来绘制图像/椭圆,然后在我们的主类的paint public void 中调用它。
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.感谢您未来的帮助。
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).使用您的代码片段, paint(g)
方法将永远不会被调用,因为它将通过 JPanel 的初始化执行,该JPanel
将通过Display
类的初始化来初始化(因为继承)。
You probably want to create an instance of Display
, which automatically initializes the JPanel
with the overridden paint(g)
method, thus the new
Operator.您可能想要创建一个Display
实例,它使用重写的paint(g)
方法自动初始化JPanel
,因此是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.由于JPanel
的构造函数返回一个JPanel
,因此 Display 的构造函数也返回一个JPanel
类型,其中包含红色圆圈。 This JPanel
needs to be added with the add
method to your original JFrame
.此JPanel
需要使用add
方法添加到您的原始JFrame
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.