Java JButton 实现完全透明按钮

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Main extends JFrame {

	private JPanel contentPane;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Main frame = new Main();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public Main() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		ImageIcon icon=new ImageIcon("a1.png");
		
		JButton button = new JButton("我是按钮",icon);
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
//				点击后变为红色
				button.setForeground(Color.red);
			}
		});
		button.setBounds(152, 116, 200, 50);
        // 以下是隐藏按钮各属性的设置,根据实际需求自己取舍
		button.setMargin(new Insets(0,0,0,0));//将边框外的上下左右空间设置为0  
        button.setIconTextGap(0);//将标签中显示的文本和图标之间的间隔量设置为0  
        button.setBorderPainted(false);//不打印边框  
        button.setBorder(null);//除去边框  
//        button.setText(null);//除去按钮的默认名称  
        button.setFocusPainted(false);//除去焦点的框  
        button.setContentAreaFilled(false);//除去默认的背景填充 
		contentPane.add(button);
	}
}

效果对比:

  • 9
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值