首页 文章

JAVA,GUI JPanel,JFrame,paintComponent,Graphics

提问于
浏览
0

关于你的评论改变添加公共显示(图形g)

[链接] http://www3.canyons.edu/Faculty/biblej/project6.html

1.)Project6类必须扩展JFrame类2.)Project6构造函数必须设置GUI窗口 . 3.)一种新的抽象方法:public void display(Graphics g);应该添加到基类和派生类中.4 . 必须使用paintComponent方法设置自定义JPanel . )新显示(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显示(Graphics 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); }

1 回答

  • 3

    一种新的抽象方法:public void display(Graphics g);应该添加到基类和派生类

    您没有正确执行此步骤,因为我注意到,当 display 打算使用参数时,您正在调用 thearray[i].display(); .

    如果正确创建 display 方法,那么您将获得可以使用的Graphics对象,例如:

    class Line extends Shape {
        int x1, y1, x2, y2;
    
        @Override
        public void display(Graphics g) {
            g.drawLine(x1, y1, x2, y2);
        }
    }
    

相关问题