Results 1 to 3 of 3
  1. #1
    zeraxis is offline Member
    Join Date
    Aug 2011
    Posts
    1
    Rep Power
    0

    Default Can someone help me fix this please?

    For some reason when I run this code nothing at all happens. All I want it to do is have the rectangle move across the screen. Here's my code:

    Java Code:
    package game;
    
    import javax.swing.*;
    
    public class Game {
    	
    	public static void main(String[] args) {
    		new Game();
    	}
    	
    	public Game() {
    		JFrame f = new JFrame("My Graphics");
    		Panel p = new Panel();
    		
    		f.setSize(800, 600);
    		f.setLocationRelativeTo(null);
    		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		f.add(p);
    		f.setVisible(true);
    	}
    
    }
    
    package game;
    
    import java.awt.*;
    import javax.swing.*;
    
    public class Panel extends JPanel {
    
    	private int txtx, txty;
    	private int rectx, recty;
    	private int ovalx, ovaly;
    	private boolean running;
    
    	public Panel() {
    		txtx = 50;
    		txty = 50;
    
    		rectx = 50;
    		recty = 80;
    
    		ovalx = 50;
    		ovaly = 210;
    		
    		running = true;
    
    		setBackground(Color.WHITE);
    		setForeground(Color.BLACK);
    		setFont(new Font("Ariel", Font.PLAIN, 20));
    		
    		gameloop();
    	}
    
    	public void paintComponent(Graphics g) {
    		super.paintComponent(g);
    		Graphics2D g2 = (Graphics2D) g;
    
    		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    				RenderingHints.VALUE_ANTIALIAS_ON);
    
    		g2.drawString("diz iz mah texz", txtx, txty);
    		g2.setColor(Color.RED);
    		g2.fillRect(rectx, recty, 100, 100);
    		g2.setColor(Color.BLUE);
    		g2.fillOval(ovalx, ovaly, 100, 100);
    	}
    
    	public void gameloop() {
    		while (running) {
    			rectx++;
    			repaint();
    
    			try {
    				Thread.sleep(20);
    			} catch (Exception e) {
    
    			}
    		}
    	}
    
    }

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,189
    Rep Power
    19

    Default

    Lesson: Concurrency in Swing (The Java™ Tutorials > Creating a GUI With JFC/Swing)

    Don't run a continuously running loop or Thread#sleep(...) on the EDT. Use a Swing Timer.

    db

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,585
    Rep Power
    23

    Default

    this code nothing at all happens
    When the execution in Panel's constructor calls the never ending loop in gameloop, it never returns.
    It needs to return to allow the JVM to complete the building of your GUI.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •