问题:在使用ActionListener时,可能会遇到以下问题:
解决方法:
示例代码:
import java.awt.*;
import java.awt.event.*;
public class MyFrame extends Frame implements ActionListener {
private Button btn1;
private Button btn2;
public MyFrame() {
btn1 = new Button("Button 1");
btn2 = new Button("Button 2");
btn1.addActionListener(this);
btn2.addActionListener(this);
// 添加按钮到窗体
add(btn1);
add(btn2);
// 设置窗体布局和大小
setLayout(new FlowLayout());
setSize(300, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn1) {
// 处理按钮1的点击事件
System.out.println("Button 1 clicked");
} else if (e.getSource() == btn2) {
// 处理按钮2的点击事件
System.out.println("Button 2 clicked");
}
}
public static void main(String[] args) {
new MyFrame();
}
}
示例代码:
import java.awt.*;
import java.awt.event.*;
public class MyFrame extends Frame {
private Button btn1;
private Button btn2;
public MyFrame() {
btn1 = new Button("Button 1");
btn2 = new Button("Button 2");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 处理按钮1的点击事件
System.out.println("Button 1 clicked");
}
});
btn2.addActionListener(e -> {
// 处理按钮2的点击事件
System.out.println("Button 2 clicked");
});
// 添加按钮到窗体
add(btn1);
add(btn2);
// 设置窗体布局和大小
setLayout(new FlowLayout());
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new MyFrame();
}
}
示例代码:
import java.awt.*;
import java.awt.event.*;
public class MyFrame extends Frame {
private Button btn1;
private Button btn2;
public MyFrame() {
btn1 = new Button("Button 1");
btn2 = new Button("Button 2");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 处理按钮1的点击事件
System.out.println("Button 1 clicked");
}
});
btn2.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// 处理按钮2的鼠标点击事件
System.out.println("Button 2 clicked");
}
});
// 添加按钮到窗体
add(btn1);
add(btn2);
// 设置窗体布局和大小
setLayout(new FlowLayout());
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new MyFrame();
}
}