In general, I wanted to create in the main method an object of the class Main , in the constructor of which a JFrame window is created, then the run method is started, in which the draw method is executed in 5 seconds ... What does it change in the constructor or the run method to make it work ?

 import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.util.Date; public class Main extends JPanel implements Runnable { public static void main(String[] args) { Main main = new Main(); System.out.println("Прошло 5 сек"); } //Переменные public final static String name = "TEST"; //Название public static final int WIDTH = 600; //ШИРИНА public static final int HEIGHT = 600; //ВЫСОТА private Date x; private Date endTime; private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); private Graphics2D g =(Graphics2D) image.getGraphics(); private boolean fourSec = true; //Цикл //Конструктор public Main() { JFrame f = new JFrame(name); f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); f.setSize(WIDTH, HEIGHT); f.setFocusable(false); f.setResizable(false); f.setLocationRelativeTo(null); f.setVisible(true); run(); f.dispose(); } @Override public void run() { x = new Date(); long xPlusFourSec = x.getTime() + 5000; endTime = new Date(xPlusFourSec); while (fourSec) { if (!x.after(endTime)) { x = new Date(); upDate(); draw(g); System.out.println(endTime.getTime() - x.getTime()); } else { fourSec = false; } } } public void draw(Graphics2D g) { g.drawImage(image, 0, 0, null); g.setColor(new Color(0, 0, 0)); g.fillRect(0, 0, WIDTH / 2, WIDTH / 2); g.drawString("TEST STRING", WIDTH / 2, HEIGHT / 2); } public void upDate() { } } 

    1 answer 1

    This method draws. He draws on the image :

     private Graphics2D g =(Graphics2D) image.getGraphics(); 

    And for drawing in the window you need to get the Graphics2D from the window. Look for ways in the documentation.

    And even better - to inherit from JFrame and overload the drawing method, then you do not have to twist the cycle.

    • Thanks for the answer, I will try to look for something, even though I did not quite understand. I thought g.drawImage (image, 0, 0, null); just imposes a picture on the frame, and on the picture you can already draw. - Danya
    • @ Danya, he would overlay the picture on the frame if the object g was created from the frame. But now he draws a picture on the same picture. - Pavel Mayorov