1. 程式人生 > >java 去按鈕邊框及焦點

java 去按鈕邊框及焦點

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); // 最後呼叫這個方法, 讓父類繪製在按鈕上繪製文字.
    }
}