gpt4 book ai didi

java - 如何访问按钮的每个单独的 ActionPerformed?

转载 作者:行者123 更新时间:2023-12-02 00:31:04 27 4
gpt4 key购买 nike

我要感谢 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();
}

}

最佳答案

由于您使用 1 个带有 2 个按钮的操作监听器类,因此您必须有一种方法来判断按下了哪个按钮。您可以在 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
}
});

关于java - 如何访问按钮的每个单独的 ActionPerformed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9073820/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com