一节课超过第二节课?

时间:2014-03-19 17:19:20

标签: java

我编写了一个包含3个类的Java程序:

main.class (主要方法类)

Infout.class (绘制圆圈+方法的类,允许用键盘输入(箭头键)控制

obj2.class (绘制矩形的类)


所有代码编译都很好,但由于某些原因,当我运行程序时,程序执行 obj2.class 中的所有代码,但不执行 Infout.class中的代码

换句话说,它绘制矩形( obj2.class )但不绘制可控圆( Infout.class )。 Obj2.class 是否超过了 Infout.class ?如果是,我该怎么办?

代码太大了,无法在此发布,该网站称这篇文章是"主要是代码" :C

谢谢!

编辑:好的,这是相关的代码:

main.class

    import javax.swing.JFrame;

    public class main {
        public static void main(String args[]) {
    JFrame frame = new JFrame();
    Infout m = new Infout();
    obj2 o = new obj2();

    frame.add(m);
    frame.add(o);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 400);
    frame.setTitle("Circle");
}
    }

Infout.class

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;

public class Infout extends JPanel implements ActionListener, KeyListener {

    Timer t = new Timer(5, this);
    double x = 0, y = 0, velx = 0, vely = 0;

    public Infout(){
        t.start();
        addKeyListener(this);
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);

    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.fill(new Ellipse2D.Double(x, y, 40, 40));
    }

    public void actionPerformed(ActionEvent e) {

        repaint();
        x += velx;
        y += vely;

        if (x < 0 || x > 260)
        {
            velx = 0;
            vely = 0;
        }
        if (y < 0 || y > 340)
        {
            velx = 0;
            vely = 0;
        }
    }

    public void up() {
        vely = -1.5;
        velx = 0;
    }

    public void down() {
        vely = 1.5;
        velx = 0;
    }

    public void left() {
        velx = -1.5;
        vely = 0;
    }

    public void right() {
        velx = 1.5;
        vely = 0;
    }

    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode();
        if (code == KeyEvent.VK_UP) {
            up();
        }
        if (code == KeyEvent.VK_DOWN) {
            down();
        }
        if (code == KeyEvent.VK_RIGHT) {
            right();
        }
        if (code == KeyEvent.VK_LEFT) {
            left();
        }
    }

    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}
}

obj2.class

    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.Ellipse2D;
    import javax.swing.JPanel;


    public class obj2 extends JPanel{

int x;
int y;

public obj2(){

}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.fill(new Ellipse2D.Double(10, 20, 40, 40));
}

    }

1 个答案:

答案 0 :(得分:0)

Infoutobj2无关。

由于obj2延伸JPanel,所以通话super.paintComponent(g)会调用JPanel的版本。如果您obj2成为Infout的子类,那么您需要使用extends

public class obj2 extends Infout {
    // Code here
}

完成此操作后,super将引用Infout