I think the user.contains is not reading every line and is only checking the first line. I had this working right earlier(I am testing the duplicate user portion of my code), but now my program is skipping :
{
JOptionPane.showMessageDialog(null, "Duplicate user found.");
goahead=false;
dispose();
}
I am not sure what I did, or how I managed to break my own program. Now its skipping all the way to:
else { if (hs.contains(new String(un+" "+pw))) {
JOptionPane.showMessageDialog(null,"User, Found Access Granted!");
dispose();
}
Where did I go wrong?
private void SubmitActionPerformed(java.awt.event.ActionEvent evt) {
String un = UserName.getText().trim();
String pw = Password.getText().trim();
HashSet hs= new HashSet();
HashSet users = new HashSet();
boolean goahead=true;
try {
Scanner Scan = new Scanner(new File("Login.txt"));
while (Scan.hasNextLine()) {
String authenticator = Scan.nextLine().trim();
String[] autparts=authenticator.split(" ");
String user = autparts[0].trim();
if (goahead){
if (users.contains(user)) {
if (user.equals(un)) {
JOptionPane.showMessageDialog(null, "Duplicate user found.");
goahead=false;
dispose();
}
} else {
hs.add(authenticator);
users.add(user);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
if (goahead) {
if (createAccount.isSelected() & (hs.contains(new String(un+" "+pw)))){
JOptionPane.showMessageDialog(null,"User Already Exsist! No Need to create a new account. ");
dispose();
} else {
if (hs.contains(new String(un+" "+pw))) {
JOptionPane.showMessageDialog(null,"User, Found Access Granted!");
dispose();
} else {
if (createAccount.isSelected()){
try {
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("Login.txt", true)));
output.println(un+" "+pw);
output.close();
} catch (IOException ex) {
System.out.printf("error %s/n", ex );
}
JOptionPane.showMessageDialog(null,"Welcome!"+" " + un+" "+"Please Relogin Now");
dispose();
}else {
JOptionPane.showMessageDialog(null, "user doesn't exist or password incorrect. ");
dispose();
}
}
}
}
the following is my output and whats in the txt file. :
I have formatted your code now:
String un = UserName.getText().trim();
if (goahead){
if (users.contains(user))
{
if (user.equals(un))
{
JOptionPane.showMessageDialog(null, "Duplicate user found.");
goahead=false;
dispose();
}
}
else
{
hs.add(authenticator);
users.add(user);
}
}
Now when the flag goahead is set to false dont we need to reset it to true somewhere? If HashSet contains user then why do you need to again compare name of user? You should have defined equals for the user itself. Nope?
You seem to chasing your tail, doing two things at one, reading the file/populating the Set AND checking for duplicates. Instead, do one at a time...
Something like...
// You could pre-load these and cache the result instead
// of reading it each time, but that's up to you
Map<String, String> credentials = new HashMap<>(25);
try (Scanner scan = new Scanner(new File("Login.txt"))) {
while (scan.hasNextLine()) {
String value = scan.nextLine();
String[] parts = value.split(" ");
credentials.put(parts[0], parts[1]);
}
} catch (IOException exp) {
exp.printStackTrace();
}
// Make your required checks here
if (credentials.containsKey(un)) {
if (credentials.get(un).equals(pw)) {
// Validated
} else {
// Wrong password
}
} else {
// New user...?
}
Related
This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 3 years ago.
It seems that its creating a new file always I try to write or read.
Each line starts with the name of the player, if exists the player should add the score at the end, if not creates a new line and write the info.
.......................
public class JogadorData {
private String nome_player;
private Scanner is;
private FileWriter os;
// this file exists
private final String path = "src/Data/JogadorData";
public JogadorData(String nome_player) {
this.nome_player = nome_player;
try {
is = new Scanner(new File(path));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
os = new FileWriter(path);
} catch (IOException e) {
e.printStackTrace();
}
}
public void escreverScore(String score) {
if (jogadorNovo(nome_player)) {
try {
os.write(nome_player + " " + score);
} catch (IOException e) {
e.printStackTrace();
}
}
else {
escreverResultadoJogadorExistente(score);
}
try {
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// returns true if it is a new player
private boolean jogadorNovo(String nome_player) {
while (is.hasNextLine()) {
String linha = is.nextLine();
String[] info = linha.split(" ");
if (info[0].equals(nome_player)) {
return false;
}
}
return true;
}
}
....................................
....................................
Test:
public class TESTE {
public static void main(String[] args) {
JogadorData jogador = new JogadorData("Manelina");
jogador.escreverScore("100");
// System.out.println(jogador.lerMelhorResultado());
}
}
The example below is a simplified read/write to file from what you have, done in similar format to what you are trying to do. What this code does is reads every line from the file you are loading from via Files#readAllLines, then runs through each line, (put your logic where I commented the if statement, and then output.add appends the new version of the line you are modifying, storing it in the array list "output", after which the file is saved to the path defined by Files#write
List<String> output = new ArrayList<>();
List<String> lines = Files.readAllLines(Paths.get("Path/To/File.txt"));
for (String line : lines) {
//... if (playerExists(line))
output.add(line + " " + score);
}
Files.write(Paths.get("Path/To/Save/File.txt"), output);
I have this:
propiedades = new Properties();
try {
entrada = new FileInputStream("config.properties");
propiedades.load(entrada);
Set set =propiedades.stringPropertyNames();
System.out.println(set);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (entrada != null) {
try {
entrada.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
So basiclly whats inside "config.properties" is the following thing:
admin=admin
user=userpass
user1:userpas1
Next up,i have this code:
public boolean revisarCredenciales(String userName,String password)
{
Enumeration<?> e = propiedades.propertyNames();
while(e.hasMoreElements())
{
for (; e.hasMoreElements();) {
System.out.println(e.nextElement());
if (e.nextElement().equals(userName) && propiedades.getProperty(userName).equals(password))
{
return true;
}
}
}
return false;
}
In this block I tried to do a simple if where if the e.nextElement() equals userName (userName is just a txUserBox.getText()) and propiedades.getProperty(userName).equals(password(txPassword.getPassword()) then it returns a value, can be either false or true, and the method where it is called will access the program if true.
The problem comes where it always is returns true and with this, doesn't matter what I put on the textboxes it will log me on..
To quick answer in case somebody has an error like this i fixed this by just doing:
public boolean revisarCredenciales(String userName,String password,Set<String> setNombres)
{
for (String key:setNombres)
{
String pass=propiedades.getProperty(key);
if( userName.equals(key) && pass.equals(password)){
return true;
}
}
return false;
}
On the method to review credentials, because it was getting the setNombres from this:
propiedades = new Properties();
try {
entrada = new FileInputStream("config.properties");
propiedades.load(entrada);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (entrada != null) {
try {
entrada.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
setNombres=propiedades.stringPropertyNames();
So, when it reviews the credentials it receives first the username from the JTextField, the password and the set of strings. When u send the JPassword field do new String(txPassword.getPassword()). If you dont do it and send just txPassword.getPassword() it will send the password encripted and cant match then.
public boolean revisarCredenciales(String userName,String password,Set<String> setNombres)
{
for (key:setNombre(Position))
{
pass(the one written on the textbox)= propiedades.getProperty(key);
//Here it obtaions the value in properties, next to key
if( userName.equals(key) && pass.equals(password)){
//UserName is what is in the textbox /pass defined on top.equals(What is on the textbox)
return true;
//if that happens returns true, this proccess repeats for each line of the config.properties
}
}
return false;
}
I am working on a turtle graphics project and I'm attempting to retrieve a user input from a jtextfield (commField) which should be like: ' forward 100 ' I've attempted to do a string split and intparse however when the program is run, even when a correct command is entered it will go to the message error dialogue. After a few hours of turning the cogs in my brain I'm struggling to figure out why and so am asking for any help. If more of my code is needed for an answer that is fine, perhaps I'm focusing on the wrong thing.
commField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
else if(commField.getText().contains("forward")) {
String cForward = commField.toString();
String[] cForwardArray = cForward.split("\\s+");
try {
int distance = Integer.parseInt(cForwardArray[1]);
graphicsPanel.forward(distance);
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
else if(commField.getText().contains("backward")) {
String cBackward = commField.toString();
String[] cBackwardArray = cBackward.split("\\s+");
try {
int distance = Integer.parseInt(cBackwardArray[1]);
graphicsPanel.backward(distance);
graphicsPanel.repaint();
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
}
});
Below is the full code block for those who want it:
commField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(commField.getText().contains("penup")) {
graphicsPanel.penUp();
}
else if(commField.getText().contains("pendown")) {
graphicsPanel.penDown();
}
else if(commField.getText().contains("turnright")) {
graphicsPanel.turnRight();
}
else if(commField.getText().contains("turnleft")) {
graphicsPanel.turnLeft();
}
else if(commField.getText().contains("forward")) {
String cForward = commField.toString();
String[] cForwardArray = cForward.split("\\s+");
try {
int distance = Integer.parseInt(cForwardArray[1]);
graphicsPanel.forward(distance);
System.out.println(commField);
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
else if(commField.getText().contains("backward")) {
String cBackward = commField.toString();
String[] cBackwardArray = cBackward.split("\\s+");
try {
int distance = Integer.parseInt(cBackwardArray[1]);
graphicsPanel.backward(distance);
graphicsPanel.repaint();
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
else if(commField.getText().contains("black")) {
graphicsPanel.black(Color.black);
}
else if(commField.getText().contains("green")) {
graphicsPanel.green(Color.green);
}
else if(commField.getText().contains("red")) {
graphicsPanel.red(Color.red);
}
else if(commField.getText().contains("reset")) {
graphicsPanel.clear();
}
else {
JOptionPane.showMessageDialog(textArea, "Invalid command, try again");
}
commField.setText("");
graphicsPanel.repaint();
}
});
Line of interest:
String cForward = commField.toString();
JTextField.toString() does not return the content of the JTextField.
I checked my java 8 sources and found the following:
public String toString() {
return getClass().getName() + '[' + paramString() + ']';
}
However, the toString() method is intended to be a debugging utility. Unless its behavior is explicitly documented it is not recommended to rely on it programmatically.
For retrieving its text content, JTextField provides a separate method: JTextComponent#getText(). The line should therefore be changed to:
String cForward = commField.getText();
I have to retrieve offline messages from Google Talk for a particular client (friend/ XMPP Client) with whom I have had a conversationn with.
Additionally, I want to retrieve the chat history.
Right now, I am using a Hash Map to keep track of the conversation and have no means of having the offline messages.
I have made an XMPP connection to "talk.google.com". I am currently able to send messages to the client via my console. I have implemented the Message Listener Interface and hence can receive messages in my console itself.
I have another implementaion(made use of OfflineMessageManager) where I try to extract the offline messages headers as a start, unfortunately, it fails with Null Exception.
I have used smack-tcp version 4.0.3 and smackx 3.1.0.
Please find below what I have tried till now...
Working Implementation:
public class StartChatImpl implements startChat, MessageListener {
static XMPPConnection myXMPPConnection;
static ArrayList<String> myFriends = new ArrayList<String>();
ArrayList<Msg> messages;
HashMap<String,ArrayList> conversation = new HashMap<String, ArrayList>();
OfflineMessageManager offlineMessages;
#Override
public void engageChat(ChatRequest chatRequest) throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
//config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setSendPresence(true);
myXMPPConnection = new XMPPTCPConnection(config);
try{
System.out.println("Connecting to talk.google.com");
myXMPPConnection.connect();
System.out.println("Logging you in...");
myXMPPConnection.login(chatRequest.getUsername(),chatRequest.getPassword());
Presence pres = new Presence(Presence.Type.unavailable);
myXMPPConnection.sendPacket(pres);
offlineMessages = new OfflineMessageManager(myXMPPConnection);
System.out.println("You have been successfully connected.");
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void send (String message, String to) throws XMPPException
{
Chat chat = ChatManager.getInstanceFor(myXMPPConnection).createChat(to, this);
//System.out.println("********************************************");
//System.out.println("CHAT ID: "+ chat.getThreadID());
//System.out.println("Participant: "+chat.getParticipant());
//System.out.println("********************************************");
try {
chat.sendMessage(message);
String friendName = myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName();
if(conversation.containsKey(friendName))
{
messages = conversation.get(friendName);
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
message = "bot says: "+message;
Msg actualMsg = new Msg(currentTimestamp,message,"bot");
messages.add(actualMsg);
//messages.add("bot says: "+message);
}
else
{
messages = new ArrayList<Msg>();
//messages.add("Bot initiated the conversation on: "+new Date());
//messages.add("bot says: "+message);
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
message = "bot says: "+message;
Msg actualMsg = new Msg(currentTimestamp,message,"bot");
messages.add(actualMsg);
conversation.put(friendName,messages);
}
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
System.out.println("You said "+"'"+message+"'"+" to "+myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName());
}
PacketListener myPacketListener = new PacketListener() {
#Override
public void processPacket(Packet p) {
if (p instanceof Message) {
Message msg = (Message) p;
}
}
};
public void displayMyFriends()
{
Roster roster = myXMPPConnection.getRoster();
Collection entries = roster.getEntries();
System.out.println("You currently have: "+entries.size()+" friends available to chat.");
int counter = 0;
Iterator i = entries.iterator();
while(i.hasNext())
{
RosterEntry r = (RosterEntry) i.next();
Presence.Type entryPresence;
entryPresence = roster.getPresence(r.getUser()).getType();
System.out.println((counter+1)+" . "+r.getName() +" is "+entryPresence);
//System.out.println("id:..."+r.getUser());
myFriends.add(r.getUser());
counter++;
}
}
public void disconnectMe()
{
try {
System.out.println("Disconnection in progress...");
myXMPPConnection.disconnect();
System.out.println("You have been successfully disconnected.");
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
#Override
public void processMessage(Chat chat, Message message)
{
if((message.getType() == Message.Type.chat) && (message.getBody()!= null)) {
System.out.println(myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName() + " says: " + message.getBody());
String myMsg = myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName() + " says: " + message.getBody();
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
Msg actualMsg = new Msg(currentTimestamp,myMsg,"customer");
conversation.get(myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName()).
add(actualMsg);
}
}
public void receiveMessage(){
myXMPPConnection.addPacketListener(myPacketListener, null);
}
public void retrieveUnservicedMessagesForSpecificPerson(String clientName)
{
ArrayList<Msg> myMessages = conversation.get(clientName);
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
System.out.println("Unserviced messages from: "+ clientName);
if(!myMessages.isEmpty())
{
int counter = myMessages.size()-1;
System.out.println("Size of array list: "+counter);
boolean found = false;
java.sql.Timestamp lastBotTimestamp = null;
while (counter != 0 && found == false){
if(myMessages.get(counter).getOwner()=="bot")
{
lastBotTimestamp = myMessages.get(counter).getTimestamp();
found = true;
}
else
{
counter = counter-1;
}
}
for(Msg msg:myMessages)
{
if(msg.getTimestamp().before(currentTimestamp) &&
msg.getTimestamp().after(lastBotTimestamp)){
System.out.println("---------------------------");
System.out.println("-"+msg.getActualMessage());
System.out.println("-"+msg.getTimestamp());
System.out.println("---------------------------");
}
}
}
}
public void returnConversation(String name) {
System.out.println("Name of participant entered: "+ name);
System.out.println("Conversation history is: ");
ArrayList<Msg> m = conversation.get(name);
for(Msg msg:m){
System.out.println(msg.getActualMessage());
System.out.println("on: "+msg.getTimestamp());
}
}
public void returnAllUnservicedMessagesHistory()
{
for(String name: conversation.keySet())
{
System.out.println("History of unserviced messages for: "+ name);
retrieveUnservicedMessagesForSpecificPerson(name);
}
}
public void getOfflineMessagesCount(){
try {
System.out.println("Number of offline messages: "+ offlineMessages.getMessageCount());
} catch (XMPPException e) {
e.printStackTrace();
}
}
}
My Main Class Implementation:
public class MainGoogleChatApp {
public static void main(String[] args)
{
//Step 1: need to make a chat request with your username and password.
Scanner input = new Scanner(System.in);
System.out.println("Please enter your username to start: ");
String myUsername = input.next();
System.out.println("Please enter your password to continue: ");
String myPassword = input.next();
ChatRequest myChatRequest = new ChatRequest();
myChatRequest.setUsername(myUsername);
myChatRequest.setPassword(myPassword);
//Step 2: Need to initiate a connection to talk.google.com
StartChatImpl convo = new StartChatImpl();
try {
convo.engageChat(myChatRequest);
} catch (XMPPException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String myMessage;
System.out.println("Friend list.");
convo.displayMyFriends();
convo.receiveMessage();
try {
while(true)
{
System.out.println("Input Which friend you want to chat with '0 to sign out' : ");
int num = input.nextInt() -1;
if (num == -1){
break;
}
String chatWith = StartChatImpl.myFriends.get(num);
System.out.print("Type your message: ");
myMessage=br.readLine();
try {
convo.send(myMessage,chatWith);
} catch (XMPPException e) {
e.printStackTrace();
}
convo.displayMyFriends();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Enter participant name to get specific chat...");
String yourName = null;
try {
yourName = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("/./././././././././././././..//.");
if(yourName!=null){
System.out.println("Your name is not null...ok");
convo.returnConversation(yourName);
}
System.out.println("Enter another participant's name to get specific chat...");
String yourName1 = null;
try {
yourName1 = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("/./././././././././././././..//.");
if(yourName1!=null){
System.out.println("Your name is not null...ok");
convo.returnConversation(yourName1);
}
System.out.println("Select a client name for whom you want to view unserviced messages: ");
String yourClientName = null;
try {
yourClientName = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if(yourClientName!=null){
System.out.println("...........................................");
convo.retrieveUnservicedMessagesForSpecificPerson(yourClientName);
}
System.out.println("...........................................");
convo.returnAllUnservicedMessagesHistory();
System.out.println("You have chosen to disconnect yourself from talk.google.com");
convo.disconnectMe();
System.exit(0);
}
}
Attempt to retrieve offline messages headers:
public class TestOfflineService {
XMPPConnection xmppConnection = null;
//OfflineMessageManager offlineMessageManager = null;
public void makeConnection()
{
ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
//config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setSendPresence(true);
xmppConnection = new XMPPTCPConnection(config);
try{
System.out.println("Connecting to talk.google.com");
xmppConnection.connect();
System.out.println("Logging you in...");
xmppConnection.login("*******.*#***.com", "*****");
System.out.println("You have been successfully connected.");
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
}
public void makeMeUnavailable()
{
try {
xmppConnection.sendPacket(new Presence(Presence.Type.unavailable));
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
public void getOfflineMessages()
{
OfflineMessageManager offlineMessageManager1 = new OfflineMessageManager(xmppConnection);
try {
Iterator<OfflineMessageHeader> headers = offlineMessageManager1.getHeaders();
if(headers.hasNext())
{
System.out.println("Messages found");
}
} catch (XMPPException e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
TestOfflineService test = new TestOfflineService();
test.makeConnection();
test.makeMeUnavailable();
System.out.println("Enter messages");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Getting offline messages.....");
test.getOfflineMessages();
}
}
OfflineMessageManager tries to use XEP-0013 to retrieve offline messages. This XEP isn't implemented by GTalk. Also note that ever starting Hangouts means you'll never get offline messages anymore, as the Hangouts instance is never offline.
GTalk also does not have an XMPP API to retrieve chat history, like XEP-0136 or XEP-0313.
I was doing a project in JAVA Swing Netbeans IDE 7.1. I created one jFrame with some button and Dropdowns on it. On selecting a choice from the dropdown,another frame object is created and setVisible is set to true. But instead of showing one window, it is showing up 2 windows. There are other similar calls, but none have this issue, someone please help me. Thanks.
Code:
private void itemListItemStateChanged(java.awt.event.ItemEvent evt) {
String item = null;
String filename = null;
item = (String) itemList.getSelectedItem();
if(item=="P"){
filename="p";
description.setText("Description: P");
}
else if(item=="A"){
filename="a";
description.setText("Description: A");
}
else if(item=="R"){
filename="r";
description.setText("Description: R");
}
else if(item=="S"){
filename="s";
description.setText("Description: S");
}
else if(item=="X"){
displayText.setText("");
x xl = new x();
xl.setVisible(true);
}
else if(item=="Xx"){
filename="xx";
description.setText("Description: xx");
}
else {
System.out.println("invalid selection.");
}
if (item=="X"){
return;
}
else {
displayText.setText("");
BufferedReader b = null;
try {
b= new BufferedReader(new FileReader ("/home/sfred/"+filename+".mile"));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
try {
line = b.readLine();
} catch (IOException ex) {
ex.printStackTrace();
}
while (line != null){
displayText.append(line + "\n");
try {
line=b.readLine();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
See The Use of Multiple JFrames, Good/Bad Practice? rather use :
1) JDialog
2) CardLayout which will allow you to flip between multiple components on a single JFrame.
You cannot compare String using ==operator must use equals(String s) or else it wont evaluate correctly
if(item.equals("X")) {
}
Rather use switch statement (Java 7+) when comparing String:
switch(item) {
case "P":
//do something
break;
case "X":
//do something
break;
default:
//if no match with above was found..
break;
}