package gui;

import javax.swing.*;
Import java.awt.event.*;
import java.applet.Applet;

public class FE extends Applet implements ActionListener {

private JLabel lb = new JLabel("Enter text :");
private JTextField jtf1 = new JTextField(10);
private JButton jb = new JButton("ENTER");
private JLabel lb2 = new JLabel(" ");

public void init() {
    add(lb);
    add(jtf1);
    add(jb);
    add(lb2);
    jb.addActionListener(this);

}

public void actionPerformed(ActionEvent e) {
    String name = jtf1.getText();
    if (e.getSource() == jb) {
      }
    // problem to compare a string. 
    //Example: i have to key in the name called "Lawrence" once i key in and i press the "Enter" button , it will show the text("Access Granted") in a Label field. If key in other name it will show ("Wrong Name").


}

Recommended Answers

All 7 Replies

Sorry im still newbie for java.. and im stuck my code at the actionPerformed .. please help :( thanks

You can use your text field's getText() method to get the String that was typed in. You can compare that to any other String by using its equals method. Then you can use an if test to set the text of the label.

hi James, thanks for reply ..

this is the code after i have modified but its still no give the result ..
I wonder how to setText() for JTextField ?

/*

private JTextField jtf1 = new JTextField(10);

public void actionPerformed(ActionEvent e)
{
    String authorized = "Lawrence"; 
    String name = jtf1.getText();  //there is no text in JTextField 
    if (e.getSource() == jb) {
        if (authorized == name)
            lb2.setText("Access Granted");
        else
            lb2.setText("Wrong Name);
    }

*/

How do you know there is no text in JTextField? Did you try to print the value out?
if (authorized == name) won't work. == tests for those being exactly the same object, which they're not. Re-read my previous post.

oh,i got it for the getText() now , is what we key in in the TextField ..
erm, could you show me how its work for the comparison instead of this method " if (authorized == name) "
sorry im quite confusing ... ><

if (string1.equals(string2)) // tests if the two String objects contain the same sequence of characters

Strings are objects so you cannot compare objects with == unless you want to compare memory locations. Use .equals

if (e.getSource().equals(jb))

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.