drawing not updating every time I change coordinates in a loop - java
I'm trying to make a space invaders game and I've got an issue where I'm trying to move the spaceinvaders in a loop [though the code shows an iteration of 5 movements in a for] but they aren't updated in the window.
as you can see from the picture, the spaceinvaders have been moved to the right only once, after the iterations of run() have ended
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyledDocument;
import java.util.Random;
public class SpaceInvadersPanel extends JPanel {
boolean running = false;
int indice = 0; //placeholder
int fine = 10; //placeholder
int speed = 10; //placeholder
String correctAnswer = "prova"; //Placeholder
Aliens[] alien = new Aliens[fine];
int alienX = 35;
int alienY = 35;
SpaceInvadersPanel(int SCREEN_WIDTH, int SCREEN_HEIGHT) throws IOException, InterruptedException {
this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
this.setBackground(Color.white);
this.setFocusable(true);
startGame();
}
public void startGame() throws IOException, InterruptedException{
newSpaceInvader();
}
public void newSpaceInvader() {
for(int i = 0; i<alien.length; i++) {
alien[i] = new Aliens(alienX, alienY, speed);
alienX += 50;
if (i == 4) {alienY += 50; alienX = 35;}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
try {
try {
draw(g);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {e.printStackTrace();
}
}
public void draw(Graphics g) throws IOException, InterruptedException {
BufferedImage image = ImageIO.read(new File("C:\\Users\\39340\\Desktop\\", "spaceinvadersart40bianco.png"));
g.setColor(Color.red);
for(int i = 0; i<alien.length; i++) {
g.drawImage(image, alien[i].x, alien[i].y, null);
}
run();
}
public void run() throws IOException, InterruptedException {
for (int i=0; i<5; i++) {System.out.println("sono al run");
move();Thread.sleep(500);}
}
public void move() throws IOException {
for(int i = 0; i<alien.length; i++) {
System.out.println("sto aumentando roba nel move");
System.out.println("alien x = " +alien[i].x);
alien[i].x += 50;
System.out.println("ora alien x = " +alien[i].x);
//alien[i].y += speed;
}
}
public void checkCollision() {}
public void gameOver(Graphics g) {}
}
Related
Java.awt Affine Transform doesn't seem to update image location
I am trying to make a chess game in java, by having a class of pieces and a subclass for each piece. However, When I try to draw the pieces, The position doesn't seem to register. Here is my Piece class: import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import java.awt.geom.AffineTransform; import java.net.URL; public class Piece { public int Id; public int color; public int state; public Image Sprite; public AffineTransform tx; public boolean dragged; public int x; public int y; public Piece(int Id, int color, int position){ dragged = false; this.Id = Id; this.color = color; int x = 100*(position % 8); int y = 100*(position / 8); System.out.println(x); tx = AffineTransform.getTranslateInstance(x, y); init(x, y); } private void init (double a, double b) { tx.setToTranslation(a, b); tx.scale(0.1, 0.1); } private void update(){ tx.setToTranslation(x*1000, y*1000); tx.scale(0.1, 0.1); } protected Image getImage(String path) { Image tempImage = null; try { URL imageURL = Piece.class.getResource(path); tempImage = Toolkit.getDefaultToolkit().getImage(imageURL); } catch (Exception e) {e.printStackTrace();} return tempImage; } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; update(); g2.drawImage(Sprite, tx, null); } } my pawn class: public class Pawn extends Piece { public Pawn(int Id, int color, int position) { super(Id, color, position); this.state = 0; String path = "/imgs/Pieces/"; if(color == 0){ path += "W"; } else{ path += "B"; } path += "_Pawn.png"; Sprite = getImage(path); } } my Board class: Piece[][] board; public Board(){ board = new Piece[8][8]; for(int i = 0; i < 8; i++){ board[1][i] = new Pawn(i, 1, 8+i); } for(int i = 0; i < 8; i++){ board[6][i] = new Pawn(i, 0, 8+i); } } } and my main class: import java.io.IOException; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class Main extends JPanel implements ActionListener, MouseListener, KeyListener{ Color GREEN = new Color( 41, 176, 59); Color WHITE = new Color(254, 255, 228); Board board = new Board(); public static void main(String[] args) { new Main(); } public void paint(Graphics g){ super.paintComponent(g); boolean flag = true; for(int i = 0; i < 8; i++){ for(int j = 0; j < 8; j++){ if(flag){ g.setColor(WHITE); } else{ g.setColor(GREEN); } g.fillRect((j*100), (i*100), ((j+1)*100), ((i+1)*100)); flag = !flag; } flag = !flag; } for(int i = 0; i < 8; i++){ for(int j = 0; j < 8; j++){ if(board.board[i][j] != null){ board.board[i][j].paint(g); } } } } public Main() { JFrame f = new JFrame("Chess"); f.setSize(new Dimension(800, 800)); f.setBackground(Color.blue); f.add(this); f.setResizable(false); f.setLayout(new GridLayout(1,2)); f.addMouseListener(this); f.addKeyListener(this); Timer t = new Timer(16, this); t.start(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } } I had previously written a game that implemented this techqnique, so I'm not sure what could have gone wrong with this one
It's really important to read the documentation, especially for something that is (to my simple brain), complicated. If you have a read of the documentation for AffineTransform#scale Concatenates this transform with a scaling transformation (emphis added by me) This is important, as it seems to apply that each time you call it, it will apply ANOTHER scaling operation. Based on your avaliable code, this means that when the Piece is created, a scale is applied and the each time it's painted, a new scale is applied, until you're basically scaled out of existence. Sooo. I took out your init (applied the scale within the constructor directly instead) and update methods and was able to get a basic result Scaling from 1.0, 0.75, 0.5, 0.25and0.1` (it's there but I had to reduce the size of the output) Runnable example... import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.IOException; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class Test { public static void main(String[] args) { new Test(); } public Test() { EventQueue.invokeLater(new Runnable() { #Override public void run() { try { JFrame frame = new JFrame(); frame.add(new Main()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } catch (IOException ex) { ex.printStackTrace(); } } }); } public class Main extends JPanel implements ActionListener, MouseListener, KeyListener { Color GREEN = new Color(41, 176, 59); Color WHITE = new Color(254, 255, 228); Board board; public Main() throws IOException { board = new Board(); } #Override public Dimension getPreferredSize() { return new Dimension(800, 800); } #Override protected void paintComponent(Graphics g) { super.paintComponent(g); super.paintComponent(g); boolean flag = true; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (flag) { g.setColor(WHITE); } else { g.setColor(GREEN); } g.fillRect((j * 100), (i * 100), ((j + 1) * 100), ((i + 1) * 100)); flag = !flag; } flag = !flag; } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (board.board[i][j] != null) { board.board[i][j].paint(g); } } } } #Override public void actionPerformed(ActionEvent e) { } #Override public void mouseClicked(MouseEvent e) { } #Override public void mousePressed(MouseEvent e) { } #Override public void mouseReleased(MouseEvent e) { } #Override public void mouseEntered(MouseEvent e) { } #Override public void mouseExited(MouseEvent e) { } #Override public void keyTyped(KeyEvent e) { } #Override public void keyPressed(KeyEvent e) { } #Override public void keyReleased(KeyEvent e) { } } public class Board { Piece[][] board; public Board() throws IOException { board = new Piece[8][8]; for (int i = 0; i < 8; i++) { board[1][i] = new Pawn(i, 1, 8 + i); } for (int i = 0; i < 8; i++) { board[6][i] = new Pawn(i, 0, 16 + i); } } } public class Pawn extends Piece { public Pawn(int Id, int color, int position) throws IOException { super(Id, color, position); this.state = 0; String path = "/imgs/Pieces/"; if (color == 0) { path += "W"; } else { path += "B"; } path += "_Pawn.png"; Sprite = getImage(path); } } public class Piece { public int Id; public int color; public int state; public Image Sprite; public AffineTransform tx; public boolean dragged; public int x; public int y; public Piece(int Id, int color, int position) { dragged = false; this.Id = Id; this.color = color; x = 100 * (position % 8); y = 100 * (position / 8); System.out.println(x + "x" + y); tx = AffineTransform.getTranslateInstance(x, y); tx.scale(0.1, 0.1); } protected Image getImage(String path) throws IOException { BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setFont(new JLabel().getFont().deriveFont(Font.PLAIN, 16)); g2d.setColor(Color.BLACK); FontMetrics fm = g2d.getFontMetrics(); int cellX = x; int cellY = y; String text = x + "x" + y; int x = (100 - fm.stringWidth(text)) / 2; int y = ((100 - fm.getHeight()) / 2) + fm.getAscent(); g2d.drawString(text, x, y); g2d.setStroke(new BasicStroke(16)); g2d.drawRect(0, 0, 99, 99); g2d.dispose(); return img; } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.drawImage(Sprite, tx, null); } } }
Key inputs not recognized though use of KeyEvent,KeyListener and much more
I'm using the following code to try to print out an array and move a BufferedPicture ( test ) through the variables of xaxis and yaxis. There is an additional class called "Screen", but it should be irrelevant to this problem. package main.main.start; import javax.swing.JTextField; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.io.File; import java.io.IOException; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import javax.imageio.ImageIO; import javax.swing.JFrame; import main.main.start.graphics.Screen; public class start extends Canvas implements Runnable{ private static final long serialVersionUID = 1L; public static int width = 320; public static int height = width / 16 * 9; public static int scale = 3; public boolean up,left,right,down; public BufferedImage keine,floor,wall,test; public int xaxis,yaxis;{ xaxis = 50; yaxis = 50; } private Thread thread; private JFrame frame; private BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB ); private int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData(); private boolean running = false; private Screen screen; public start (){ Dimension size = new Dimension(width*scale,height*scale); setPreferredSize (size); screen = new Screen(width, height); frame = new JFrame(); } public synchronized void start() { running = true; thread = new Thread(this, "Display"); thread.start(); } public synchronized void stop(){ running = false; try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } public void run(){ while(running == true){ //rendering&updating //System.out.println("running..."); update(); render(); } } public void update() { } public void render() { BufferStrategy bs = getBufferStrategy(); if(bs == null){ createBufferStrategy(3); return; } screen.clear(); screen.render(); for(int i = 0; i < pixels.length; i++){ pixels[i] = screen.pixels[i]; } Graphics g = bs.getDrawGraphics(); g.setColor(Color.BLUE); g.fillRect(0,0,getWidth(), getHeight() ); g.drawImage(image, 0, 0, getWidth(),getHeight(),null); //playercontrollerstart //playercontrollerend //map int[][] map= { {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10} }; int rows = 20; int cols = 20; int i, j; try { keine = ImageIO.read(new File("keine.png")); floor = ImageIO.read(new File("floor.png")); wall = ImageIO.read(new File("wall.png")); test = ImageIO.read(new File("test.png")); } catch (IOException e) { e.printStackTrace(); } for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { if(map[i][j] == 10){ g.drawImage(keine,i*32,j*32,this); } if(map[i][j] == 11){ g.drawImage(wall,i*32,j*32,this); } if(map[i][j] == 12){ g.drawImage(floor,i*32,j*32,this); } } g.drawImage(test,xaxis,yaxis,this); } //mapend g.dispose(); bs.show(); } public static void main(String[] args) { start game = new start(); game.frame.setResizable(false); game.frame.setTitle("TestWindowName"); game.frame.add(game); game.frame.pack(); game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); game.frame.setLocationRelativeTo(null); game.frame.setVisible(true); game.start(); } Then the problem code (there is NO break in the code from } to //StartController //StartController public void keyPressed(KeyEvent q) { if(q.getKeyCode() ==37){ left = true; } if(q.getKeyCode() ==38){ up = true; } if(q.getKeyCode() ==39){ right = true; } if(q.getKeyCode() ==40){ down = true; } } public void keyReleased(KeyEvent q) { if(q.getKeyCode() == 37){ left = false; } if(q.getKeyCode() == 38){ up = false; } if(q.getKeyCode() == 39){ right = false; } if(q.getKeyCode() == 40){ down = false; } } //EndController }
What I believe to be the problem is that you have not implemented or added a KeyListener to your application. You must implement KeyListener, and inherit all methods. Like so: import javax.swing.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; /** * Simple Canvas with KeyListener */ public class TestCanvas extends Canvas implements KeyListener, Runnable { public TestCanvas() { addKeyListener(this); } #Override public void keyTyped(KeyEvent e) { //Do Stuff } #Override public void keyPressed(KeyEvent e) { //Do Stuff } #Override public void keyReleased(KeyEvent e) { //Do Stuff } } Secondly, I would recommend using KeyEvent.VK_(some key) to compare key code values, this way you aren't relying on the assumption that your constants are always true for every keyboard.
Image circling the window using JApplet
So here's where I am stuck... I got it to go to the end of the window horizontally, then go down, but I don't know how to make it go left after it reaches the bottom of the window and then go up when it reaches the left side of the screen. Thanks, import javax.swing.*; import java.awt.*; public class AnimatedImageApplet extends JApplet implements Runnable { private static final long serialVersionUID = 1L; private Thread t = null; private Image image; private int x = 0; private int y = 0; private static final int vx = 1; private static final int vy= 1; private boolean horizontal = true; private boolean vertical = true; public void init() { image = getImage(getDocumentBase(), "face.png"); } public void start() { if (t == null) { t = new Thread(this); t.start(); } } public void paint(Graphics canvas) { canvas.fillRect(0,0,getWidth(),getHeight()); synchronized (this) { canvas.drawImage(image, x, y, this); } } #Override public void run() { int direction = 1; while (true) { synchronized (this) { x += vx * direction; y += vy * (horizontal ? 0 : 1); if (x + image.getWidth(this) == getWidth()) { horizontal = false; direction = 0; } } repaint(); try { Thread.sleep(15); } catch (InterruptedException e) { e.printStackTrace(); } } } }
Conceptually, the idea is simple enough. When you reach one of your edges, you need to change the direction of your movement. if x + image.width > width then go down else if x < 0 then go up else if y + image.height > height then go left else if y < 0 then go right for clock wise motion. import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class MoveTest { public static void main(String[] args) { new MoveTest(); } public MoveTest() { EventQueue.invokeLater(new Runnable() { #Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new TestPane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class TestPane extends JPanel { private BufferedImage img; private int xDelta = 2; private int yDelta = 0; private int x, y = 0; public TestPane() { try { img = ImageIO.read(...); } catch (IOException ex) { ex.printStackTrace(); } Timer timer = new Timer(15, new ActionListener() { #Override public void actionPerformed(ActionEvent e) { x += xDelta; y += yDelta; if (x + img.getWidth() > getWidth()) { x = getWidth() - img.getWidth(); xDelta = 0; yDelta = 2; } else if (x < 0) { x = 0; xDelta = 0; yDelta = -2; } if (y + img.getHeight() > getHeight()) { y = getHeight() - img.getHeight(); xDelta = -2; yDelta = 0; } else if (y < 0) { y = 0; xDelta = 2; yDelta = 0; } repaint(); } }); timer.start(); } #Override public Dimension getPreferredSize() { return new Dimension(200, 200); } #Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.drawImage(img, x, y, this); g2d.dispose(); } } } You should be careful of threads in Swing as Swing is not thread save. Have a look at Concurrency in Swing and How to use Swing Timers for more details
MouseListener on Sprites
I am creating a 6x6 grid memory game. Its requirements is to use an image in a panel as a replacement for the buttons. 210 x 70 The project requires to implement MouseListeners on the following conditions: The button will show first pokebell. When the mouse hovers over the pokeball, it changes into the second pokeball. When the mouse moves away from the pokeball, it reverts back to the first pokeball. When the mouse clicks the pokeball, it changes to the 3rd pokeball. Grid MouseEvents public void mouseEntered(MouseEvent e) { for(i = 0; i < 36; i++){ if(e.getSource() == pkm[i]){ pkb[i].repaint(); } } } public void mouseExited(MouseEvent e) { for(i = 0; i < 36; i++){ if(e.getSource() == pkm[i]){ pkb[i].repaint(); } } } PokeBall class int start = 0; int ht = 0, wt = 0; URL url; BufferedImage img, sp1; public PokeBall(String imgLink, int w, int h, int x){ wt = w; ht = h; start = x; url = this.getClass().getResource(imgLink); try{ img = ImageIO.read(url); } catch(Exception e){ } } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D)g; sp1 = img.getSubimage(start, 0, wt, ht); g2d.drawImage(sp1,20,10,null); if(start == 70) { start = 0; } else { start += 70; } } My thought was that the change of sprite will be invoked on the corresponding mouse event, but instead I got the whole pokeball to animate in an infinite loop even when the mouse didn't invoke any event. I need some ideas or suggestions on how to stop it from looping by itself and to actually call the designated pokeball.
Basically, the responsibility for painting the balls is the PokeBall class, it needs to know when the state has changed, so it makes sense to apply an MouseListener and MouseMotionListener to it. Then you don't need to care about trying to update grid locations and other fun stuff. On your GridPane, I would then attach another MouseListener so you can detect when a ball is clicked and take appropriate action there... import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class MyPokeBalls { public static void main(String[] args) { new MyPokeBalls(); } public MyPokeBalls() { EventQueue.invokeLater(new Runnable() { #Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new PokeBall()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class PokeBall extends JPanel { private BufferedImage balls; private int ballWidth = 70; private int ballHeight = 70; private int ballOffset = 0; public PokeBall() { try { balls = ImageIO.read(new File("PokeBalls.png")); } catch (IOException ex) { ex.printStackTrace(); } MouseAdapter ma = new MouseAdapter() { private boolean isIn = false; #Override public void mouseEntered(MouseEvent e) { ballOffset = 1; isIn = true; repaint(); } #Override public void mouseExited(MouseEvent e) { ballOffset = 0; isIn = true; repaint(); } #Override public void mousePressed(MouseEvent e) { ballOffset = 2; repaint(); } #Override public void mouseReleased(MouseEvent e) { if (isIn) { ballOffset = 1; } else { ballOffset = 2; } repaint(); } }; addMouseListener(ma); addMouseMotionListener(ma); } #Override public Dimension getPreferredSize() { return new Dimension(ballWidth, ballHeight); } #Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (balls != null) { Graphics2D g2d = (Graphics2D) g.create(); BufferedImage ball = balls.getSubimage(ballWidth * ballOffset, 0, ballWidth, ballHeight); int x = (getWidth() - ball.getWidth()) / 2; int y = (getHeight() - ball.getHeight()) / 2; g2d.drawImage(ball, x, y, this); g2d.dispose(); } } } }
AbstractButton b=new JToggleButton(firstIcon); b.setContentAreaFilled(false); b.setFocusable(false); b.setBorder(BorderFactory.createEmptyBorder()); b.setRolloverEnabled(true); b.setRolloverIcon(secondIcon); b.setSelectedIcon(thirdIcon); Why reinventing the wheel? Creating a grid of such buttons is quite simple…
trouble with logic in java
I am trying to get this program to show two pictures and check if they are the same picture, i am having trouble getting bildeSjekk() to do this, it shows all pictures and if you double click a picture it removes it, first i need to store the previous instance of the int i, then when teller should become two when two pictures have been revealed, and then i will use current int i and int temp in the int array index and check if the value is the same. It's a Picture memory game. package prosjekt_1139; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JPanel; #SuppressWarnings("serial") public class Hukommelse extends JPanel implements MouseListener, ActionListener{ //private JLabel[] kort = new JLabel[16]; private JButton nyOmgang = new JButton("Del ut kortene"); private JButton tilbake = new JButton("Tilbake"); private HovedVinduet vindu; private int[] index = new int[16]; private int teller =0, temp = 0; private Image img; private Image[] imgarray; private Rectangle[] bokser; private Point point1; private URL path1, path2[]= new URL[8]; private boolean sjekk[] = new boolean[16]; public Hukommelse(HovedVinduet vindu) throws IOException{ this.vindu = vindu; bokser = new Rectangle[16]; imgarray = new Image[8]; point1 = new Point(); img = null; setBackground(Color.GREEN); setPreferredSize(new Dimension(720,690)); setLocation(0,0); nyOmgang.addActionListener(this); tilbake.addActionListener(this); add(nyOmgang); add(tilbake); this.addMouseListener(this); boks(); } // this is my randomisere metode public void kortIndex(){ int temp; for (int i = 0;i<index.length;i++){ index[i] = i/2; //System.out.println(index[i]); } for (int i=0;i<1000;i++){ int index1 = (int)(Math.random()*16); int index2 = (int)(Math.random()*16); temp = index[index1]; index[index1] = index[index2]; index[index2] = temp; } // for (int i = 0; i<index.length;i++) // System.out.print(index[i]+"\t"); // System.out.println(); } public void paintComponent(Graphics g){ super.paintComponents(g); g.setColor(Color.green); int j = 0; int k = 0; for (int i = 0; i<16;i++){ g.drawImage(img, 20+(k*175), 50+(j*160), 150, 150, this); k++; if(i == 3 || i == 7 || i == 11 || i == 15){ j++; k = 0; } } for (int i=0; i<bokser.length; i++) { if(sjekk[i]){ g.drawImage(imgarray[index[i]], bokser[i].x, bokser[i].y, bokser[i].width, bokser[i].height, this); } } } //Metode For checking if the image is clicked on public void bildeSjekk(){ for (int i = 0;i<bokser.length;i++){ if(bokser[i].contains(point1)){ sjekk[i] = true; teller++; temp = i; } if(teller >= 2 ){ sjekk[i] = false; sjekk[temp] = false; teller = 0; } } } public void boks(){ int j = 0; int k = 0; for(int i = 0; i <bokser.length; i++){ bokser[i] = new Rectangle(20+(j*175), 50+(k*160), 150, 150); j++; if(i == 3 || i == 7 || i == 11 || i == 15){ j =0; k++; } } } public void bilder() throws IOException{ img = ImageIO.read(new File("Image/grass.jpg")); //repaint(); imgarray[0] = ImageIO.read(new File("Image/bekk.jpg")); imgarray[1] = ImageIO.read(new File("Image/solnedgang.jpg")); imgarray[2] = ImageIO.read(new File("Image/tåge.jpg")); imgarray[3] = ImageIO.read(new File("Image/vile.jpg")); imgarray[4] = ImageIO.read(new File("Image/fuglekasse.jpg")); imgarray[5] = ImageIO.read(new File("Image/gullfugl.jpg")); imgarray[6] = ImageIO.read(new File("Image/byen.jpg")); imgarray[7] = ImageIO.read(new File("Image/bekk.jpg")); } #Override public void mouseClicked(MouseEvent agr0) { // TODO Auto-generated method stub } #Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } #Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } #Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub System.out.println(e.getX()+"\t"+e.getY()); point1 = e.getPoint(); bildeSjekk(); repaint(); } #Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } #Override public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("Del ut kortene")){ try { bilder(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } point1 = new Point(0,0); for (int i = 0;i<bokser.length;i++){ sjekk[i] = false; } teller = 0; kortIndex(); repaint(); } if(e.getSource() == tilbake){ vindu.setMenyPanelAktivt(); vindu.setSize(800, 600); vindu.setLocation(0,0); } } }
You might like this related memory game that uses JToggleBUtton and Unicode glyphs instead of pictures. Addendum: As an aside, you may get more helpful answers if you prepare an sscce that doesn't depend on a large number of inaccessible images. As an example, RotatableImage is a simple, static class that can be adapted as required.