3

我正在尝试调用actionPerformed()in normal类的方法。我知道每当按下按钮时它都会自动执行。但是我想在特定文本字段上按下 ENTER 按钮时调用该方法。是否可以调用或调用正常的函数/方法actionPerformed()keyPressed()

以下代码将使您大致了解我想要做什么。

void myFunction()
{
      actionPerformed(ActionEvent ae);
}

public void actionPerformed(ActionEvent ae)
{
      //my code
}

提前致谢

4

2 回答 2

5

如果你愿意,在 a内按下时要执行actionPerformed()a 的某些方法,那么我想你可以使用类中的doClick()方法来实现这一点。尽管这种方法,可能会覆盖按键时的原始行为:(JButtonENTERJTextFieldAbstractButtonJTextFieldENTER

请查看下面粘贴的这段代码,看看这是否符合您的需求:-) !!!

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();
            }
        });
    }
}
于 2013-04-27T10:58:58.417 回答
3

我知道这是一个旧线程,但对于看到这个的其他人,我的建议是这样的:

// This calls the method that you call in the listener method
void performActionPerformedMethod(){
    actionPerformed(ActionEvent e);
}

// This is what you want the listener method to do
void actionPerformedMethod(){
// Code...
}

// This is the interface method
public void actionPerformed(ActionEvent e){
    actionPerformedMethod()
}
于 2014-04-03T19:33:23.417 回答