Итак, мой учитель хочет, чтобы я сделал интерактивную анимацию. Проблема в том, что он не сказал классу, как это сделать. (Это онлайн-курс). Суть в том, что он хочет, чтобы я сделал графику, которую можно контролировать с помощью клавиатуры. Я посмотрел в Интернете, но, видимо, я не задавал правильных вопросов, потому что по какой-то причине я начинаю пустым.Как создать интерактивную анимацию?
Anyways. У меня есть три файла кода. Zorx1, Zorx2 и Zorx3, которые являются одними и теми же инопланетянами с незначительными различиями в цвете, которые дал учитель.
// The Zorx alien object
import java.awt.*;
public class Zorx1
{
/* the fields of the object defined here as static to make the
interface as simple as possible to start*/
static int x = 100, y = 100;
static int size = 50;
static Color clr = Color.red;
static boolean showing = false;
// paints Zorx on the screen Note this method is not part of Interface
static void paint (Graphics g)
{
g.setColor (clr);
g.fillRect (x, y, size/4, size);
g.setColor (Color.black);
g.drawLine (x-3,y-2,x-1,y+size/8);//These four lines will add fangs to this guy. Nasty!
g.drawLine (x-2,y-2,x-1,y+size/8);
g.drawLine (x+3,y-2,x+5,y+size/8);
g.drawLine (x+2,y-2,x+4,y+size/8);
g.setColor (clr);
g.fillOval (x - (3 * size/8), y - (size/2), size, size/2);
g.drawLine (x - 3 * size/8, y + size, x - 3 * size/8 + size, y + size);
g.drawLine (x, y + size/2, x - size, y);
g.drawLine (x - size, y, x - size, y - size/4);
g.drawOval (x - size - size/8, y - size/4 - size/8, size/8, size/8);
g.setXORMode (Color.black); //Makes his eyes black. Sinister
g.fillOval (x - size/4, y - size/3, size/12, size/12);
g.fillOval (x + size/4, y - size/3, size/12, size/12);
g.fillOval (x - size/1000, y - size/4, size/12, size/12); //adds a third eye to our alien. Spooooooooky.
g.setPaintMode();
} // end of paint method
// Show the Zorx alien. The show method is part of the interface.
public static void show (Graphics g)
{
paint (g);
showing = true;
} // end of show method
// Erase Zorx from the screen. The erase method
// is not part of the interface.
static void erase (Graphics g, Color backgroundColor)
{
g.setColor (backgroundColor);
g.fillRect (x, y, size/4, size);
g.fillOval (x - (3 * size/8), y - (size/2), size, size/2);
g.drawLine (x-3,y-2,x-1,y+size/8);
g.drawLine (x-2,y-2,x-1,y+size/8);
g.drawLine (x+3,y-2,x+5,y+size/8);
g.drawLine (x+2,y-2,x+4,y+size/8);
g.drawLine (x - 3 * size/8, y + size, x - 3 * size/8 + size, y + size);
g.drawLine (x, y + size/2, x - size, y);
g.drawLine (x - size, y, x - size, y - size/4);
g.drawOval (x - size - size/8, y - size/4 - size/8, size/8, size/8);
g.fillOval (x - size/4, y - size/3, size/12, size/12);
g.fillOval (x + size/4, y - size/3, size/12, size/12);
} // end of erase method
// Hide Zorx The hide method is part of the interface.
public static void hide (Graphics g, Color backgroundColor)
{
erase (g, backgroundColor);
showing = false;
} // end of hide method
// Move Zorx from one location to another. The move method
// is part of the interface.
public static void move (int newX, int newY, Graphics g, Color backgroundColor)
{
if (showing)
{
erase (g, backgroundColor);
}
x = newX;
y = newY;
if (showing)
{
show (g);
}
} // end of move method
} // end of Zorx Class
Иностранец объект имеет все методы и все необходимое для перемещения объекта вокруг, в то время как анимация должна контролировать все это.
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Animation extends JFrame implements KeyListener
{
public Animation (Graphics g)
{
Zorx1.show(g);
Zorx2.show(g);
Zorx3.show(g);
this.setFocusable(true);
}
public static void main (String args[])
{
Animation application = new Animation(g);
application.setVisible(true);
}
public int x=100;
public int y=100;
public void keyPressed (KeyEvent e)
{
switch (e.getKeyCode()) //I can't seem to get this thing to animate through this so this is just left blank for the sake of necessity.
{
case KeyEvent.VK_LEFT:
break;
case KeyEvent.VK_RIGHT:
break;
case KeyEvent.VK_DOWN:
break;
case KeyEvent.VK_UP:
break;
}
}
public void keyTyped(KeyEvent e)
{
if (e.getKeyChar() == KeyEvent.VK_LEFT)
{
left(g);
}
else if (e.getKeyChar() == KeyEvent.VK_RIGHT)
{
right(g);
}
else if (e.getKeyChar() == KeyEvent.VK_UP)
{
up(g);
}
else if (e.getKeyChar() == KeyEvent.VK_DOWN)
{
down(g);
}
if (e.getKeyChar() == KeyEvent.VK_ESCAPE)
{
System.exit(0);
// If you hit escape you will exit the animation
}
}
public void left (Graphics g)
{
x=x-10;
Zorx1.move (x,y, g, getBackground());
Zorx2.move (x,y+50,g,getBackground());
Zorx3.move (x,y+100,g,getBackground());
}
public void right (Graphics g)
{
x=x+10;
Zorx1.move (x,y,g,getBackground());
Zorx2.move (x,y+50,g,getBackground());
Zorx3.move (x,y+100,g,getBackground());
}
public void up(Graphics g)
{
y=y-10;
Zorx1.move (x,y,g,getBackground());
Zorx2.move (x,y+50,g,getBackground());
Zorx3.move (x,y+100,g,getBackground());
}
public void down(Graphics g)
{
y=y+10;
Zorx1.move (x,y,g,getBackground());
Zorx2.move (x,y+50,g,getBackground());
Zorx3.move (x,y+100,g,getBackground());
}
public void keyReleased(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_LEFT:
break;
case KeyEvent.VK_RIGHT:
break;
case KeyEvent.VK_DOWN:
break;
case KeyEvent.VK_UP:
break;
}
}
}
Я понимаю, что приведенный выше код не работает, но это, вероятно, потому что я понятия не имею, какого черта я должен делать.
Я выяснил, что вызывало переопределяющую проблему статического метода. Я добавил расширение JFrame к zorx1.java, и это вызвало конфликт с краской (Graphics g). Поэтому я просто переименовал его в make (Graphics g). Надеюсь, это не вызовет осложнений.
Я думаю, что мне нужно будет переместить интерактивную часть клавиатуры в другой класс (надеюсь), но у меня тоже есть проблема с этим.
public class Animation extends JFrame
{
public int x=100;
public int y=100;
public Animation (Graphics g)
{
Zorx1.show(g);
Zorx2.show(g);
Zorx3.show(g);
}
public static void main (String args[])
{
Animation application = new Animation (g);
}
новый Анимация (g); не может найти символ g. И я не могу добавить его нигде, потому что это вызовет проблему. Как я могу заставить его распознать символ, или я никогда не нуждался в нем в первую очередь?
public Animation()
{
repaint();
}
public void paintComponent (Graphics g)
{
super.paintComponent(g);
Zorx1.show(g);
Zorx2.show(g);
Zorx3.show(g);
}
Хорошо, я думаю, что получил, но super.paintComponent (g); возвращает ошибку, в которой говорится: «не удается найти символ - метод paintComponent (java.awt.Graphics)».
Исправлено. В заключение.
Пожалуйста, перечитайте мои сообщения и учебные пособия. Я несколько раз говорил вам, какой тип класса должен находиться в этом методе. –