回车怎么激活按钮事件

lihaifeng0412 2008-03-16 08:08:27
现在在窗口上添加一个JButton按钮,点击是触发一个事件,怎么能使按下回车键时候触发此button事件,处理同样的问题
...全文
248 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
rainsilence 2008-03-16
  • 打赏
  • 举报
回复
3楼5楼正解
andyfor 2008-03-16
  • 打赏
  • 举报
回复
tf.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyChar() == 13)//KeyEvent.VK_ENTER) //按键 执行相应操作;
{
ta.append("\n\r");
ta.append(tf.getText());
tf.setText("");//记住该数据后,清空窗口
}

}
});
love1907 2008-03-16
  • 打赏
  • 举报
回复
2楼很清楚...
love1907 2008-03-16
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 Fenglee2008 的回复:]
jbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
callYourMethod();//你处理鼠标事件的方法
}
));
[/Quote]
应该不正确哈,楼主要求是按上回车键;

这样子的楼主: JButton jb = new JButton();
jb.addKeyListener(监听器);

然后在监听器里实现KeyListener()的相关方法
Inhibitory 2008-03-16
  • 打赏
  • 举报
回复
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Test extends JPanel {

private static void createAndShowGUI() {

JFrame frame = new JFrame("Change Icon");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);

JButton button = new JButton("Button");
JPanel panel = new JPanel();
panel.add(button);
panel.add(new JButton("Other")); // 测试用tab按切换, 使不同的铵钮得到焦点
frame.getContentPane().add(panel);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button is clicked.");
}
});

button.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 10) {
System.out.println("Enter is pressed.");
}
}
});

frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Test.createAndShowGUI();
}
});
}
}
Fenglee2008 2008-03-16
  • 打赏
  • 举报
回复
jbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
callYourMethod();//你处理鼠标事件的方法
}
));

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧