Reputation: 51
When I call the Main.main(null) from other .java file,
return_str = "Not assigned!";
is returned by the main(), before the user could press the "Student" button and
return_str = "student sign-in";
is executed.
public class Main extends JFrame {
private static JPanel contentPane;
static Main frame;
static String return_str;
static JButton btnStudent = new JButton("Student");
/**
* Launch the application.
*/
public static String main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new Main();
frame.setVisible(true);
btnStudent.addActionListener(new Action_student());
contentPane.add(btnStudent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
return_str = "Not assigned!";
System.out.println(return_str);
return return_str;
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnStudent.setFont(new Font("Times New Roman", Font.PLAIN, 16));
btnStudent.setBounds(171, 148, 85, 21);
contentPane.add(btnStudent);
}
static class Action_student implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
return_str = "student sign-in";
}
}
}
Upvotes: 0
Views: 191
Reputation: 4475
As the method already indicates, the frame creation is 'invoked later' meaning in another thread. So you have to let your main routine wait for the button to be pressed.
Add a new variable to the Main class:
static boolean studentEntered = false;
In the action listener sets the studentEntered flag to true:
static class Action_student implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
return_str = "student sign-in";
Main.studentEntered = true;
}
}
In the main method you change your last lines to:
return_str = "Not assigned!";
while (!studentEntered) {
// loop as long as the flag is not switched
}
System.out.println(return_str);
try {
return return_str;
} finally {
// close the frame by the application otherwise your application will not stop
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
}
Upvotes: 1
Reputation: 703
The problem is how a Listener works!
When you create your button, you are assigning a listener to that, it means that ONLY when the button is pressed your string is going to change!
The output is correct, because after creating the listener it executes the rest of code, in your case
return_str = "Not assigned!";
System.out.println(return_str);
You have to change the way you return the string.
Upvotes: 0