JavaSwing学习日记(四)
JButton(按钮)
以及监听事件的创建
在日常的开发中,会经常的需要按钮为我们提交点击事件,在这里,我将会把JButton的使用方法写下来,以供后续使用
1、按钮的创建
//创建一个没有设置文本或图标的按钮。
JButton btn = new JButton();
//创建一个带有图标的按钮。
JButton btn = new JButton(Icon icon);
//创建一个带文本的按钮。
JButton btn = new JButton(String text);
2、为按钮提供点击事件监听器
/*
使用addActionListener(ActionListener l)方法为jButton(按钮)添加监听事件
实现addActionListener里的参数接口ActionListener,重写ActionListener接口的actionPerformed方法
如果发生了点击事件,系统将会回调actionPerformed方法
*/
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
}
});
说明:其他的控件大部分都可以添加事件监听器,并不是独按钮一份
按钮例子
package test.demo05;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* @author 13537
*/
public class JTextFied {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(()->{
JFrame jFrame = new JFrame("标题");
Container container = jFrame.getContentPane();
container.setLayout(new FlowLayout());
JButton jButton = new JButton("确定");
/*
使用addActionListener(ActionListener l)方法为jButton(按钮)添加监听事件
实现addActionListener里的参数接口ActionListener,重写ActionListener接口的actionPerformed方法
如果发生了点击事件,系统将会回调actionPerformed方法
*/
jButton.addActionListener((actionEvent -> {
System.out.println("我点击了按钮");
}));
container.add(new JLabel("请输入"));
container.add(jButton);
jFrame.setSize(300,300);
jFrame.setVisible(true);
});
}
}
实现效果