java – 使用普通的类方法调用actionPerformed方法
发布时间:2020-12-15 04:09:33 所属栏目:Java 来源:网络整理
导读:我试图在普通的类方法中调用actionPerformed().我知道只要按下按钮就会自动执行.但是我想在特定文本字段上按下ENTER按钮时调用该方法.是否可以在keyPressed()或普通函数/方法中调用actionPerformed(). 以下代码将让您粗略了解我想要做什么. void myFunction(
我试图在普通的类方法中调用actionPerformed().我知道只要按下按钮就会自动执行.但是我想在特定文本字段上按下ENTER按钮时调用该方法.是否可以在keyPressed()或普通函数/方法中调用actionPerformed().
以下代码将让您粗略了解我想要做什么. void myFunction() { actionPerformed(ActionEvent ae); } public void actionPerformed(ActionEvent ae) { //my code } 提前致谢 解决方法
如果你想要的话,JButton的一些actionPerformed()方法在按下JTextField里面的ENTER时执行,那么我猜你可以使用来自AbstractButton类的
doClick()方法来实现这一点.虽然这种方法,可能会按下ENTER键覆盖JTextField的原始行为:(
请看下面粘贴的代码,看看这是什么,适合您的需求:-) !!! import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ButtonClickExample { private JTextField tfield; private JButton button; private JLabel label; private ActionListener actions = new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if (ae.getSource() == button) { label.setText(tfield.getText()); } else if (ae.getSource() == tfield) { button.doClick(); } } }; private void displayGUI() { JFrame frame = new JFrame("Button Click Example"); frame.setDefaultCloSEOperation(JFrame.DISPOSE_ON_CLOSE); JPanel contentPane = new JPanel(); contentPane.setLayout(new BorderLayout(5,5)); JPanel centerPanel = new JPanel(); tfield = new JTextField("",10); button = new JButton("Click Me or not,YOUR WISH"); tfield.addActionListener(actions); button.addActionListener(actions); centerPanel.add(tfield); centerPanel.add(button); contentPane.add(centerPanel,BorderLayout.CENTER); label = new JLabel("Nothing to show yet",JLabel.CENTER); contentPane.add(label,BorderLayout.PAGE_END); frame.setContentPane(contentPane); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { new ButtonClickExample().displayGUI(); } }); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |