java做的圓角矩形按鈕

來源:互聯網
上載者:User

                                     

 

 

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Shape;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.RoundRectangle2D;

import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;

public class MyButton extends JButton implements MouseListener {
 private Shape shape = null;

 private Color click = new Color(0, 0, 113);// 按下時的顏色

 private Color quit = new Color(237, 234, 228);// 離開時顏色

 public MyButton(String s) {
  super(s);
  addMouseListener(this);
  setContentAreaFilled(false);// 是否顯示外圍矩形地區 選否
 }

 public MyButton() {
  super();
  addMouseListener(this);
 }

 public MyButton(String text, Icon icon) {
  super(text, icon);
  addMouseListener(this);
 }

 public MyButton(Icon icon) {
  super(icon);
  addMouseListener(this);
 }

 public void setColor(Color c, Color q) {
  click = c;
  quit = q;
 }

 public void mouseClicked(MouseEvent e) {
  System.out.println("mouseClicked");
 }

 public void mousePressed(MouseEvent e) {
  System.out.println("mousePressed");
 }

 public void mouseReleased(MouseEvent e) {
  System.out.println("mouseReleased");
 }

 public void mouseExited(MouseEvent e) {
  System.out.println("mouseExited");
 }

 public void mouseEntered(MouseEvent e) {
  System.out.println("mouseEntered");
 }

 public void paintComponent(Graphics g) {
  //如果按下則為CLICK色 否則為 QUIT色
  if (getModel().isArmed()) {
   g.setColor(click);
  } else {
   g.setColor(quit);
  }
  //填充圓角矩形地區 也可以為其它的圖形
  g
    .fillRoundRect(0, 0, getSize().width - 1, getSize().height - 1,
      20, 20);
  //必須放在最後 否則畫不出來
  super.paintComponent(g);
 }

 public void paintBorder(Graphics g) {
  //畫邊界地區
  g.setColor(click);
  g
    .drawRoundRect(0, 0, getSize().width - 1, getSize().height - 1,
      20, 20);
 }

 public boolean contains(int x, int y) {
  //判斷點(x,y)是否在按鈕內
  if (shape == null || !(shape.getBounds().equals(getBounds()))) {
   shape = new RoundRectangle2D.Float(0, 0, getWidth(), getHeight(),
     20, 20);
  }
  return shape.contains(x, y);
 }

 public static void main(String[] argv) {
  JFrame f = new JFrame();
  f.setSize(400, 300);

  MyButton btn = new MyButton("button");

  f.getContentPane().add(btn, BorderLayout.NORTH);
  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  f.setVisible(true);
 }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.