import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Rectangle2D;
import javax.swing.*;
/**
* @version 1.0.2 2010-04-08
* @author liangdong HIT
*/
public class MoveTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
MoveFrame frame = new MoveFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
/**
* frame
*/
class MoveFrame extends JFrame
{
/**
* cancel warning
*/
private static final long serialVersionUID = 1L;
public MoveFrame()
{
setTitle("MoveTest");
setBounds(STARTX, STARTY, DEFAULT_WIDTH, DEFAULT_HEIGHT);
MovePanel panel = new MovePanel();
add(panel);
}
public static final int STARTX=100;
public static final int STARTY=100;
public static final int DEFAULT_WIDTH=800;
public static final int DEFAULT_HEIGHT=600;
}
/**
* panel
*/
class MovePanel extends JPanel
{
/**
* cancel warning
*/
private static final long serialVersionUID = 1L;
public MovePanel()
{
setLayout(new BorderLayout());
Action insert = new MoveAction();
x1=100;
y1=100;
x2=540;
y2=460;
choice = 1;
lu=new Rectangle2D.Double(x1,y1,40,40);
wu=new Rectangle2D.Double(x2,y2,40,40);
InputMap imap = this.getInputMap();
imap.put(KeyStroke.getKeyStroke('1'),"rr");
imap.put(KeyStroke.getKeyStroke('2'),"rb");
imap.put(KeyStroke.getKeyStroke('w'),"up");
imap.put(KeyStroke.getKeyStroke('s'),"down");
imap.put(KeyStroke.getKeyStroke('a'),"left");
imap.put(KeyStroke.getKeyStroke('d'),"right");
ActionMap amap= this.getActionMap();
amap.put("rr", insert);
amap.put("rb", insert);
amap.put("up", insert);
amap.put("down", insert);
amap.put("left", insert);
amap.put("right", insert);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.RED);
g2.fill(lu);
g2.setColor(Color.BLACK);
g2.fill(wu);
}
private class MoveAction extends AbstractAction {
/**
* cancel warning
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent event) {
String input = event.getActionCommand();
if (input.equals("1"))
choice = 1;
else if (input.equals("2"))
choice = 2;
if (choice==1) {
if (input.equals("w") && y1 > 100)
y1 = y1 - 40;
else if (input.equals("s") && y1 < 450)
y1 = y1 + 40;
else if (input.equals("a") && x1 > 100)
x1 = x1 - 40;
else if (input.equals("d") && x1 < 540)
x1 = x1 + 40;
lu.setRect(x1, y1, 40, 40);
repaint();
} else if(choice == 2) {
if (input.equals("w") && y2 > 100)
y2 = y2 - 40;
else if (input.equals("s") && y2 < 460)
y2 = y2 + 40;
else if (input.equals("a") && x2 > 100)
x2 = x2 - 40;
else if (input.equals("d") && x2 < 540)
x2 = x2 + 40;
wu.setRect(x2, y2, 40, 40);
repaint();
}
}
}
private Rectangle2D lu;
private Rectangle2D wu;
private int choice;
private double x1;
private double y1;
private double x2;
private double y2;
}