Page 1 of 2 12 LastLast
Results 1 to 20 of 37
Like Tree3Likes

Thread: Move Elements

  1. #1
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Red face Move Elements

    Hi guys,
    I have a class that implements JComponent and draw a rectangle and if a key pressed(for example UP) I want to draw it up, and then when down key pressed to draw it down... But I want not only to disappear, but somehow to move, so the user can see the rectagle moving...

    Thank you!

  2. #2
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,782
    Rep Power
    5

    Default Re: Move Elements

    When you press the key you update the coordinates of the rectangle and then invoke a repaint. You need to learn about key listeners and painting.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,563
    Rep Power
    25

    Default Re: Move Elements

    user can see the rectagle moving
    That could also require a Timer to change the rectangle's position over time slowly enough that it appears to be moving and not just jumping from one position to another.
    If you don't understand my response, don't ignore it, ask a question.

  4. #4
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Default Re: Move Elements

    The thing is that I already built my game and it's working fine... I made that if you press a button, all the rectangles ( 16 ) will change the position if needed, and they are removed from frame and drawed again... And I don't know how to do now.

  5. #5
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: Move Elements

    Hi,

    if I understood you correctly, the first problem is, that the control vanishes first and then appears at the new location. Maybe this could be fixed with a call to setIgnoreRepaint so that the windows is not drawn without the control. (But I am also wondering - you just move the existing control or do you remove it and add it again? Maybe you can show us a simple example?)

    And then the second problem might be, that the control "jumps" to the new position. Then you should check out Norms reply which suggested a timer to move the control in multiple steps to the new location (which is seen as a movement by the user).

    With kind regards,

    Konrad

  6. #6
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Default Re: Move Elements

    I have a class that extends JComponent and draws one rectangle. Then, in another class which extends JFrame I add to it the rectangle 4x4 times(into a matrics [][] ). Then I have a logic of the game, which moves the elements depending of the user. (4 directions: up down left and right). After the user press a key, I remove the curent cumponents (remove(component)) check the new logic and add the matrics of rectangles again.
    -add b[][]-matrics of rectangles
    -check what key was pressed
    -remove b[][]- old ones
    -add new components b[][]...

    I know somehow I should repaint them, but didn't worked for me. And now I don't know how to see the rectangles moving around when key pressed...

  7. #7
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Default Re: Move Elements

    Java Code:
    package game2048remade;
    
    public class Game2048 {
        public static void main(String[]args){
            MainFrame mf = new MainFrame();
            mf.addFrame();
        }
    }
    Java Code:
    package game2048remade;
    
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Toolkit;
    import javax.swing.JComponent;
    
    public class GameBox extends JComponent{
        private int posX=0;
        private int posY=0;
        private Color col;
        private Image img=Toolkit.getDefaultToolkit().createImage("/home/flopet17/Desktop/2.png");
        
        public GameBox(int x, int y,Image img){
            this.posX=x;
            this.posY=y;
            this.img=img;
        }
        
        @Override
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setColor(col);
            g2d.drawImage(img,posX,posY,this);
        }
    }
    Java Code:
    package game2048remade;
    
    public class GameLogic{
        
        public int[][] m = new int[6][6];;
        
        private char c;
        public int score;
        public int[][] ifUpPressed(int[][] m){
            this.m=m;
            for(int i=1;i<5;i++)
                for(int j=1;j<5;j++)
                {
                    if(m[i][j]!=0)
                    {
                        int k=i;
                        int l=j;
                        while(m[k-1][l]==0)
                        {
                            m[k-1][l]=m[k][l];
                            m[k][l]=0;
                            k--;
                        }
                        while(m[k-1][l]==m[k][l])
                        {
                            m[k-1][l]=m[k-1][l]+m[k][l];
                            score+=m[k-1][l];
                            m[k][l]=0;
                            k--;
                        }
                    }
                }
            return m;
        } 
        public int[][] ifDownPressed(int[][] m){
            this.m=m;
            for(int i=4;i>0;i--)
                for(int j=4;j>0;j--)
                {
                    if(m[i][j]!=0)
                    {
                        int k=i;
                        int l=j;
                        while(m[k+1][l]==0)
                        {
                            m[k+1][l]=m[k][l];
                            m[k][l]=0;
                            k++; 
                        }
                        while(m[k+1][l]==m[k][l])
                        {
                            m[k+1][l]=m[k+1][l]+m[k][l];
                            score+=m[k+1][l];
                            m[k][l]=0;
                            k++;
                        }
                    }
                }
            return m;
        } 
        public int[][] ifLeftPressed(int[][] m){
            this.m=m;
            for(int i=1;i<5;i++)
                for(int j=1;j<5;j++)
                {
                    if(m[i][j]!=0 )
                    {
                        int k=i;
                        int l=j;
                        while(m[k][l-1]==0)
                        {
                            m[k][l-1]=m[k][l];
                            m[k][l]=0;
                            l--;
                        }
                        while(m[k][l-1]==m[k][l])
                        {
                            m[k][l-1]=m[k][l-1]+m[k][l];
                            score+=m[k][l-1];
                            m[k][l]=0;
                            l--;
                        }
                    }
                }
            return m;
        } 
        public int[][] ifRightPressed(int[][] m){
            this.m=m;
            for(int i=4;i>0;i--)
                for(int j=4;j>0;j--)
                {
                    if(m[i][j]!=0)
                    {
                        int k=i;
                        int l=j;
                        while(m[k][l+1]==0)
                        {
                            m[k][l+1]=m[k][l];
                            m[k][l]=0;
                            l++;
                        }
                        while(m[k][l+1]==m[k][l])
                        {
                            m[k][l+1]=m[k][l+1]+m[k][l];
                            score+=m[k][l+1];
                            m[k][l]=0;
                            l++;
                        }
                    }
                }
            return m;
        }
        public int[][] createMat() {
            for(int i=0;i<6;i++)
                for(int j=0;j<6;j++)
                {
                    if(i==0 || i==5 || j==0 || j==5)
                        m[i][j]=-1;
                    else
                        m[i][j]=0;
                }
            
            int ran1 = (int) Math.floor(Math.random()*4+1);
            int ran2 = (int) Math.floor(Math.random()*4+1);
            int ran3, ran4;
            
            do{
            ran3 = (int) Math.floor(Math.random()*4+1);
            ran4 = (int) Math.floor(Math.random()*4+1);
            }while(ran3==ran1 && ran4==ran2);
            
            m[ran1][ran2]=2;
            m[ran3][ran4]=2;
            
            for(int i=1;i<5;i++){
                for(int j=1;j<5;j++){
                    System.out.print(m[i][j]+"\t");
                }
                System.out.println();
            }
            return m;
        }
        public int[][] addToMat(int [][] m){
            
            int ran3 = (int) Math.floor(Math.random()*4) + 1;
            int ran4 = (int) Math.floor(Math.random()*4) + 1;
            
            while(m[ran3][ran4]!=0){
            ran3 = (int) Math.floor(Math.random()*4) + 1;
            ran4 = (int) Math.floor(Math.random()*4) + 1;
            }
            
            m[ran3][ran4]=2;
            return m;
        }
    }
    Java Code:
    package game2048remade;
    
    import java.awt.Container;
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JFrame;
    import javax.swing.OverlayLayout;
    
    public class MainFrame extends JFrame implements KeyListener{
        private int posX=100;
        private int posY=100;
        private Image img;
        GameBox[][] GB = new GameBox[6][6];
        public void ComponentsPaintFirst(int[][] m){
        for(int i=1;i<5;i++)
            for(int j=1;j<5;j++)
            {
                if(m[i][j]==0)
                {
                    img=Toolkit.getDefaultToolkit().createImage("/home/flopet17/Desktop/2048_images/0.png");
                }
                else if(m[i][j]==2){
                    img=Toolkit.getDefaultToolkit().createImage("/home/flopet17/Desktop/2048_images/2.png");
                }
                GB[i][j]= new GameBox((j-1)*posX+(j-1)*5+10,(i-1)*posY+(i-1)*5+80,img);
                add(GB[i][j]);
            }
        }
        public void ComponentsPaint(int[][] m){
        for(int i=1;i<5;i++)
            for(int j=1;j<5;j++)
            {
                remove(GB[i][j]);
                if(m[i][j]==0)
                {
                    img=Toolkit.getDefaultToolkit().createImage("/home/flopet17/Desktop/2048_images/0.png");
                }
                else if(m[i][j]==2){
                    img=Toolkit.getDefaultToolkit().createImage("/home/flopet17/Desktop/2048_images/2.png");
                }
                else if(m[i][j]==4){
                    img=Toolkit.getDefaultToolkit().createImage("/home/flopet17/Desktop/2048_images/4.png");
                }
                else if(m[i][j]==8){
                    img=Toolkit.getDefaultToolkit().createImage("/home/flopet17/Desktop/2048_images/8.png");
                }
                else if(m[i][j]==16){
                    img=Toolkit.getDefaultToolkit().createImage("/home/flopet17/Desktop/2048_images/16.png");
                }
                else if(m[i][j]==32){
                    img=Toolkit.getDefaultToolkit().createImage("/home/flopet17/Desktop/2048_images/32.png");
                }
                else if(m[i][j]==64){
                    img=Toolkit.getDefaultToolkit().createImage("/home/flopet17/Desktop/2048_images/64.png");
                }
                else if(m[i][j]==128){
                    img=Toolkit.getDefaultToolkit().createImage("/home/flopet17/Desktop/2048_images/128.png");
                }
                else if(m[i][j]==256){
                    img=Toolkit.getDefaultToolkit().createImage("/home/flopet17/Desktop/2048_images/256.png");
                }
                else if(m[i][j]==512){
                    img=Toolkit.getDefaultToolkit().createImage("/home/flopet17/Desktop/2048_images/512.png");
                }
                else if(m[i][j]==1024){
                    img=Toolkit.getDefaultToolkit().createImage("/home/flopet17/Desktop/2048_images/1024.png");
                }
                else if(m[i][j]==2048){
                    img=Toolkit.getDefaultToolkit().createImage("/home/flopet17/Desktop/2048_images/2048.png");
                }
                GB[i][j]= new GameBox((j-1)*posX+(j-1)*5+10,(i-1)*posY+(i-1)*5+80,img);
                add(GB[i][j]);
            }
        }
        
        private int[][] y;
        GameLogic gl = new GameLogic();
        Container c = getContentPane();
        
        
        
        public void addFrame(){
            setTitle("2048");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(438,535);
            c.setLayout(new OverlayLayout(c));
            
            
            y=gl.createMat();
            ComponentsPaintFirst(y);
            addKeyListener(this);
            
            setVisible(true);
        }
    
        @Override
        public void keyTyped(KeyEvent e) {
        }
    
        @Override
        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();
            if(keyCode == KeyEvent.VK_UP){
                gl.ifUpPressed(y);
                System.out.println("UP");
            }
            if(keyCode == KeyEvent.VK_DOWN){
                gl.ifDownPressed(y);
                System.out.println("DOWN");
            }
            if(keyCode == KeyEvent.VK_LEFT){
                gl.ifLeftPressed(y);
                System.out.println("LEFT");
            }
            if(keyCode == KeyEvent.VK_RIGHT){
                gl.ifRightPressed(y);
                System.out.println("RIGHT");
            }
            y=gl.addToMat(y);
            ComponentsPaint(y);
            for(int i=1;i<5;i++){
                for(int j=1;j<5;j++)
                {
                    System.out.print(y[i][j]+" ");
                }
            System.out.println();
            }
        }
    
        @Override
        public void keyReleased(KeyEvent e) {
            invalidate();
            validate();
            repaint();
        }
        
        
    }
    The game works fine, but I want to make the elements to move, not to just appear... I think I have to redo it... What do you think?

  8. #8
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: Move Elements

    Hi,

    just a few thoughts from my side:

    a) You should check if it is really required to remove the component and then add it again. That is something that might not be required. Instead move it and then everything will be repainted.

    b) You load an image multiple times. That is something that I wouldn't do. Just load all images one time and then reuse these images. That way you do not have an image multiple times in memory.

    c) What I did in the past (But that is more than 10 years in the past): I simply created 3 images with the size of the window.
    - one image was used by the game loop to prepare the output.
    - the second one was a spare one. Once of the first image was done, these 2 images was swapped.
    - the third one was used by the paint event to (re)draw the window.
    - I had a reference which simply told me, which image should be used next by the paint method.
    All swapping was done synchronized of course. So after drawing an image and whenever the window was painted, a swap was possible.
    After drawing, I also told the window to redraw.

    That was a double buffering that I build when I created a small java game. I am not saying that this is the best solution but it worked fine for me.

    (Ohh .. be aware that window resizing can cause a lot of work. After an resize you have to create the new images and so on. That is quite fine but you cannot provide this "live changing" where the user still holds the mouse and resizes the window and the content is redrawn all the time! But I do not remember what I had to do and I am not even sure that there was a real issue ... It is just something that goes through the mind of an old man who tells stories of his youth :) )

    With kind regards,

    Konrad
    Flopet17 likes this.

  9. #9
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Default Re: Move Elements

    I don't know how can I just move the components witouth remove and add them again. I tryed for a day or so...

  10. #10
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,563
    Rep Power
    25

    Default Re: Move Elements

    how can I just move the components
    If you look at the way the components are defined and added to the container using the OverlayLayout, all the components have the same bounds. That means that each component can draw anywhere on the whole GUI screen.
    To see: add a call to println to the paintComponent() method of the GameBox class that prints the value returned by getBounds().
    If you don't understand my response, don't ignore it, ask a question.

  11. #11
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,098
    Rep Power
    6

    Default Re: Move Elements

    If I see your code, all it would take is:

    - change X,Y of your boxes
    - repaint the container which holds your components (MainFrame contentpane)
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  12. #12
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Default Re: Move Elements

    I can't just change x,y, I have to change the image too... Check 2048 game. When two tiles with the same number touch, they merge into one.

  13. #13
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,563
    Rep Power
    25

    Default Re: Move Elements

    When two tiles merge does the count of tiles go down by 1? Where is the empty spot when one tile is removed?
    If you don't understand my response, don't ignore it, ask a question.

  14. #14
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,098
    Rep Power
    6

    Default Re: Move Elements

    I understand that you can't just change them, but what I said remains unchanged; to get the things moving on screen, you need to change the X and Y and repaint the parent component.

    That in your game model there are restrictions on how and when you can change the X,Y is entirely besides the point. The only fact remains is that a possible path in your game might be:

    1. the game logic decides that a box should move up
    2. the game logic decides what happens when a box moves up. Lets assume: it can freely move
    3. The game logic 'moves' the box by altering the X,Y position
    4. the UI needs a repaint to see the changes made in step 3

    Another path may be that in step 2 is decided two boxes may merge. Fine, the game logic will do different things and stuff to the game model and the UI will then be updated to reflect those changes.
    Flopet17 likes this.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  15. #15
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Default Re: Move Elements

    It might be a silly question but, I'm trying to redo the game in order to change the errors, and:
    Java Code:
    package repaint;
    public class Repaint {
        public static void main(String[] args) {
            
            MainFrame mf = new MainFrame();
            mf.addFrame();
            mf.setVisible(true);
        }
        
    }
    Java Code:
    package repaint;
    
    import javax.swing.JFrame;
    
    public class MainFrame extends JFrame{
        public void addFrame(){
            setSize(600,500);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setTitle("Test Repaint");
            AllBox al = new AllBox();
            al.AddAllBox();
            add(al);
            
        }
        
    }
    Java Code:
    package repaint;
    
    import javax.swing.JComponent;
    
    public class AllBox extends JComponent{
        
        private final int x=100, y=100, h=100, w=100;
        
        OneBox ob[][] = new OneBox[4][4];
        
        public void AddAllBox () {
            for(int i=0;i<4;i++)
                for(int j=0;j<4;j++)
                {
                    ob[i][j]= new OneBox(i*x,j*y,h,w);
                    add(ob[i][j]);
                    System.out.println(getComponents().length);
                }
            
        }
        
    }
    Java Code:
    package repaint;
    
    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.JComponent;
    
    public class OneBox extends JComponent {
        private int x, y, h, w;
        
        public OneBox(int x,int y,int h,int w){
            this.x=x;
            this.y=y;
            this.h=h;
            this.w=w;
            
        }
        @Override
        public void paintComponent(Graphics g){
            super.paint(g);
            System.out.println("test if comes here");
            g.setColor(Color.yellow);
            g.drawRect(x, y, h, w);
            g.setColor(Color.red);
            g.fillRect(x, y, h, w);
        }
        
    }
    Why it's not going into paintComponent of OneBox class? I used there a println to check and it's not going in there. Why?

    Thank you

  16. #16
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Default Re: Move Elements

    Quote Originally Posted by Norm View Post
    When two tiles merge does the count of tiles go down by 1? Where is the empty spot when one tile is removed?
    The game works fine, all the tiles are ok, they merge into one, the only problem is that I have to make them move, not just add and remove, not I'm trying to understand how to do this.

  17. #17
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,563
    Rep Power
    25

    Default Re: Move Elements

    I'm having a problem understanding that. What does it mean to "merge" two tiles? After the merge how many tiles are there?

    make them move,
    Does that mean changing their location? I see x and y variables. Do they control where a tile is located? Would changing the value of x and/or y change the tile's location?
    If you don't understand my response, don't ignore it, ask a question.

  18. #18
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Default Re: Move Elements

    Quote Originally Posted by Norm View Post
    I'm having a problem understanding that. What does it mean to "merge" two tiles? After the merge how many tiles are there?
    for example you have this:
    0 0 2 0
    2 0 2 0
    0 2 0 0
    2 0 0 0
    After you press the DOWN key you should see this:
    0 0 0 2*
    0 0 0 0
    0 0 0 0
    4 2 4 0
    The 2 of 2 in the column 1 and 3 merged into 4. The 2* is a 2 that randomly appeared in the matrics.
    If we now press a LEFT key you should see this:
    2' 0 0 0
    0 0 0 0
    0 0 0 2**
    4 2 4 0
    The 2' is the old 2* that moved max to left and another 2(the new 2**) appeared randomly.
    If we press again LEFT key:
    2' 0 0 0
    0 2*** 0 0
    2'' 0 0 0
    4 2 4 0
    2' --- old 2*... 2'' --- previous 2** ... 2*** a new 2 randomly appeared.
    If now we press DOWN key:
    0 0 2& 0
    0 0 0 0
    4* 2''' 0 0
    4 2 4 0
    2' and 2'' merged into 4*, 2*** is now 2''' and 2&-> random 2 generated.
    And if we press again DOWN:
    0 0 0 0
    0 0 0 0
    0 0 2^ 0
    8* 4$ 4 0
    4* and 4 merged into 8* ... 2''' and 2 merged into 4$ and another random 2 generated: 2^

    This is the logic of the game...
    The logic works, the interface works well, as I said, the only thing I have to redo is that the tiles have to move on the screen, instead of just appearing in the correct spot.
    The game you can find here: 2048

  19. #19
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,563
    Rep Power
    25

    Default Re: Move Elements

    tiles have to move on the screen
    That would be done with a Timer that repeatedly changes the x/y values and calls repaint until the tile is at its new location.
    If you don't understand my response, don't ignore it, ask a question.

  20. #20
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Default Re: Move Elements

    What classes that extends what do you think i sould use? I tryed alot of methods and... not working for me

Page 1 of 2 12 LastLast

Similar Threads

  1. How to move elements around in Swing?
    By DecoratorFawn82 in forum AWT / Swing
    Replies: 1
    Last Post: 12-03-2013, 04:56 PM
  2. move line
    By ekstends in forum New To Java
    Replies: 3
    Last Post: 06-08-2012, 04:25 PM
  3. Replies: 3
    Last Post: 10-19-2011, 11:42 PM
  4. Move from console to GUI
    By MaxMonic in forum Advanced Java
    Replies: 2
    Last Post: 01-01-2011, 06:34 AM
  5. How to move elements between Arraylists
    By Kerrai in forum New To Java
    Replies: 2
    Last Post: 11-04-2010, 12:44 PM

Posting Permissions

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