簡體   English   中英

使用PaintComponent在Panel外部繪制

[英]Using PaintComponent to draw outside of Panel

嘿伙計我剛剛來到這里,因此我提前為我的模糊問題道歉。 我有一個學校項目完成,目標是創建一個完全工作的Paint Programm。 我們獲得了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);
}
}

現在我的問題是我不知道如何從我的Panel調用這個類。 當我嘗試在PaintComponent方法中從我的JPanel調用draw(...)時 ,它什么也沒做。 這是我在我的JFrame fyi中添加的JPanel類。

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);
}
}

不要介意參數中的Frame,這是針對橢圓,線和多邊形類中的克隆方法,以避免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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM