I'm starting to learn Java.

Example: you need a picture (circle) to reach the border of the window and come back. One way I did it, the other way I do not know how to return it.

The code itself:

import java.awt.*; import java.awt.event.*; import java.io.*; import javax.imageio.*; import javax.swing.*; public class Proj { public static void main(String[] args) { myFrame o = new myFrame(); } } class myFrame extends JFrame{ public myFrame() { myPanel p =new myPanel(); Container c = getContentPane(); c.add(p); setBounds(0,0,800,600); setVisible(true); } } class myPanel extends JPanel { private Image img; private int x=0, y=0; private Timer t1,t2; public myPanel() { t1= new Timer(5, new ActionListener() { public void actionPerformed (ActionEvent e) { x++; repaint(); } }); t1.start(); try { img = ImageIO.read(new File("./cir.png")); } catch(IOException exp) { JOptionPane.showMessageDialog(null, "Error!"); } t2 =new Timer(10, new ActionListener() { public void actionPerformed (ActionEvent e) { if((x+img.getWidth(null))>=790) { t1.stop(); } } }); } public void paintComponent (Graphics g) { super.paintComponent(g); g.drawImage(img, x, y,50,50,null); } } 

    1 answer 1

     package main; import java.awt.Container; import java.awt.Graphics; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class Proj { public static void main(String[] args) throws IOException { new Proj().new MyFrame(); } class MyFrame extends JFrame{ public MyFrame() throws IOException { MyPanel p =new MyPanel(); Container c = getContentPane(); c.add(p); setBounds(0,0,800,600); setVisible(true); } } class MyPanel extends JPanel { private Image img; private int x=0, y=0; private Timer t1,t2; private int direction = 1; public MyPanel() throws IOException { loadImage(); t1= new Timer(5, new ActionListener() { public void actionPerformed (ActionEvent e) { x += direction; if((x+img.getWidth(null))>=790) direction = -1; repaint(); } }); t1.start(); } private void loadImage() throws IOException { ImageIcon ii = new ImageIcon("C:/Users/Николай/eclipse-workspace/Proj/src/main/cir.png"); img = ii.getImage(); } public void paintComponent (Graphics g) { super.paintComponent(g); g.drawImage(img, x, y,null); } } } 
    • Thank you very much! - Alena