简体   繁体   中英

JAVA: How to set a string value to be returned, when a button is pressed?

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";
        }
        
    }
    
}

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));
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM