Java – call the actionperformed method using normal class methods
I try to call actionPerformed () in a generic class method. I know it will be executed automatically as long as I press the button But I want to call this method when I press the enter button on a specific text field You can call actionPerformed () in keyPressed () or ordinary function / method.
The following code will give you a rough idea of what I want to do
void myFunction()
{
actionPerformed(ActionEvent ae);
}
public void actionPerformed(ActionEvent ae)
{
//my code
}
Thank you in advance
Solution
If you want, some of JButton's actionperformed () methods execute when you press enter in jtextfield, then I guess you can use the doclick () method from the abstractbutton class to achieve this Although this method may override the original behavior of jtextfield by pressing enter:(
Please see the code pasted below to see what it is, which is suitable for your needs: -)!!!
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();
}
});
}
}
