呸。我想出了这个bug。当然这很荒谬。 MovingPanelItem下的重写更新需要编写如下:
@Override
public void update( int x, int y )
{
xCoord = xCoord + getxStep();
yCoord = yCoord + getyStep();
}
完全披露:这是作业。
问题: 在每个Key侦听器事件时,应更新屏幕并移动移动对象。目前,当对象最初出现时,如果按下指定的键,它们就会消失。
此外,所有PanelItem都存储在ArrayList中(在另一个类中)。所有不是MovingPanelItem子类的对象都保留在KeyEvent的屏幕上。
我知道我已经留下了很多想象力所以如果需要更多细节请告诉我。
超类:
public class PanelItem
{
private Image img;
protected int xCoord;
protected int yCoord;
protected int width;
protected int height;
//constructor
public SceneItem( String path, int x, int y, int w int h )
{
xCoord = x;
yCoord = y;
setImage( path, w, h );
}
public void SetImage( String path, int w, int h )
{
width = w;
height = h;
img = ImageIO.read(new File(path));
}
//to be Overriden
public void update( int width, int height )
{
}
}
子类:
public class MovingPanelItem extends PanelItem
{
private int xStep, yStep;
// x & y correspond to the coordinate plane
// w & h correspond to image width and height
// xs & ys correspond to unique randomized 'steps' in the for the x and y values
public MovingSceneItem(String path, int x, int y, int w, int h, int xs, int ys)
{
super( path, x, y, w, h);
setxStep(xs);
setyStep(ys);
update( x, y );
}
@Override
public void update( int x, int y )
{
this.xCoord = x + getxStep();
this.yCoord = y + getyStep();
}
}
(回应鳗鱼) 面板/窗口本身包含在以下类中:
public class Panel extends JPanel {
protected ArrayList<PanelItem> panelItems;
private JLabel statusLabel;
private long randomSeed;
private Random random;
public Panel(JLabel sl) {
panelItems = new ArrayList<PanelItem>();
statusLabel = sl;
random = new Random();
randomSeed = 100;
}
private void addPanel() {
addPanelItems(10, "Mouse");
}
private void addPanelItems(int num, String type) {
Dimension dim = getSize();
dim.setSize(dim.getWidth() - 30, dim.getHeight() - 30);
synchronized (panelItems) {
for (int i = 0; i < num; i++) {
int x = random.nextInt(dim.width);
int y = random.nextInt(dim.height);
if (type.equals("Person")) {
int xs = random.nextInt(21) - 10;
int ys = random.nextInt(21) - 10;
panelItems.add(new Mouse(x, y, xs, ys));
}
}
repaint();
}
// causes every item to get updated.
public void updatePanel() {
Dimension dim = getSize();
synchronized (panelItems) {
for (PanelItem pi : panelItems) {
pi.update(dim.width, dim.height);
}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
synchronized (panelItems) {
for (PanelItem pi : panelItems) {
pi.draw(g);
}
}
}
}
测试类中的KeyListener类:
private class MyKeyListener extends KeyAdapter
{
@Override public void keyTyped(KeyEvent e)
{
if(e.getKeyChar() == 'f') {
panel.updatePanel();
panel.repaint();
}
// other key events include reseting the panel &
// creating a new panel, both of which are working.
}
}
在上面的代码中,我允许更改的唯一代码(以及我编写的唯一代码)是子类MovingPanel项。