java 去按钮边框及焦点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37614259/article/details/72854547
JButton jb;
//去焦点
jb.setFocusPainted(false);
//去边框
jb.setBorderPainted(false);


效果图



按钮内部类,重绘按钮



import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

import javax.swing.*;

public class Test1 extends JFrame{
	int x,y,xx,yy;
	boolean isDraging;
	public static void main(String[] args) {
		
		new Test1();
	}
	
	Test1(){
	MyButton jb = new MyButton();
	
	this.add(jb);
		this.setSize(400, 400);
		//this.setLocationRelativeTo(null);
		int windowWidth = this.getWidth(); //获得窗口宽
		int windowHeight = this.getHeight(); //获得窗口高
		Toolkit kit = Toolkit.getDefaultToolkit(); //定义工具包
		Dimension screenSize = kit.getScreenSize(); //获取屏幕的尺寸
		int screenWidth = screenSize.width; //获取屏幕的宽
		int screenHeight = screenSize.height; //获取屏幕的高
		this.setLocation(screenWidth/2-windowWidth/2, screenHeight/2-windowHeight/2);//设置窗口居中显示
	
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
		
		//窗口拖动
		 this.addMouseListener(new MouseAdapter() {
			    public void mousePressed(MouseEvent e) {
					isDraging = true; 
					xx = e.getX();
					yy = e.getY();
			    }
			   public void mouseReleased(MouseEvent e) {
				   	isDraging = false;
			    }
		 		});
		 
		 this.addMouseMotionListener(new MouseMotionAdapter() {
			    public void mouseDragged(MouseEvent e) {
			    	if (isDraging) {
					int left = getLocation().x;
					int top = getLocation().y;
					setLocation(left + e.getX() - xx, top + e.getY() - yy);
			    	}
			    }
		 		});
	
	}
	
	}
	
	 
class MyButton extends JButton {
    private static final long serialVersionUID = 1965063150601339314L;
 
    public MyButton() {
        super();
        setOpaque(false);
        setContentAreaFilled(false); // 这一句非常重要, 否则父类还会绘制按钮的区域.
    }
 
    @Override
    protected void paintComponent(Graphics g) {
        int width = this.getWidth();
        int height = this.getHeight();
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//      设置画笔颜色
        g2d.setColor(Color.GREEN);
//      画矩形
//      g.draw3DRect(10, 10, 50, 50, false);
//      g2d.fillRoundRect(0, 0, width, height, 20, 20);
//		 画图片
        g.drawImage(new ImageIcon("Test_Img/background.jpg").getImage(), 0, 0, 100,30,this);//this代指JPanel本身,意思是把图片放这上面  		 
        super.paintComponent(g); // 最后调用这个方法, 让父类绘制在按钮上绘制文字.
    }
}




展开阅读全文

没有更多推荐了,返回首页