danny 2007-12-7 10:18
java自訂滑鼠游標
在java裡要自訂游標是件輕而易舉之事.
只要在元件裡設定一個游標物件就可以了.
這聽起來很簡單,實作起來也的確是很簡單.
只有Component.setCursor(Cursor)這個單純的游標設定指令而已.
也就是說,你只要建個游標(Cursor)物件,再把物件指定給元件
滑鼠游標就這樣輕而易舉的被置換過來了.
底下我們用個小範例來示範如何如用圖檔來建個影像游標.
程式只是單純的在button事件中指定了一個元件的Cursor物件而己.
只要按一下button.TextArea元件的游標就換成了Remond的大頭照了.
想玩玩這個範例程式的效果,請執行以下 Java Web Start
範例程式碼實作如下:
代碼:[code]import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Test extends JFrame{
private Cursor cusTand,cusRemond;
private JButton btn,btnRemond,btnTand;
private JTextArea ta;
public static void main(String[] args) {
new Test();
}
public Test() {
btn = new JButton("Normal");
btnRemond = new JButton("Remond");
btnTand = new JButton("Tand");
ta = new JTextArea(10,20);
Image TandImg= new ImageIcon(getClass().getResource("tand.gif")).getImage();
Image RemondImg= new ImageIcon(getClass().getResource("remond.jpg")).getImage();
cusTand = this.getToolkit().createCustomCursor(TandImg,new Point(16,16),"Tand");
cusRemond = this.getToolkit().createCustomCursor(RemondImg,new Point(16,16),"Tand");
Container c = getContentPane();
JPanel jp = new JPanel();
jp.add(btn);
jp.add(btnRemond);
jp.add(btnTand);
c.add(jp,BorderLayout.SOUTH);
c.add(ta,BorderLayout.CENTER);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Performed(e);
}
});
btnRemond.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Performed(e);
}
});
btnTand.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Performed(e);
}
});
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void Performed(ActionEvent e){
Object obj = e.getSource();
if(obj==btnRemond)
ta.setCursor(cusRemond);
else if(obj==btnTand)
ta.setCursor(cusTand);
else
ta.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
} [/code]