Java --UI添加事件

mac2022-06-30  21

用Java实现按钮添加事件:

package HandEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class EventDemo extends JFrame { JPanel jp; JButton jb; public EventDemo() { jp=new JPanel(); jb=new JButton("click me"); add(jp); jp.add(jb); setSize(200,200); setVisible(true); //shixian sx=new shixian();//该类充当监视器 jb.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { System.out.print( "Let me give you a surprise.\n"); } }); // sx是实现类的对象 } public static void main(String args[]) { EventDemo ed=new EventDemo(); } }

运行后出现如下界面:

点击按钮“click me ”之后,在下面的运行结果框中出现“Let  me give you a surprise.”字样。点击一次 按钮 出现一次该字样。

以上是方法一,还有另外一种方法。

重新在下面创建一个class类:

package HandEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class Testing extends JFrame { JPanel jp; JButton jb; public Testing() { jp=new JPanel(); jb=new JButton("click me"); add(jp); jp.add(jb); setSize(200,200); setVisible(true); shixian sx=new shixian();//该类充当监视器 jb.addActionListener(new shixian()); // sx是实现类的对象 } public static void main(String args[]) { Testing ed=new Testing(); } } class shixian implements ActionListener{ public void actionPerformed(ActionEvent arg0) { System.out.print( "Let me give you a surprise.\n"); } }

也能实现上面功能,但此方法并不推荐。

 

转载于:https://www.cnblogs.com/Catherinezhilin/p/7955972.html

最新回复(0)