C
C
CheshKin2015-06-22 15:35:06
Java
CheshKin, 2015-06-22 15:35:06

How to get rid of flickering when opening Java window?

The opening frame gets annoying with its flickering when centered. Here is the code for a simple program.
Main.java

import javax.swing.*;

public class Main extends JFrame {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Тест фрейма");
        frame.add(new MainMenu());
        frame.setSize(600, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setResizable(false); 
        frame.setLocationRelativeTo(null); //из-за него мерцает???
    }

Then he opens a window, it appears for a millisecond in the upper left corner, and then moves to the center!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rodgenk, 2015-06-23
@CheshKin

The main mistake is that all your code needs to be wrapped:

SwingUtilities.invokeLater(new Runnable() {
// TODO
})

Read about EventDispatchThread in Swing.

V
Vasily, 2015-06-23
@Applez

And you can try setDoubleBuffered(true);
But, of course, you need to launch the window in the interface processing thread.

N
Nikita, 2015-06-23
@jkotkot

You need to move setVisible to the very end.
And there is also a bug in the JDK about flickering in swing. But this way you at least minimize it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question