以前的按钮操作都是按下面的方法实现的,楼上的方法可用吗?? Action searchAction = new AbstractAction("查询") { public void actionPerformed(ActionEvent action) { clickSearchButton(true); } }; _searchButton = new JButton(searchAction);
ActionListener接收到的是什么事件啊? 鼠标点击能触发,键盘回车不行吗??why?
帮你搞了一下, 试试. 别忘了给分哟.呵呵. import java.awt.event.*; import javax.swing.*;/** * @author He Kun * */ public class ButtonFrame2 extends JFrame { JButton button = new JButton("button0");
public ButtonFrame2() { init(); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
Action searchAction = new AbstractAction("查询")
{
public void actionPerformed(ActionEvent action)
{
clickSearchButton(true);
}
};
_searchButton = new JButton(searchAction);
鼠标点击能触发,键盘回车不行吗??why?
import java.awt.event.*;
import javax.swing.*;/**
* @author He Kun
*
*/
public class ButtonFrame2 extends JFrame
{
JButton button = new JButton("button0");
public ButtonFrame2()
{
init();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void init()
{
this.getContentPane().setLayout(null);
this.setSize(300,200);
button.setBounds(20,20,80,20);
this.getContentPane().add(button);
button.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
button_keyPressed(e);
}
});
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
button_actionPerformed(e);
}
});
}
private void button_actionPerformed(ActionEvent e)
{
javax.swing.JOptionPane.showMessageDialog(this,"mouse clicked");
}
private void button_keyPressed(KeyEvent e)
{
javax.swing.JOptionPane.showMessageDialog(this,"keyPressed "+ KeyEvent.getKeyText(e.getKeyCode()));
if(e.getKeyCode() == KeyEvent.VK_ENTER)
button_actionPerformed(null);
}
public static void main(String[] args)
{
ButtonFrame2 buttonFrame = new ButtonFrame2();
buttonFrame.setVisible(true);
}
}
假如有几个按钮每个按钮的鼠标事件和键盘事件是一样的但不同的按钮的鼠标事件又不一样时
好像就不行了吧?
我的写法是沿用了VB的那种事件相应处理方式。
你说的“假如有几个按钮每个按钮的鼠标事件和键盘事件是一样的但不同的按钮的鼠标事件又不一样”是另外一种写法,要设置按钮的command属性,并根据command属性进行各自的事件处理。