1 简单叙述制作过程
(1)导入相应组件
import javax.swing.JButton;//导入按钮容器组件
import javax.swing.JFrame;//导入窗口界面组件
import javax.swing.JPanel;//面板容器组件
import java.awt.event.ActionEvent;//事件处理组件
import java.awt.event.ActionListener;//监听器组件
(2)类及方法的介绍
//JFrame是一个窗口类,构造方法初始化
JFrame frame = new JFrame("Swing");
//关闭窗口设置时,退出整个程序
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//添加面板
JPanel panle = new JPanel();
frame.setContentPane(panle);
//窗口设计
frame.setSize(600,400);
//显示窗口
frame.setVisible(true);
(3)监听事件处理
public class Myframe extends JFrame {
public Myframe(String title) {
super(title);
JPanel panel = new JPanel();
this.setContentPane(panel);
JButton button = new JButton("点击");
panel.add(button);
//创建监听事件实例
MyActionListener listener = new MyActionListener();
button.addActionListener(listener);
}
// 定义内部类
private class MyActionListener implements ActionListener {
@Override
//创建事件处理方法
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("Hallo!");
}
}
}
2 代码展示
事件触发的关键代码
package com.weh.my;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Myframe extends JFrame {
public Myframe(String title) {
super(title);
JPanel panel = new JPanel();
this.setContentPane(panel);
JButton button = new JButton("点击");
panel.add(button);
//创建监听事件实例
MyActionListener listener = new MyActionListener();
button.addActionListener(listener);
}
// 定义内部类
private class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("Hallo!");
}
}
}
测试
package com.weh.my;
import javax.swing.JButton;//导入按钮容器组件
import javax.swing.JFrame;//导入窗口界面容器组件
import javax.swing.JLabel;//文本组件
import javax.swing.JPanel;//面板
public class Test3 {
public static void main(String[] args) {
// JFrame是一个窗口类,构造方法初始化
// frame.setTitle("Swing");//标题
Myframe test = new Myframe("Swing");
// 关闭窗口设置时,退出整个程序
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 窗口设计
test.setSize(600, 400);
// 显示窗口
test.setVisible(true);
}
}
3 效果展示
博主后记:
希望看到此篇博文的网友,如果发现有什么不对的地方,欢迎在下方留言指正!博主一定虚心接受并改正!大家一起共同进步。如果对你有所帮助,可以给博主一个赞👍。