addPointerPressed和addActionListener是两种不同的事件监听方式,针对不同的用户交互动作。
示例代码:
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;
public class PointerPressedExample extends MIDlet {
private Display display;
private Canvas canvas;
public PointerPressedExample() {
display = Display.getDisplay(this);
canvas = new Canvas() {
protected void paint(Graphics g) {
g.drawString("Press the screen", getWidth() / 2, getHeight() / 2, Graphics.HCENTER | Graphics.BASELINE);
}
protected void pointerPressed(int x, int y) {
// 处理按下动作
System.out.println("Pressed at: " + x + ", " + y);
}
};
}
protected void startApp() {
display.setCurrent(canvas);
}
protected void pauseApp() {
}
protected void destroyApp(boolean unconditional) {
}
}
示例代码:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ActionListenerExample {
public static void main(String[] args) {
JFrame frame = new JFrame("ActionListener Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("No button clicked");
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 处理按钮点击事件
label.setText("Button clicked");
}
});
frame.getContentPane().add(label);
frame.getContentPane().add(button);
frame.pack();
frame.setVisible(true);
}
}
总结: