java怎么给按钮添加一个键盘监听?(麻烦写的易懂些)

java怎么给按钮添加一个键盘监听?(麻烦写的易懂些),第1张

importjava.awt.*importjava.awt.event.*publicclassKeyTestextendsFrame{publicKeyTest(){//注册键盘监听addKeyListener(newKeyAdapter(){publicvoidkeyPressed(KeyEventke){System.out.println("Thecharis:"+ke.getKeyChar())}})//注册窗口监听setSize(100,100)setVisible(true)}publicstaticvoidmain(String[]args){newKeyTest()}}不知道这个行否?

import java.awt.FlowLayout

import java.awt.event.ActionEvent

import java.awt.event.ActionListener

import javax.swing.JButton

import javax.swing.JFrame

import javax.swing.JTextField

public class ShowButton implements ActionListener{

private JTextField textField = null

private JButton button = null

private JFrame frame = null

public ShowButton(){

frame = new JFrame("显示按钮文字")

button = new JButton("3")

textField = new JTextField("",20)

frame.setLayout(new FlowLayout(FlowLayout.CENTER))

frame.add(textField)

button.addActionListener(this)

frame.add(button)

frame.setSize(400, 100)

frame.setResizable(false)

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

frame.setVisible(true)

}

public void actionPerformed(ActionEvent e) {

textField.setText("")

textField.setText(button.getActionCommand())

System.out.println(button.getActionCommand()+"===")

}

public static void main(String[] args) {

new ShowButton()

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11926594.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存