製作圓形Swing按鈕(中文版) (轉)

worldblog發表於2007-12-10
製作圓形Swing按鈕(中文版) (轉)[@more@]

  這是一個關於製作圓形按鈕的技巧。事實上,這個技巧中的知識方便的適用於任何形狀的按鈕,但我們只作一個圓形的按鈕。當你製作一個圓形的按鈕時,需要做兩件事。第一件事是過載一個適當的繪畫方法以畫出一個圓形。第二件事是設定一些事件使得只有當你點選圓形按鈕的範圍中的時侯按鈕才會作出響應(不是包含圓形按鈕的矩形的範圍中)。

下面是一個實現了圓形按鈕的例程:

 
import .awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class Rounutton extends JButton {
  public RoundButton(String label) {
  super(label);

// 這些宣告把按鈕擴充套件為一個圓而不是一個橢圓。
  Dimension size = getPreferredSize();
  size.width = size.height = Math.max(size.width,
  size.height);
  setPreferredSize(size);


//這個使JButton不畫背景,而允許我們畫一個圓的背景。
  setContentAreaFilled(false);
  }

// 畫圓的背景和標籤
  protected void paintComponent(Graphics g) {
  if (getModel().isArmed()) {

// 你可以選一個高亮的顏色作為圓形按鈕類的屬性
  g.setColor(Color.lightGray);
  } else {
  g.setColor(getBackground());
  }
  g.fillOval(0, 0, getSize().width-1,
  getSize().height-1);

//這個呼叫會畫一個標籤和焦點矩形。
  super.paintComponent(g);
  }


// 用簡單的弧畫按鈕的邊界。
  protected void paintBorder(Graphics g) {
  g.setColor(getForeground());
  g.drawOval(0, 0, getSize().width-1,
  getSize().height-1);
  }


// 偵測點選事件
  Shape shape;
  public boolean contains(int x, int y) {

// 如果按鈕改變大小,產生一個新的形狀。
  if (shape == null ||
  !shape.getBounds().equals(getBounds())) {
  shape = new Ellipse2D.Float(0, 0,
  getWidth(), getHeight());
  }
  return shape.contains(x, y);
  }

// 測試
  public static void main(String[] args) {
// 產生一個帶‘Jackpot’標籤的按鈕。 
  JButton button = new RoundButton("Jackpot");
  button.setBackground(Color.green);

// 產生一個以顯示這個按鈕。
  JFrame frame = new JFrame();
  frame.getContentPane().setBackground(Color.yellow);
  frame.getContentPane().add(button);
  frame.getContentPane().setLayout(new FlowLayout());
  frame.setSize(150, 150);
  frame.setVisible(true);
  }
}

  由於我們想保留JButton的大部分功能,我們讓RoundButton類繼承了JButton類。在RoundButton的構造方法中,setContentAreaFilled()方法被呼叫。這就讓按鈕畫了一個矩形的焦點區,但不畫背景。

現在我們需要畫一個圓的背景。這是透過過載paintComponent()方法實現的。那個方法使用Graphics.fillOval()方法畫一個實心的圓。然後paintComponent()方法呼叫super.paintComponent()在這個實心圓的上面畫了一個標籤。

這個例子還過載了paintBorder()方法以在圓形按鈕的邊界上畫一個邊。如果你不想要邊框,你也可以不過載這個方法。這個方法呼叫了Graphics.drawOval()方法以在圓的邊界上畫一個細的邊框。

注意:在TM 1.2.2中,當你將滑鼠拖進或拖出按鈕的範圍時,JButton的行為有一個小。理論上,當你在圓形按鈕上點選滑鼠然後拖動滑鼠離開按鈕的邊界時,按鈕應該改變它的外形。當你拖動滑鼠進入按鈕的邊界內時,按鈕應回覆它的外形。不幸的是,包含這個行為的程式碼不能呼叫contains()方法。代替它的是隻使用按鈕的‘限制範圍’(這是包含按鈕的最小矩形範圍)注意,如果你在圓形邊界內輕微的拖動滑鼠,也就是說離開圓形的範圍但不離開邊界,按鈕將不會改變它的外形。

 


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752043/viewspace-990937/,如需轉載,請註明出處,否則將追究法律責任。

相關文章