如何通过JButton去触发事件?

来源:百度知道 编辑:UC知道 时间:2024/06/05 01:09:15
在一个面板上 点击jbutton去触发猜数游戏,是怎么做

JButton j= new JButton("whatever");//声明 j ,一个jbutton
j.addActionListener(this); //在后面监听 j

public void actionPerformed(ActionEvent e){
if(e.getSource()==j){
……}
} // 这是事件的函数

较具体的代码:这只是精简的,图形界面没有具体设置,兄弟你自己研究图形界面的类吧
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class any extends JFrame implements ActionListener{
private JButton bottom;
public any() {
bottom=new JButton("猜数游戏");
getContentPane().add(bottom);//在面板上添加按钮
bottom.addActionListener(this);//给bottom注册监听
}
//main方法
public static void main (String[] args) {
any example= new any();
example.setSize(200,200);
example.setTitle("猜数字");
example.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
example.setVisible(true);
}
//事件处理
public void actionPerformed(ActionEven