0

I'm not sure what I'm doing wrong here. I'm trying to create a basic command line using JFrame, which in future I want to create a bunch of functions that will be done based on the user's input, however, when I try to compare the ActionCommand to a string or variable, it doesn't seem to work:

`

    import javax.swing.*;
    import javax.swing.JFrame;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;


    public class GUI extends JFrame{

private JTextField cmd;


public GUI(){
    super("Command Line V2");       //Window title
    setLayout(new FlowLayout());            //Set layout

    cmd = new JTextField("Enter Command");  //Make cmd a JTextField
    add(cmd);                               //Add cmd to the screen

    //Adding action listeners
    cmdHandler handler = new cmdHandler();
    cmd.addActionListener(handler);


}

private class cmdHandler implements ActionListener{
    public void actionPerformed(ActionEvent event){


        String butt = "Whut";

        if(event.getSource()==cmd){
            if(event.getActionCommand()==butt){

                System.out.println("Yay");
            }else{
                System.out.println("uh dear");
                System.out.println(event.getActionCommand());
            }


        }




    }
}`

This is the GUI.java page, but just incase it's needed, here's the main.java page:

        import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.FlowLayout;

    public class Main {

public static void main(String args[]){

    GUI g = new GUI();
    g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    g.setSize(275,180);
    g.setVisible(true);
    g.setResizable(false);
}

    }

When opened, a window opens and a JTextBox appears: "Enter Command" once I write in the command line EXACTLY what the if statement is trying to compare the "event.getActionCommand()" to, it still outputs "uh dear" (Which is what it does if it doesn't compare it to anything)

How am I supposed to fix this? Thank you.

1 Answers1

1

When comparing objects, you must used the .equals function, else you are comparing reference.

So,

if(event.getSource()==cmd){
    if(event.getActionCommand()==butt){
        ...

Will become

if(event.getSource().equals(cmd)){
    if(event.getActionCommand().equals(butt)){
        ...
Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76