Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Moving Selection

  1. #1
    Junior Member
    Join Date
    Jan 2014
    Posts
    22
    My Mood
    Happy
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Moving Selection

    Hello, i'm making a simple game where there's a 10x10 grid and you can move around a selection box and you can move around. Iv'e been trying to make the green selection box to move around but it won't move! I only have right movement in the code but it won't work so far. Here are the classes that have to do greatly with each other.

    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.KeyEvent;
    import java.awt.image.BufferStrategy;
    import java.util.Random;
     
    public class Game extends Canvas implements Runnable{
    	private static final long serialVersionUID = 1L;
     
    	private boolean running = false;
    	private Thread thread;
     
    	public static int WIDTH, HEIGHT;
     
    	Handler handler;
    	Graphics g;
    	Random rand = new Random();
    	Selection select;
     
    	public void init(){
    		handler = new Handler();
    		select = new Selection(0, 0);
    		this.addKeyListener(new KeyInput(this));
    		this.requestFocus();
     
    		for (int i = 0; i < 100; i++){
    			int R = rand.nextInt(21);
    			int G = rand.nextInt(21);
    			int B = rand.nextInt(255);
     
    			Color randomColor = new Color(R,G,B);
    		    handler.addObject(new Square(rand.nextInt(10) * 61, rand.nextInt(10) * 61, ObjectId.Square, randomColor));
    		}
    	}
     
    	public void run(){
    		init();
    		this.requestFocus();
    		long lastTime = System.nanoTime();
    		double amountOfTicks = 60.0;
    		double ns = 1000000000 / amountOfTicks;
    		double delta = 0;
    		long timer = System.currentTimeMillis();
    		int updates = 0;
    		int frames = 0;
    		while(running){
    			long now = System.nanoTime();
    			delta += (now - lastTime) / ns;
    			lastTime = now;
    			while(delta >= 1){
    				tick();
    				updates++;
    				delta--;
    			}
    			render();
    			frames++;
     
    			if(System.currentTimeMillis() - timer > 1000){
    				timer += 1000;
    				System.out.println("FPS: " + frames + " TICKS: " + updates);
    				frames = 0;
    				updates = 0;
    			}
    		}
    	}
     
    	public void tick(){
     
    		handler.tick();
    	}
     
    	public void render(){
     
    		BufferStrategy bs = this.getBufferStrategy();
    		if (bs == null){
    			this.createBufferStrategy(3);
    			return;
    		}
     
    		Graphics g = bs.getDrawGraphics();
    		/////////////////////////////////
    		//Draw Here
    		g.setColor(Color.BLACK);
    		g.fillRect(0, 0, getWidth(), getHeight());
     
    		handler.render(g);
    		select.render(g);
     
    		for(int x = 0; x < 600; x+=61){
    			for (int y = 0; y < 600; y +=61){
    			g.setColor(Color.white);
    			g.drawRect(x, y, 61, 61);
    		}
    		}
     
    		/////////////////////////////////
    		g.dispose();
    		bs.show();
    	}
     
    	public synchronized void start(){
    		if (running){
    			return;
    		}
     
    		running = true;
    		thread = new Thread(this);
    		thread.start();
    	}
     
    	public synchronized void stop(){
     
    	}
     
    	public static void main(String[] args){
    		new Window(600, 600, "Squares", new Game());
    	}
    //this is not working for moving the selection box r
    	public void keyPressed(KeyEvent e) {
    		int key = e.getKeyCode();
     
    		if (key == KeyEvent.VK_RIGHT || key == KeyEvent.VK_D){
    			select.setX(61);
    		}
    	}
     
    	public void KeyReleased(KeyEvent e) {
    		int key = e.getKeyCode();
     
    		if (key == KeyEvent.VK_RIGHT || key == KeyEvent.VK_D){
    			select.setX(getX());
    		}
     
    	}
     
    }

    Selection class
    import java.awt.Color;
    import java.awt.Graphics;
     
    public class Selection {
     
    	Graphics g;
    	private double x, y;
     
    	public Selection(double x, double y){
    		this.x = x;
    		this.y = y;
    	}
     
    	public void render(Graphics g){
    		g.setColor(Color.GREEN);
    		g.fillRect((int)x, (int)y, 61, 61);
    	}
     
    	public void tick(){
     
    	}
     
    	public double getX() {
    		return x;
    	}
     
    	public void setX(double x) {
    		this.x = x;
    	}
     
    	public double getY() {
    		return y;
    	}
     
    	public void setY(double y) {
    		this.y = y;
    	}
     
    }

    KeyInput Class
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
     
    public class KeyInput extends KeyAdapter{
     
    	Game game;
     
    	public KeyInput(Game game){
    		this.game = game;
    	}
     
    	public void KeyPressed(KeyEvent e){
    		game.keyPressed(e);
    	}
     
    	public void KeyReleased(KeyEvent e){
    		game.KeyReleased(e);
    	}
     
    }

    I also tried an approach where you click with the move and it snaps to a tile grid but that didn't work either. Help is MUCH appreciated. I also messed with it a lot so don't be surprised if it's pretty messy


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Moving Selection

    Why aren't you using Swing and the more up-to-date techniques that go along with it?

  3. #3
    Junior Member
    Join Date
    Jan 2014
    Posts
    22
    My Mood
    Happy
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Moving Selection

    Could you give examples on how I could make it work?

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Moving Selection

    Do you mean using Swing and the more modern techniques, or fixing what you have?

    Edit: Never mind. I'll build you a modern example that does what you describe.

  5. #5
    Junior Member
    Join Date
    Jan 2014
    Posts
    22
    My Mood
    Happy
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Moving Selection

    Thanks!

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Moving Selection

    Thrown together hastily, but I hope completely and with sufficient comments to give you insight into what's going on. Ask questions as needed.
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.GridLayout;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
     
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
     
    // a JFrame to hold a JPanel. the JPanel contains a 10x10 grid with one chosen
    // square colored green that can be moved around using the arrow keys
    public class TCJGame
    {
        // instance variables
        private JFrame tcjGameFrame;
        private TCJPanel tcjPanel;
     
        // default constructor
        public TCJGame()
        {
            // initialize the frame - the main container
            tcjGameFrame = new JFrame( "TCJ Game Example" );
            tcjGameFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            tcjGameFrame.setFocusable( true );
     
            // add the contents
            tcjPanel = new TCJPanel();
            tcjPanel.requestFocusInWindow();
            tcjGameFrame.add( tcjPanel );
     
            // add a key listener to the main container. this same effect should
            // work with the key listener on the JPanel 
            tcjGameFrame.addKeyListener( new TCJKeyListener( tcjPanel ) );
     
            // size the container to the component(s) and make it visible
            tcjGameFrame.pack();
            tcjGameFrame.setVisible( true );
            tcjGameFrame.requestFocusInWindow();
     
        } // end default constructor
     
        private final class TCJKeyListener implements KeyListener
        {
            // instance variables
            TCJPanel tcjPanel;
     
            // single parameter constructor to identify target
            public TCJKeyListener( TCJPanel tcjPanel )
            {
                this.tcjPanel = tcjPanel;
     
            } // end constructor
     
            @Override
            public void keyTyped(KeyEvent e)
            {
                System.out.println( "Processing key typed." );
     
            } // end method keyTyped()
     
            @Override
            public void keyPressed(KeyEvent e)
            {
                // an indication which method is being processed
                System.out.println( "Processing key pressed." );
     
                int keyCode = e.getKeyCode();
     
                if ( keyCode == KeyEvent.VK_UP )
                {
                    // move the chosen square up one
                    tcjPanel.setChosenRow( -1 );
                }
                else if ( keyCode == KeyEvent.VK_LEFT )
                {
                    // move the chosen square up one
                    tcjPanel.setChosenColumn( -1 );
                }
                else if ( keyCode == KeyEvent.VK_RIGHT )
                {
                    // move the chosen square right one
                    tcjPanel.setChosenColumn( 1 );
                }
                else if ( keyCode == KeyEvent.VK_DOWN )
                {
                    // move the chosen square down one
                    tcjPanel.setChosenRow( 1 );
                }
     
            } // end method keyPressed()
     
            @Override
            public void keyReleased(KeyEvent e)
            {
                // nothing for now 
                System.out.println( "Processing key released." );
     
            } // end method keyReleased()
     
        } // end class TCJKeyListener
     
     
        private final class TCJPanel extends JPanel
        {
            // instance variables
            private JLabel[][] squares;
            private JLabel chosenSquare;
            private int chosenRow;
            private int chosenColumn;
     
            // default constructor
            public TCJPanel()
            {
                // initialize the JPanel to 600x600 and a 10 x 10 grid
                setPreferredSize( new Dimension( 600, 600 ) );
                setLayout( new GridLayout( 10, 10 ) );
     
                // initialize the squares
                squares = new JLabel[10][10];
     
                // for each row . . .
                for ( int i = 0 ; i < 10 ; i++ )
                {
                    // for each column
                    for ( int j = 0 ; j < 10 ; j++ )
                    {
                        // initialize each square
                        squares[i][j] = new JLabel();
                        squares[i][j].setOpaque( true );
                        // number the squares so that their location can be seen
                        // comment out the next line to remove location text
                        squares[i][j].setText(  "  " + i + "   " + j );
     
                        // add each square to the JPanel
                        add( squares[i][j] );
                    }
                }
     
                // set the chosen row and column (the square is set in the
                // paintComponent() method)
                chosenRow = 4;
                chosenColumn = 4;
     
            } // end default constructor
     
     
            @Override
            public void paintComponent( Graphics g )
            {
                // clear the panel's drawing area
                super.paintComponent( g );
     
                // refresh the chosen square
                chosenSquare = squares[chosenRow][chosenColumn];
     
                // set all squares white
                // for each row . . .
                for ( int i = 0 ; i < 10 ; i++ )
                {
                    // for each column
                    for ( int j = 0 ; j < 10 ; j++ )
                    {
                        // color each square white
                        squares[i][j].setBackground( Color.WHITE );
                    }
                }
     
                // set the one chosen square green
                chosenSquare.setBackground( Color.GREEN );
     
            } // end method paintComponent()
     
            // methods to move the chosen square. there are other options. this
            // implementation stops the chosen square movement at the edges, but
            // the square could also wrap to the other side
            public void setChosenRow( int direction )
            {
                // keep the green square on the 10 x 10 grid (limits could
                // be generalized)
                if ( chosenRow + direction < 0 || chosenRow + direction > 9 )
                {
                    // do nothing
                }
                else
                {
                    chosenRow += direction;
                    repaint();
                }
     
            } // end method setChosenRow()
     
            public void setChosenColumn( int direction )
            {
                // keep the green square on the 10 x 10 grid (limits could
                // be generalized)
                if ( chosenColumn + direction < 0 || chosenColumn + direction > 9 )
                {
                    // do nothing
                }
                else
                {
                    chosenColumn += direction;
                    repaint();
                }
     
            } // end method setChosenRow()
     
        } // end class TCJPanel
     
        // a main() method to launch the demo on the EDT
        public static void main( String[] args )
        {
            SwingUtilities.invokeLater( new Runnable()
            {
                @Override
                public void run()
                {
                    new TCJGame();
     
                } // end method run()
     
            } );
     
        } // end method main()
     
    } // end class TCJGame

  7. #7
    Junior Member
    Join Date
    Jan 2014
    Posts
    22
    My Mood
    Happy
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Moving Selection

    Wow! That's great and pretty simple! I only have two questions...

    1. How do I set the JFrame to be in the middle of the screen? I usually just use JFrame.setLocationRelativeTo(null) and that works but not in this situation.

    2. Would you recommend to use Swing for all games?

    Thanks again!

  8. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Moving Selection

    Yes, it really is simple, essentially cookbook once you understand a few basic techniques and can vary them to fit different situations.

    1. You can use either of these methods:

    tcjGameFrame.setLocationRelativeTo( null );
    tcjGameFrame.setLocation( x, y );

    as needed to locate the main frame. x and y can be fixed or calculated based on the screen size. Why what you tried did not work for you is uncertain. You'll have to show what you tried.

    2. All games? I wouldn't make a statement that broad and definite. BUT, if the choice is to use either AWT or Swing to code Java games, I would definitely recommend Swing.

Similar Threads

  1. selection sorting help?
    By namenamename in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 2nd, 2013, 05:11 PM
  2. Help with Course Selection
    By randy81 in forum The Cafe
    Replies: 4
    Last Post: August 14th, 2013, 03:51 AM
  3. IDE Selection
    By vinodlondhe in forum Java IDEs
    Replies: 5
    Last Post: January 23rd, 2013, 05:56 AM
  4. Selection with a for loop
    By sowmyad96 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 26th, 2012, 09:21 AM
  5. Selection Sorting
    By chronoz13 in forum Algorithms & Recursion
    Replies: 5
    Last Post: December 10th, 2009, 11:08 AM