Good day.
The task is as follows: to realize the movement of the image when pressing the keys W, A, S, D.
I tried to implement it as follows:
I also try to move the object of this class with setLocation ()
package viewPG; import java.awt.image.*; import java.awt.*; import javax.swing.*; import java.io.File; import javax.imageio.ImageIO; import modelPG.IMove; import modelPG.Model; class Person extends JPanel implements IMove{ private Image image; private Model model; Person(Model model) { this.model = model; try { image = ImageIO.read(new File(View.path + "wizard.png")); } catch(Exception e) { } setSize(model.getWidthPerson(), model.getHeightPerson()); setOpaque(false); model.addMoveListener(this); } public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, 0, 0, null); } //Этот метод вызывается из другого потока public void newPoz(int x, int y) { SwingUtilities.invokeLater(new Runnable() { public void run() { setLocation(x, y); } }); } } Here is the class that adds all the objects to the frame:
package viewPG; import java.awt.image.*; import java.awt.*; import javax.swing.*; import java.io.File; import javax.imageio.ImageIO; import modelPG.Model; public class View extends JPanel{ private Model model; private Container container; private Map map; private Person person; static String path = "D:/mapPG/src/graphicsPG/"; public View(Model model, Container container) { this.model = model; this.container = container; map = new Map(model); person = new Person(model); container.add(map); container.add(person); } } If you do not add a Map object to the frame:
container.add(map); That no plume from the moving image does not appear (although the movement is jerky). But if you add, then there is a train. I just can not understand the reason.
Here is the Map class code:
package viewPG; import java.awt.image.*; import java.awt.*; import javax.swing.*; import java.io.File; import javax.imageio.ImageIO; import modelPG.mapPG.MapObject; import modelPG.Model; class Map extends JPanel{ private int width; private int height; private int countCellInRow; private int countCellInColumn; private Image[][] images; private Model model; Map(Model model) { this.model = model; this.width = model.getWidthMap(); this.height = model.getHeightMap(); this.countCellInRow = model.getCountCellInRow(); this.countCellInColumn = model.getCountCellInColumn(); setSize(width, height); images = new Image[countCellInColumn][countCellInRow]; assembleMap(); } //часть кода пропущена public void paintComponent(Graphics g) { for(int y = 0; y < countCellInColumn; y++) { for(int x = 0; x < countCellInRow; x++) { if(images[y][x] != null) { int pozX = model.getCellInRowAndColumn(x, y).CENTER_X - images[y][x].getWidth(null) / 2; int pozY = model.getCellInRowAndColumn(x, y).CENTER_Y - images[y][x].getHeight(null); g.drawImage(images[y][x], pozX, pozY, null); } } } }