0

I want to have a Frame in which I have while loop, that every frame it paints something differently. It's working, but how can I stop it using X button in upper right corner?

Main:

import java.awt.*;

public class Main {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                MainFrame frame = new MainFrame();
                frame.draw();
            }
        });


    }
}

MainFrame:

import javax.swing.*;
import java.awt.*;

public class MainFrame extends JFrame {
    private JPanel panel;

    public MainFrame() {
        super("Objects simulation");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setExtendedState(JFrame.MAXIMIZED_BOTH);
        setResizable(true);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        setSize(d);

        panel = new JPanel();
        panel.setSize(d);
        panel.setBackground(Color.BLACK);
        add(panel);

        setVisible(true);
    }

    public void draw() {
        while(true) {
            //Paint something differently
        }
    }
}

Thanks in advance!

camickr
  • 321,443
  • 19
  • 166
  • 288
  • 1
    The structure of your code is wrong: 1) Don't use a while loop to do animation. Instead use a [Swing Timer](https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) to schedule the animation. 2) Custom painting is done by overriding the `paintComponent(...) method of a JPanel and then you add the panel to the frame. See [Custom Painting](https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) for basic information. You can also check out: https://stackoverflow.com/a/54028681/131872 for a working example using the above suggestions. – camickr Sep 15 '20 at 17:22
  • 1
    *but how can I stop it using X button in upper right corner?* - not sure what the point of that is. The "X" button is used to close the frame. You should add a separate button to the frame and then use an ActionListener and you can then just stop the Timer. – camickr Sep 15 '20 at 17:24

0 Answers0