當前位置:編程學習大全網 - 腳本源碼 - Java中,如何讓KeyListener與ActionListener同時監聽?

Java中,如何讓KeyListener與ActionListener同時監聽?

監聽器應該加在JTextArea上,而不是窗口上:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class KeyinEvent extends JFrame implements KeyListener

{

JTextArea textarea=new JTextArea(4,20);

Container c;

public KeyinEvent()

{

super("按鍵測試");

c=getContentPane();

c.setLayout(new FlowLayout());

textarea.addKeyListener(this);

c.add(textarea);

//textarea.setText("請按任意鍵");

setSize(300,120);

setVisible(true);

//addKeyListener(this);

}

public void keyPressed(KeyEvent e)

{

String line1="按鍵"+e.getKeyChar();

String line2="按鍵是否為Action鍵"+e.isActionKey();

String mkey=e.getKeyModifiersText(e.getModifiers());

String line3="是否按下Modifier鍵"+(mkey.equals("")?"否":"是,其鍵為:"+mkey);

textarea.setText(line1+"\n"+line2+"\n"+line3+"\n");

}

public void keyReleased(KeyEvent e){}

public void keyTyped(KeyEvent e){}

public static void main(String[] args)

{

KeyinEvent be=new KeyinEvent();

be.addWindowListener(new MyWindowListener());

}

}

class MyWindowListener implements WindowListener

{

public void windowActivated(WindowEvent e)

{

System.out.println("窗口為活動狀態");

}

public void windowClosed(WindowEvent e)

{

System.out.println("窗口為關閉狀態");

System.exit(0);

}

public void windowClosing(WindowEvent e)

{

System.out.println("窗口正在關閉");

System.exit(0);

}

public void windowDeactivated(WindowEvent e)

{

System.out.println("窗口不再活動");

}

public void windowDeiconified(WindowEvent e)

{

System.out.println("窗口由最小化變為正常");

}

public void windowIconified(WindowEvent e)

{

System.out.println("窗口為最小化");

}

public void windowOpened(WindowEvent e)

{

System.out.println("窗口首次可見");

}

}

  • 上一篇:金字塔原理
  • 下一篇:電腦有幾種開機方式?
  • copyright 2024編程學習大全網