0

Here I have two classes:

Test Class:

public class test {
    private static JPanel contentPane;
    private static JFrame frame = new JFrame("Sleeping");
    private static JTextPane textPane;
    private static StyledDocument doc;
    private static Thread sleep;
    private static HandleMouse S = new HandleMouse();

public static void main(String[] args) {

    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    frame.setBounds(0, 0, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    frame.setContentPane(contentPane);
    frame.setLocationRelativeTo(null);

    JPanel panel = new JPanel();
    contentPane.add(panel, BorderLayout.CENTER);
    panel.setLayout(new BorderLayout(0, 0));

    textPane = new JTextPane();
    panel.add(textPane, BorderLayout.CENTER);

    doc = textPane.getStyledDocument();
    SimpleAttributeSet center = new SimpleAttributeSet();
    StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
    doc.setParagraphAttributes(doc.getLength() + 1, 1, center, false);

    textPane.setEditable(false);
    sleep = new Thread(() -> {
        try {
            textPane.setBackground(new Color(59, 82, 217));
            Thread.sleep(1200);
            doc.insertString(doc.getLength(), "Waiting for sleep, I drift from thoughts like these;\n", null);
            Thread.sleep(1200);
            doc.insertString(doc.getLength(), "And where to-day was dream-like, build my dreams.\n", null);
            Thread.sleep(1200);
            doc.insertString(doc.getLength(), "Across my brain, ghost of remembered chords\n ", null);
            Thread.sleep(1200);
            doc.insertString(doc.getLength(), "Which still can make such radiance in my dream.\n", null);
            Thread.sleep(1200);
            doc.insertString(doc.getLength(), "And count their faces; faces; sunlit faces.\n", null);
            Thread.sleep(1200);
            doc.insertString(doc.getLength(), "Falling asleep ... the herons, and the hounds....\n", null);
            Thread.sleep(1200);
            doc.insertString(doc.getLength(), "September in the darkness; and the world I've known\n", null);
            Thread.sleep(1200);
            doc.insertString(doc.getLength(), "all fading past me into peace. ", null);

        } catch (BadLocationException | InterruptedException e) {

        }
    });

    frame.setResizable(false);
    frame.setVisible(true);
    sleep.start();

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    textPane.addMouseMotionListener(S);
    frame.addMouseMotionListener(S);

}

}

and another inner class that is within the test class which handles the mouse motion:

public static class HandleMouse implements MouseMotionListener {

    @Override
    public synchronized void mouseDragged(MouseEvent e) {
        textPane.setText("Test");
        ifinterrupt();
    }

    @Override
    public synchronized void mouseMoved(MouseEvent e) {
        textPane.setText("Test");
        ifinterrupt();

    }

    private void ifinterrupt() {
        sleep.interrupt();
        textPane.removeMouseMotionListener(S);
        frame.removeMouseMotionListener(S);
        textPane.setBackground(Color.RED);
        try {
            Thread.sleep(1000);
            System.exit(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

However, when I move my mouse and trigger the mouseMoved method, the JFrame exits(System.exit(0)) before the this line is executed:

textPane.setText("Test");

but in theory it should set the text to "Test" before exiting, as setTextis set before the ifinterrupt() line:

textPane.setText("Test");
ifinterrupt();

My question is, why does the JFrame exit before the text is set and what causes it?

Any help is appreciated.

3
  • Don't over use static; don't use null layouts; don't block the event dispatching thread Mar 31, 2016 at 4:39
  • The problem is with your ifintergrupt(); You invoke Thread.sleep() which block current Thread before re-paint the UI
    – An Do
    Mar 31, 2016 at 4:49
  • 1
    @Joseph The problem is every where in the code, the OP is violating the single threaded nature of Swing Mar 31, 2016 at 5:26

2 Answers 2

1

If you want to wait 1sec to see the GUI re-rendered, don't block the EDT but create a new timer instead and close your frame inside this timer

        Thread r = new Thread() {
            public void run() {
                try {
                    sleep(1000);
                    System.exit(0);
                } catch (InterruptedException e) {
                }
            };
        };
        r.start();
1

If you want to change something on the GUI then you should use EDT(Event Dispatch Thread). ALL interactions with any UI/Swing component MUST be done within the context of the EDT

When starting an application, you should ensure that you are executing within the EDT BEFORE you try and create/interact with any Swing component.

Use this code. The below thread is known as Event handling thread. Write the codes that make changes in the UI within this thread or call the method containing the code from this thread.

EventQueue.invokeLater(new Runnable() {
    public void run() {
        // Now in the event dispatching thread
    }
});

EDT will queue your changes on the UI and run according to the priority.

1
  • Except ifinterrupt is called in the EDT, so it'll prevent it from updating the ui before System.exit is called :P Mar 31, 2016 at 4:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.