例如,我一直想让我的按键事件在每次使用JLabel
时都做不同的事情,例如:第一次按右键将标签中的图像更改为一件事,而下一次按下右键将图像更改为其他图像,依此类推。
这是我的代码:
Movement
类:
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.*;
import javax.swing.*;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import javax.swing.Timer;
public class Movement
{
public JLabel jt;
public InputMap ip;
public ActionMap ap;
public String comm;
public KeyStroke key;
public int movement;
public Movement(JLabel jt, InputMap ip,ActionMap ap, String comm,KeyStroke key)
{
this.jt = jt;
this.ip = ip;
this.ap= ap;
this.comm = comm;
this.key = key;
}
public void newAction()
{
this.ip = this.jt.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
this.ip.put(key, comm);
this.ap = this.jt.getActionMap();
this.ap.put(this.comm, new AbstractAction()
{
public void actionPerformed(ActionEvent arg0)
{
int x = jt.getX();
int y = jt.getY();
if(key == KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0))
{
if(x==jt.getX()){
jt.setIcon(new ImageIcon("C:\\Users\\leguy\\OneDrive\\Desktop\\Stuff\\walksp2.png"));
jt.setAlignmentX(jt.getAlignmentX()+5);
}
if(x==jt.getX()+5){
jt.setIcon(new ImageIcon("C:\\Users\\leguy\\OneDrive\\Desktop\\Stuff\\walksp3.png"));
}
else{
System.out.println("hey2");
}
}
}
});
}
}
Walk
类:
import java.awt.*;
import java.awt.peer.FileDialogPeer;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.beans.PropertyChangeListener;
import java.net.MalformedURLException;
import java.net.URL;
public class Walk
{
public static void main(String[] args)
{
JFrame f = new JFrame("Study");
JPanel p = new JPanel();
p.setLayout(null);
p.setBackground(Color.white);
f.setSize(3000,1000);
f.setContentPane(p);
String path = new String("C:\\Users\\leguy\\OneDrive\\Desktop\\Stuff\\stillsp.png");
JLabel testl = new JLabel(new ImageIcon("C:\\Users\\leguy\\OneDrive\\Desktop\\Stuff\\stillsp.png"));
testl.setSize(500, 500);
testl.setLocation(500,500);
p.add(testl);
Movement moveRight = new Movement(testl, new InputMap(), new ActionMap(), "move Right",KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0));
moveRight.newAction();
f.setVisible(true);
}
}
主要方法^