我寫有3類的Java程序:一節課騎上第二節課?
main.class(main方法的類)
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));
}
}
不要發佈您的所有代碼或您的代碼,請發佈代碼的[MCVE](http://stackoverflow.com/help/mcve)。 –
是的,沒有看到代碼就無法解決這個問題。只需向我們展示相關的部分(infout.class中未調用的方法以及可能調用它的代碼)。 –
我更新了帖子!有關的代碼是 – AbSaintDane