下面是我无法修复bug的代码。我无法正确使用箭头键移动对象。每当我使用箭头键在屏幕上移动对象时,它会移动几个像素然后停止。钥匙停止工作。我正在使用eclipse编译器。 非常感谢帮助。 谢谢!
import acm.program.*;
import acm.graphics.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Ch10_Ex06_Draw_Star_Additions extends GraphicsProgram
{
public void init ()
{
slider = new JSlider (1, 150, 30);
box = new JComboBox ();
box.addItem ("White");
box.addItem ("Black");
box.addItem ("Red");
box.addItem ("Green");
box.addItem ("Blue");
box.addItem ("Orange");
box.addItem ("Yellow");
box.setEditable (false);
box.setSelectedItem ("White");
textField = new JTextField (20);
textField.addActionListener (this);
add (new JLabel ("Small"), SOUTH);
add (slider, SOUTH);
add (new JLabel ("Large"), SOUTH);
add (new JButton ("Clear"), SOUTH);
add (new JLabel ("Text"), SOUTH);
add (textField, SOUTH);
add (box, SOUTH);
setBackground (Color.LIGHT_GRAY);
addActionListeners ();
addKeyListeners ();
addMouseListeners ();
}
public void keyPressed (KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_DELETE)
removeAll ();
gobj = getElementAt (X, Y);
if (gobj != null)
{
switch (e.getKeyCode ())
{
case KeyEvent.VK_UP: gobj.move(0, -5); break;
case KeyEvent.VK_DOWN: gobj.move(0, +5); break;
case KeyEvent.VK_LEFT: gobj.move(-5, 0); break;
case KeyEvent.VK_RIGHT: gobj.move(+5, 0); break;
}
}
}
public void mouseClicked (MouseEvent e)
{
X = e.getX();
Y = e.getY();
star = new GStar (slider.getValue());
star.setFilled (true);
star.setColor (getCurrentColor());
star.setFillColor (getCurrentColor());
add (star, e.getX(), e.getY());
}
public void mousePressed (MouseEvent e)
{
point = new GPoint (e.getPoint());
gobj = getElementAt (point);
}
public void mouseDragged (MouseEvent e)
{
if (gobj != null)
{
gobj.move (e.getX() - point.getX(), e.getY() - point.getY());
point = new GPoint (e.getPoint());
}
}
public void actionPerformed (ActionEvent e)
{
if (e.getActionCommand() == "Clear")
removeAll ();
if (e.getSource() == textField)
{
GLabel label = new GLabel (textField.getText());
String str = "Arial-" + slider.getValue() / 2;
label.setColor (getCurrentColor());
label.setFont(str);
add (label, X + star.getWidth() , Y + star.getHeight()/4);
}
}
private Color getCurrentColor()
{
String name = (String) box.getSelectedItem();
if (name == "Red") return Color.RED;
else if (name == "Green") return Color.GREEN;
else if (name == "Blue") return Color.BLUE;
else if (name == "Orange") return Color.ORANGE;
else if (name == "Yellow") return Color.YELLOW;
else if (name == "Black") return Color.BLACK;
else return Color.WHITE;
}
private JTextField textField;
private JSlider slider;
private JComboBox box;
private GObject gobj;
private GPoint point;
private GStar star;
private int X, Y;
}
答案 0 :(得分:0)
你的物体正在移开,超出了" X"和" Y"只有在单击对象时才会获得。您应该在点击成员变量(例如,selectedObject)期间保存getElementAt(X,Y)返回的对象,然后使用它来移动它。