java GUI(滑鼠鍵盤事件)

來源:互聯網
上載者:User

標籤:滑鼠鍵盤事件

/*
 * 
 */
import java.awt.*;
import java.awt.event.*;
public class MouseAndEvent {

private Frame f;
private Button but;
private TextField tf;
MouseAndEvent()
{
init();
}
//對圖形化介面進行初始化。
public void init()
{
f=new Frame("my frame");
//對frame進行基本設定,該方法包含setsize和setlocation.
f.setBounds(200,200,400,300);
f.setLayout(new FlowLayout());
//定義文字框對象,指定列數。
tf=new TextField(10);
but=new Button("my button");
//在顯示表單之前,添加一個文字框。
f.add(tf);
//將組建添加到frame中
f.add(but);
//顯示表單之前,載入一下表單上的事件。
myEvent();
//顯示表單
f.setVisible(true);
}
private void myEvent()
{
//為表單添加監聽器
f.addWindowListener(new WindowAdapter() {
public void windowClosing (WindowEvent e)
{
System.exit(0);
}
});
//為按鈕添加活動事件。
but.addActionListener(new ActionListener() {


public void actionPerformed(ActionEvent e) {
System.out.println("action activity");

}
});
//為按鈕添加滑鼠事件。
but.addMouseListener(new MouseAdapter() {
//滑鼠進入按鈕事件
int count=0;
int clikcount=0;
public void mouseEntered(MouseEvent e)
{
System.out.println("滑鼠進入該組件"+count++);
}
public void mouseClicked(MouseEvent e)
{
//擷取滑鼠點擊次數,實現雙擊
if(e.getClickCount()==2)
System.out.println("雙擊組件"+clikcount++);
}
});
//為but添加鍵盤事件。
but.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
//KeyCode()列印鍵名,KeyChar()列印鍵所對應的碼。
//getKsyText根據鍵碼擷取鍵文本(String)。
//KeyEvent是類名。VK_ESCAPE是按鍵所對應的靜態常量。
if(e.isControlDown()&&e.getKeyCode()==KeyEvent.VK_ENTER)
//System.exit(0);
System.out.println("按鍵組合運行");

//System.out.println(KeyEvent.getKeyText(e.getKeyCode())+"---"+e.getKeyCode());
}
});
//給文字框添加鍵盤事件
tf.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e)
{
int code=e.getKeyCode();
//如果文字框輸入的不是0到9則顯示為不合法資料,而且不會出現在文本 框中。
if(!(code>=KeyEvent.VK_0&&code<=KeyEvent.VK_9))
{

System.out.println(code+"---不合法資料");
e.consume();
}
}
});
}
public static void main(String[] args) {
new MouseAndEvent();
}
}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

java GUI(滑鼠鍵盤事件)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.