我要感谢Andrew Thompson帮助我在代码中做到这一点。 如何访问每个按钮的actionPerformed监听器?
代码应根据您按下的按钮移动屏幕上的“球”。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Lab2a extends JFrame {
Lab2a(){
setTitle("Lab 1b - Application #2");
Lab2Panel p = new Lab2Panel();
add(p);
}
public static void main(String[] args){
Lab2 frame = new Lab2();
frame.setTitle("Lab2 Application # 1");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.setVisible(true);
}
}
class Lab2Panel extends JPanel{
Lab2Button canvas = new Lab2Button();
JPanel panel = new JPanel();
Lab2Panel () {
setLayout(new BorderLayout());
JButton leftButton = new JButton("left");
JButton rightButton = new JButton("right");
JButton upButton = new JButton("up");
JButton downButton = new JButton("down");
panel.add(leftButton);
panel.add(rightButton);
panel.add(upButton);
panel.add(downButton);
this.add(canvas, BorderLayout.CENTER);
this.add(panel, BorderLayout.SOUTH);
leftButton.addActionListener(new Lab2MoveBallListener(canvas));
rightButton.addActionListener(new Lab2MoveBallListener(canvas));
}
}
class Lab2Button extends JPanel {
int radius = 5;
int x = -1;
int y = -1;
protected void paintComponent(Graphics g){
if (x<0 || y<0) {
x = getWidth() / 2 - radius;
y = getHeight() / 2 - radius;
}
super.paintComponent(g);
g.drawOval(x,y, 2 * radius, 2 * radius);
}
public void moveLeft(){
x -= 5;
this.repaint();
}
public void moveRight(){
x += 5;
this.repaint();
}
public void moveUp(){
y += 5;
this.repaint();
}
public void moveDown(){
y -= 5;
this.repaint();
}
}
class Lab2MoveBallListener implements ActionListener{
private Lab2Button canvas;
Lab2MoveBallListener(Lab2Button canvas) {
this.canvas = canvas;
}
public void actionPerformed(ActionEvent e){
canvas.moveLeft();
}
}
答案 0 :(得分:2)
由于您正在使用带有2个按钮的1个动作侦听器类,因此您必须有一种方法来判断按下了哪个按钮。你可以在actionPerformed方法中尝试这样的东西:
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().matches("left"))
System.out.print("left button pressed");
else if(e.getActionCommand().matches("right"))
System.out.print("right button pressed");
}
另一种方法是通过这样做来创建一个匿名类:
buttonLeft.addActionListener(new ActionListener(){
public void actionPerformed(){
//left button code
}
});
buttonRight.addActionListener(new ActionListener(){
public void actionPerformed(){
//right button code
}
});
答案 1 :(得分:1)
在ActionListener的actionPerformed(...)
方法中,您可以获取通过ActionEvent的getActionCommand()
方法按下的按钮文本。
试试看结果:
public void actionPerformed(ActionEvent e){
String actionCommand = e.getActionCommand();
System.out.println("actionCommand is: " + actionCommand);
}
现在你可以在这个方法中使用这些信息,而不仅仅是写出标准输出,但我会让你弄清楚其余的。