user3869810 user3869810 - 4 months ago 18
Java Question

How can I activate control statement from gui button?

In this example, why doesn't the method activate if the variable was changed and the button is set up in another class?

public class Printing {

static boolean print = false;

public static void main(String[] args){
new Gui().setVisible(true);
print();
}

public static void print(){
while (print) {
System.out.println("true");
}
}
}


When the button is pressed it set the
boolean
print to
true
the method print doesn't activate and start printing true can anyone tell me why is this happening and how to solve this.

EDIT FOR MY ASKED FOR CODE

My Code

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

public class Gui extends JFrame {
boolean print = false;
public Gui() {
initComponents();
}

public static void main(String[] args) {
Gui gui = new Gui();
new Gui().setVisible(true);
gui.Print();
}
public void Print(){
while(print == true){
System.out.println("Its true");
}
}
private void buttonActionPerformed(ActionEvent e) {
print = true;
}
private void initComponents() {
button = new JButton();
Container contentPane = getContentPane();
button.setText("Push");
button.addActionListener(e -> buttonActionPerformed(e));
GroupLayout contentPaneLayout = new GroupLayout(contentPane);
contentPane.setLayout(contentPaneLayout);
contentPaneLayout.setHorizontalGroup(
contentPaneLayout.createParallelGroup()
.addGroup(contentPaneLayout.createSequentialGroup()
.addGap(81, 81, 81)
.addComponent(button, GroupLayout.PREFERRED_SIZE, 219, GroupLayout.PREFERRED_SIZE)
.addContainerGap(84, Short.MAX_VALUE))
);
contentPaneLayout.setVerticalGroup(
contentPaneLayout.createParallelGroup()
.addGroup(GroupLayout.Alignment.TRAILING, contentPaneLayout.createSequentialGroup()
.addContainerGap(144, Short.MAX_VALUE)
.addComponent(button)
.addGap(91, 91, 91))
);
pack();
setLocationRelativeTo(getOwner());
}
private JButton button;


}

Answer

The code provided in your question doesn't even compile so we can't understand what are the requirements. Anyway I'll assume that you want to keep printing while the flag is true, so you'll need a separate thread to run the printing routine:

public class Printer implements Runnable {

  public volatile boolean keepPrinting;

  public static void main(String... args) {
    Printer printer = new Printer();
    Gui gui = new Gui(printer);
    Thread t = new Thread(printer);
    t.start();
  }

  @Override public void run() {
    while (true) {
      if (keepPrinting) {
        System.out.println("It works!");
      }
    }
  }
}