[英]JAVA, GUI JPanel, JFrame, paintComponent, Graphics
关于您的评论更改添加公共显示(图形g)
[link] http://www3.canyons.edu/Faculty/biblej/project6.html
1.)Project6类将必须扩展JFrame类。2.)Project6构造函数将必须设置GUI窗口。 3)一种新的抽象方法:public void display(Graphics g); 应该添加到基类和派生类中。4)必须使用paintComponent方法设置自定义的JPanel。5)新的display(Graphics g)方法将必须在GUI窗口上绘制形状并从循环中调用在paintComponent方法中
public class Project6 extends JFrame {
//project6 constructor without parameters to set up new JFrame
public Project6() {
add(new NewPanel());
}
class NewPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//所以我需要在这里添加Graphics g吗? 或者没有?
for(int i = 0; i < thearray.length && thearray[i] != null; i++) {
thearray[i].display(**Graphics g**);
}}}
public static void main (String [] args) {
JFrame frame = new JFrame();
frame.setSize(800, 700);
frame.setTitle("Shapes");
frame.setLocationRelativeTo(null); //Center Frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
例如,这是类之一,是否可以像这样将其添加到末尾? 我是否需要向Shape父类添加公共抽象void显示(图形g)? 以及如何在project6类中调用它?
public class Rectangle extends Shape {
private int width;
private int height;
public Rectangle() {
setWidth(0);
setHeight(0);
setXPos(0);
setYPos(0);}
public Rectangle(int xPos, int yPos, int height, int width) {
setWidth(xPos);
setHeight(yPos);
setXPos(height);
setYPos(width);}
public int getWidth() {
return width;}
public void setWidth(int width) {
this.width = width;}
public int getHeight() {
return height;}
public void setHeight(int height) {
this.height = height;}
@Override
public void display() {
System.out.println("Rectangle: (" + getXPos() + ", " + getYPos() + ") " + " Height: " + height + " Width: " + width);}
@Override
public void display(Graphics g) {
g.drawRect(getXPos(), getYPos(), width, height); }
一种新的抽象方法: public void display(Graphics g); 应该添加到基类和派生类
您没有正确完成此步骤,因为我注意到您正在调用thearray[i].display();
当display
旨在具有参数时。
如果正确创建display
方法,则将获得可以使用的Graphics对象,例如:
class Line extends Shape {
int x1, y1, x2, y2;
@Override
public void display(Graphics g) {
g.drawLine(x1, y1, x2, y2);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.