E
E
Ernest Farukshin2019-08-24 21:18:42
Java
Ernest Farukshin, 2019-08-24 21:18:42

Why doesn't the code work without else?

Why if you do not write else with sout then the number does not change

public class Main {
    static JFrame jFrame = getJFrame();
    static  int width = jFrame.getBounds().width;
    static  int height = jFrame.getBounds().height;

    public static void main(String[] args) {
        JLabel labelx = new JLabel();
        JLabel labely = new JLabel();
        jFrame.add(labelx);
        jFrame.add(labely);
        labelx.setText(jFrame.getBounds().width + " width");
        labely.setText(jFrame.getBounds().height + " height");
        jFrame.revalidate();
        while (true){
            if(width != jFrame.getBounds().width || height != jFrame.getBounds().height){
                labelx.setText(jFrame.getBounds().width + " width");
                labely.setText(jFrame.getBounds().height + " height");
                width = jFrame.getBounds().width;
                height = jFrame.getBounds().height;

            }else{
                System.out.println();
            }
        }
    }
    private static JFrame getJFrame(){
        JFrame jFrame = new JFrame();
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension screensize = tk.getScreenSize();

        jFrame.setBounds(screensize.width/2-250,screensize.height/2-250,500,500);
        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        return jFrame;
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-08-25
@Ernest3

When a window is created, an Event Dispatch Thread is created , inside which an infinite loop spins, at each iteration getting an event from the queue and launching a handler for it. It is useless to use loops to change the interface, since all changes will simply queue up and will only be executed on one of the next iterations of the event loop. And since your infinite whileruns orders of magnitude faster than the Event Thread 's loop , the event queue just fills up. System.out.println()is a blocking operation, so calling it gives the event loop time to parse the queue.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question