Hello, I was creating a simple game, and I wanted to test program. But when I press "Run" on eclipse, nothing happens, "Terminate" button is active so I think, that program running. Here is my code:
import javax.swing.*; public class MainClass { public static void main(String[] args) { JFrame frame = new JFrame("Catch Paulenas"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new GameClass()); frame.setSize(400,400); frame.setVisible(true); } }
import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; 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.Random; public class GameClass extends JPanel{ //Declaring variables private int numberOfHits; private JLabel resultsBar; private BufferedImage target; private int targetX; private int targetY; private Timer timer; private int tryX; private int tryY; private Random rand; //Creating constructor, setting everything default public GameClass(){ numberOfHits = 0; setLayout(new BorderLayout()); setBackground(Color.WHITE); rand = new Random(); getReady(); } //Continue get ready for game private void getReady(){ try{ target = ImageIO.read(new File("target.jpg")); }catch(IOException e){} resultsBar = new JLabel("Number of hits "+ numberOfHits); add(BorderLayout.SOUTH, resultsBar); addMouseListener(new PanelListener()); playGame(); } //Playing game private void playGame(){ while(numberOfHits < 20){ timer = new Timer(rand.nextInt(2000)+1000, new TimerListener()); } } public void paintComponent(Graphics g){ g.drawImage(target,targetX,targetY,null); } //Listener for pressing buttons private class PanelListener implements MouseListener{ public void mouseClicked(MouseEvent e) { tryY = e.getY(); tryX = e.getX(); if(tryY == targetY || tryX == targetX){ numberOfHits++; } } public void mouseEntered(MouseEvent arg0) {} public void mouseExited(MouseEvent arg0) {} public void mousePressed(MouseEvent arg0) {} public void mouseReleased(MouseEvent arg0) {} } //Listener for timer private class TimerListener implements ActionListener{ public void actionPerformed(ActionEvent e) { targetX = rand.nextInt(400)+1; targetY = rand.nextInt(380)+1; repaint(); } } }
Maybe you can see where is the problem, because with syntax is everything good, no errors.