Question

As i have seen many answers are too obscure for a entry level student like me.

i am following the steps by first addActionListner(this) to my JTextField.

what i am trying to do next and confuses the most is under:

public void actionperformed(Actionevent ae){
     if(ae.getSource() == "Enter pressed")
         {
          outArea.setText(result);
         }
}

which does not work because i feel like the code ae.getSource() == "Enter presses" is not working correctly and even i replaced the action i took under actionPerformed by a simple print line command like System.out.println("working"), it won't execute.

here is what i do if a button is pressed.

    public void actionperformed(Actionevent ae){
     if(ae.getSource() == "JButton")
         {
          System.out.println("JButton was pushed");
         }
}

no matter how, lets say i have a GUI with a piece of given code like these:

  public static void main(string[] args){
 new myProg();
 } 
  public myProg(){
  ....
  buildTheGUI();
  ...}

           }
//GUI Objects
 ...
JTextField input = new JTextField(10);
 ...

//method building the GUI

public void buildTheGUI(){
...
input.addActionListner(this);
...

//a method called actionPerformed
public void actionperformed(Actionevent ae){
}

i am now trying to detect the enter key by actionListner not by any other method because it's given.

Was it helpful?

Solution

Firstly, actionPerformed is triggerd by an action event, typically on most systems, this is triggered by the Enter key (with context to the JTextField)...so you don't need to check for it.

Secondly, the source of the ActionEvent is typically the control that triggered it, that would be the JTextField in this case.

Thirdly, String comparison in Java is done via the String#equals method...

 if ("Enter presses".equals(someOtherString)) {...

OTHER TIPS

Your actionPerformed method for the Button is wrong, try better this:

@Override
public void actionPerformed(ActionEvent e) {
    if(e.getSource() instanceof JButton) {
        JButton button = (JButton) e.getSource();
        System.out.println("This button was pushed: " + button.getText());
    }
}

And your for KeyListener try this to learn how it works:

@Override
    public void keyPressed(KeyEvent e) {
        System.out.println(e.getKeyChar());
        System.out.println(e.getKeyCode());
    }

Dont forget to let your class implement ActionListener and KeyListener.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top