关于java.awt.Graphics g问题

来源:百度知道 编辑:UC知道 时间:2024/05/13 19:21:23
我定义了一个父类
package Rect;

public class RectClass{
public int x1,x2,y1,y2;

public RectClass(int x1,int y1,int x2,int y2)
{
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}

public RectClass(int width,int height)
{this(0, 0, width, height);}

public RectClass() {this(0, 0, 0, 0);}

public void move(int moveX, int moveY)
{
x1 += moveX;
x2 += moveX;
y1 += moveY;
y2 += moveY;
}

public boolean isInside(int x, int y)
{
return ((x>=x1) && (x<=x2) && (y>=y1) && (y<=y2));

因为 Graphics 是一个抽象类,所以应用程序不能直接调用此构造方法。Graphics可以从其他图形上下文获取,或者通过在swing组件上调用 getGraphics 来创建。

public Graphics getGraphics()为组件创建一个图形上下文。如果组件当前是不可显示的,则此方法返回 null。
返回:组件的图形上下文,如果其没有,则返回 null
从以下版本开始:JDK1.0
另请参见:paint(java.awt.Graphics)

例如:
JFrame jf=new JFrame();
jf.setVisible(true);
Graphics g=jf.getGraphics();
然后再使用g
rec_draw.draw(g);
rec_color.draw(g);
如果画不上的话,尝试把jf.setVisible(true);放在rec_color.draw(g);后面,不敢保证一定能画上,因为在swing组件上画图的一般方法是重写paint()方法,例如:
class DrawPanel extends JPanel {
public DrawPanel() {
super();
}
public void paint(Graphics g) {
g.setColor(Color.red);
g.drawRect(0,0,100,100);
}
public static void main(String args[]){
JFrame jf=new JFrame();
jf.setSize(600,600);
jf.setLocation(200,200);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.getContentPane().setLayout(new BorderLayout());
jf.getConten