本篇文章将会教会大家JButton常用的使用方法
JButton是Swing的组件所以需要导入包
import javax.swing.*;
1创建JButton
//创建JButton
JButton jButton = new JButton();
//将JButton添加到面板里
jPanel.add(jButton);
2设置JButton大小以及坐标
//设置JButton大小
jButton.setSize(200,50);
//设置JButton坐标
jButton.setLocation(325,210);
3JButton设置默认,点燃,不可用时图片
//导入常态
ImageIcon A = new ImageIcon("src/image/1.png");
//导入点燃图片
ImageIcon B = new ImageIcon("src/image/2.png");
//导入禁止使用图片
ImageIcon C = new ImageIcon("src/image/3.png");
//设置按钮图片
jButton.setIcon(A);
//设置按钮点燃图片
jButton.setPressedIcon(B);
//设置按钮不可用时图片
jButton.setDisabledIcon(C);
去除边框可以让JButton更加的好看
//去除按钮边框
jButton.setBorderPainted(false);
4JButton背景颜色
//设置背景颜色
jButton.setBackground(Color.LIGHT_GRAY);
5JButton是否可用
//设置按钮是否可用
jButton.setEnabled(false);
6JButton注册事件
//需先导入包
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//注册事件
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("按钮被点击了");
}
});
以上时JButton常见的使用方法,如有遗漏请在评论区补充!