嘿,大家好,我是新来的,因此我为我模糊的问题提前道歉。 我有一个学校项目要完成,其目标是创建一个完全可用的绘画程序。 我们分了3个类。椭圆形、直线和多边形。这些类的工作原理基本相同,主要区别在于它们绘制的形式。其中一个类如下所示:
public class Oval extends Drawable{
private int x1,y1,x2,y2;
private Color c;
private JFrame f;
/**
* Constructor of the Oval Class
* Initialises the attributes of this Class
*
* @return void
*/
public Oval(int X, int Y, int width, int height, Color c){
this.x1 = x1;
this.y1= y1;
this.x2 = x2;
this.y2 = y2;
this.c = c;
}
/**
* Draws an Oval based on the Values x1,y1,x2,y2
*
* @return void
*/
@Override
public void draw(Graphics g) {
g.setColor(c);
g.drawOval(x1, y1, x2, y2);
}
}
现在我的问题是我不知道如何从我的面板中调用这个类。当我尝试在 PaintComponent 方法中从 JPanel 调用 draw(...) 时,它绝对不执行任何操作。 这是我的 JPanel 类,我已将其添加到我的 JFrame 仅供引用。
public class PaintPanel extends JPanel {
private PaintFrame f;
public PaintPanel(PaintFrame f){
this.f = f;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Oval o = new Oval(100, 100, 50, 50, new Color(127, 184, 255), f);
o.draw(g);
}
}
不要介意参数中的框架,这是椭圆形、直线和多边形类内的克隆方法,以避免 OutOfBounce 绘图。
现在我的框架:
public class PaintFrame extends JFrame{
private PaintPanel pp;
public PaintFrame(){
pp = new PaintPanel(this);
this.setSize(500, 500);
this.setTitle("Paint");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(pp);
this.setVisible(true);
}
}
所以我想这差不多就是这样了。我只想完成这项工作,因为这几乎是整个项目的基本部分。预先感谢您的任何帮助,如果您有任何建议可以使我的下一个问题更好、更准确,请随时批评:)
最佳答案
看起来您的 Oval
坐标没有在 Oval
构造函数中正确设置。您需要做的是使用初始 x 和 y 位置以及宽度和高度值来计算它们,如下所示:
this.x1 = X;
this.y1= Y;
this.x2 = x+width;
this.y2 = y+height;
关于java - 使用PaintComponent在Panel之外绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44186460/