【发布时间】:2018-09-26 14:23:33
【问题描述】:
我正在尝试使用 AWT 进行一些简单的 GUI 操作。 我现在坚持的一点是如何调用绘制函数(我正在尝试为每个形状/对象创建一个方法)。我根本无法通过阅读 API 来判断“Graphics”指的是什么参数,我需要在调用时传递函数。看其他例子,我觉得我什至不需要专门称呼它。我很困惑..
另外,是否可以将 drawRect(int ... int) 函数传递给我的实际对象中的值,或者我是否必须诉诸硬编码值,就像它现在在范围内定义的方式一样?
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics.*;
class AWTFigur extends Panel{
Figur f;
AWTFigur (Figur f){
this.f = f;
}
public void paint(Graphics g){
f.paint(g);
}
public Dimension getPreferredSize(){
return new Dimension (f.getWidth()+2, f.getHeight()+2);
}
public void paintRect(Graphics g){
super.paint(g);
g.drawRect(0, 0, 10, 10);
}
public static void main(String args[]){
Frame F=new Frame();
F.setLayout(new FlowLayout());
F.addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent we){System.exit(0);}});
AWTFigur P1=new AWTFigur(new Square(Integer.parseInt(args[0])));
F.add(P1);
AWTFigur P2=new AWTFigur(new Circle(Integer.parseInt(args[1])));
F.add(P2);
F.pack();
F.setVisible(true);
}
}
circle类的代码位:
public class Circle extends Figur{
private int radius;
private int diameter;
private final double pi = 3.14159265358979323846264338327950288419;
public Circle(int radius){
if (radius>0)
this.radius=radius;
else{
this.radius=2;
}
}
@Override
double getCircumference(){
return (this.radius*this.pi*2);
}
@Override
double getArea(){
return this.pi*this.radius*this.radius;
}
int getRadius(){
return this.radius;
}
int getDiameter(){
return this.diameter;
}
void setRadius(int radius){
if (radius > 0)
this.radius=radius;
else{
this.radius=2;
}
}
void setDiameter(int diameter){
if (diameter == (radius*2))
this.diameter=diameter;
else{
this.diameter=radius*2;
}
}
}
对于方形类:
public class Square extends Figur{
private int height;
private int width;
public Square(int height){
if (height >0){
this.height=height;
this.width=height;
}
else{
this.height=2;
this.width=2;
}
}
@Override
double getCircumference(){
return this.height*4;
}
@Override
double getArea(){
return this.width*2;
}
@Override
int getHeight(){
return this.height;
}
@Override
int getWidth(){
return this.width;
}
void setHeight(int height){
if (height > 0)
this.height=height;
else{
this.height=2;
}
}
void setWidth(int width){
if (width > 0)
this.width=width;
else{
this.width=2;
}
}
}
还有超类 Figur:
import java.awt.*;
class Figur{
double getCircumference(){return 0;}
double getArea(){return 0;}
int getHeight(){return 0;}
int getWidth(){return 0;}
public void paint(Graphics g){}
}
【问题讨论】:
标签: java user-interface graphics awt paint