I have updated this ask, i created a simple program with the following problem.
This is the version code that work:
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
static boolean readytoconnect = false;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
JPanel panel = new JPanel();
frame.add(panel);
panel.setBounds(0, 0, frame.getWidth(), frame.getHeight());
panel.setBackground(Color.lightGray);
panel.setLayout(null);
JButton connect = new JButton("Connect");
panel.add(connect);
connect.setBounds(200, 200, 80, 40);
connect.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
readytoconnect = true;
}
});
Thread threadtoconnect = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println("WAITING TO CONNECT");
if (readytoconnect) {
System.out.println("CONNECTED");
}
}
}
});
threadtoconnect.start();
}
}
This is the version code that don't work:
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
static boolean readytoconnect = false;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
JPanel panel = new JPanel();
frame.add(panel);
panel.setBounds(0, 0, frame.getWidth(), frame.getHeight());
panel.setBackground(Color.lightGray);
panel.setLayout(null);
JButton connect = new JButton("Connect");
panel.add(connect);
connect.setBounds(200, 200, 80, 40);
connect.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
readytoconnect = true;
}
});
Thread threadtoconnect = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
//System.out.println("WAITING TO CONNECT");
if (readytoconnect) {
System.out.println("CONNECTED");
}
}
}
});
threadtoconnect.start();
}
}
the difference between these is that in the first, which works, there is the output before the 'IF' and in the second, which does not work, there is no output.