0
public MultiplicationTable()
{
    JLabel jl;
    JTextField tf;
    JButton btn[];
    Container c;
    JPanel p1, p2, p3;
    int a;
    String value;

    super ("Multiplication Table");
    c = getContentPane();
    p3 = new JPanel (new FlowLayout());
    btn = new JButton[1];
    btn[0] = new JButton ("Show Times Table");
    jl = new JLabel ("Enter a Number:");
    tf = new JTextField(5);
    p3 = new JPanel (new BorderLayout(5,5));
    p3.add (jl, BorderLayout.NORTH);
    p3.add (tf, BorderLayout.CENTER);
    p3.add (btn[0], BorderLayout.SOUTH);

    btn[0].addActionListener(
        new ActionListener() 
        {
            public void actionPerformed(ActionEvent e) 
            {
                String Value;
                Value = tf.getText();
                if (Value == "1")
                {
                    System.out.print ("asd");
                }
            }
        }
    );

}

I would like to make the action listener for the button as I enter "1" in the text field. I really need to work on these codes. I wish you could help. Thanks!

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 2
    Why not add an `ActonListener` to the text field? It will fire when the user presses the enter key. To know when the text in the field changes, add a `DocumentListener`.. – Andrew Thompson Sep 02 '14 at 16:35
  • 2
    `if (Value == "1")` 1) `Value` should be `value` (to meet Java naming conventions). 2) `== "1"` should be `.equals("1")` for correct string comparison. – Andrew Thompson Sep 02 '14 at 16:37
  • 2
    See this [`if (Value == "1")`](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Paul Samsotha Sep 02 '14 at 16:38

1 Answers1

1

In your code, == is testing whether the two strings are the same object.

Remember this:

== tests for reference equality

.equals() tests for value equality

If you want to know if two strings have the same value you should use .equals(), (as was already pointed out).

Also, as a Java naming convention, for variable names use lowercase for the first word and capitalize only the first letter of each of the remaining words.

JosEduSol
  • 5,268
  • 3
  • 23
  • 31