V
V
Vitaly Kostyuk2018-05-14 17:36:28
Java
Vitaly Kostyuk, 2018-05-14 17:36:28

How to implement flows here??

i have a myPanel class that is inherited from the JPANEL class and a myFrame class that is inherited from the JFRAME class.
I need to make sure that there is a myPanel class in the stream. I would only add objects of the myPanel class in the myFrame class through the stream.
As a result of the work, the photo should move, the more the better. Here is my code:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.Timer;

import javax.swing.JFrame;
public class Main  {

  public static void main(String[] args) {
    int width = 400;
    int height  = 400;
    
    MyFrame frame = new MyFrame(width, height);
    

  }


}
public class MyFrame extends JFrame  {
  
  Dimension dimension = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
  
  public MyFrame(int width,int height){
    
    
    int x = dimension.width/2-(width/2);
    int y = dimension.width/2-(height/2);
    setBounds(x, y, width, height);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    MyPanel panel = new MyPanel("src/1.png",50);
    add(panel);
    panel.setBounds(0, 0, width, height);
    
    MyPanel panel1 = new MyPanel("src/2.png",50);
    add(panel1);
    panel1.setBounds(0, 150, width, height);
    

    MyPanel panel2 = new MyPanel("src/3.png",50);
    add(panel2);
    panel2.setBounds(0, 200, width, height);
  }


}
public class MyPanel extends JPanel {

  Image img = null;
  
  int a = 0;
  int b = 400;

  int x = a +(int)(Math.random()*b);
  int y = a +(int)(Math.random()*b);
  public MyPanel(String imageName,int t) {
    try {
      img = ImageIO.read((new File(imageName)));
    } catch (IOException e) {
    }

    Timer time = new Timer(t, new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        repaint();

      }
    });
    time.start();

  }

  public void paintComponent(Graphics graphics) {

    graphics.drawImage(img, x, y, null);

    x++;
    
  if(x>400) {
    
    x=0;
  }
    

  }


}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
EVGENY T., 2018-05-14
@VitalyKostyuk

You can make mypanel implements runnable and write the run() method there, in which to move the panel along the frame.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question