Right now, I've got this really ugly loop in my code that waits for a boolean to be true
before the method can return. It's triggered when "Done" is clicked. I'm wondering, what is the proper way for me to delay this method's return
until the button is pressed? How should I refactor this code so that it follows common practices for this?
Here is the relevant code. It is part of a much bigger application. This is the only place this happens because it is the only custom dialog box in the application. Everything else is done with JOptionPane
, so it doesn't have this problem.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
PrintWriter out = new PrintWriter("textfile.txt");
out.println(GUI.getUserInput());
out.close();
}
}
class GUI implements ActionListener {
private static boolean pressed;
public static String getUserInput() {
pressed = false;
JFrame frame = new JFrame();
frame.setSize(400, 250);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Diary");
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout(4, 2));
JLabel instructionLabel = new JLabel("What's on your mind?");
panel.add(instructionLabel, BorderLayout.NORTH);
JTextArea inputField = new JTextArea("", 7, 30);
inputField.setLineWrap(true);
inputField.setWrapStyleWord(true);
panel.add(new JScrollPane(inputField), BorderLayout.CENTER);
JButton done = new JButton("Done");
done.addActionListener(new GUI());
panel.add(done, BorderLayout.SOUTH);
frame.add(panel);
frame.setVisible(true);
inputField.setCaretPosition(inputField.getText().length());
while (!pressed) { // Wait for the "Done" button to be pressed
// For some reason, there has to be something in this loop for it to work
System.out.println();
}
frame.dispose();
return inputField.getText();
}
public void actionPerformed(ActionEvent e) {
pressed = true;
}
}