Rafael Rondon
Rafael Rondon

Reputation: 27

Moving a rectangle down a JFrame

I'm trying to make a program to move rectangles down a JFrame, can anyone explain why this doesn't work?

public class DrawingComponent extends JLabel {

public static int x = 0;

public void paintComponent(Graphics g){
    Graphics2D g2 = (Graphics2D) g;
    Rectangle rect = new Rectangle(50,x,50,50);
    g2.draw(rect);
    x = x+100;
}
}

public class GameL {

javax.swing.JFrame frame = new javax.swing.JFrame();

public static void main(String[] args) {
        GameL tetris = new GameL();
        tetris.start();     
}

public void start(){
    //setup frame
    frame.setSize(800,600);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

    TimerEH timereh = new TimerEH();
    Timer timer = new Timer(5000,timereh);
    timer.start();          
}

class TimerEH implements ActionListener{        
    public void actionPerformed(ActionEvent e){
        DrawingComponent dc = new DrawingComponent();
        frame.add(dc);
    }       
}
}

Upvotes: 0

Views: 4315

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347204

You're creating a new DrawingComponent and adding it to the frame on each tick cycle. That's a lot of DrawComponents

While it is possible to animation a component by moving it, you would need to provide more information as to why you want to do it this way. The preferred method would be to use something like a JPanel, add it the frame that's using a BorderLayout and override the panels paintComponent method.

The issue with trying "move" the component is components have a defined space in which they can render, from the looks of you code, you label is likely to have a size of 0x0, which isn't much space to paint in at all...

Updated with example

So, the following example demonstrates the painting of a rectangle WITHIN the confines of component by using a layout manager that will attempt to size the component to the available usable space.

It also shows the user getPreferredSize to provide useful size hints back to the layout manager.

enter image description here

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class CreppyRectangle {

    public static void main(String[] args) {
        new CreppyRectangle();
    }

    public CreppyRectangle() {
        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 GridLayout(0, 6));
                frame.add(new TestPane(Color.RED));
                frame.add(new TestPane(Color.GREEN));
                frame.add(new TestPane(Color.BLUE));
                frame.add(new TestPane(Color.ORANGE));
                frame.add(new TestPane(Color.PINK));
                frame.add(new TestPane(Color.MAGENTA));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private int yPos;
        private int size = 25 + (int)Math.round(Math.random() * 50);
        private int yDelta = 5 + (int)Math.round(Math.random() * 10);

        public TestPane(Color foreground) {
            setForeground(foreground);
            Timer timer = new Timer(40, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    yPos += yDelta;
                    if (yPos < 0) {
                        yPos = 0;
                        yDelta *= -1;
                        System.out.println(yDelta);
                    } else if (yPos + size > getHeight()) {
                        yPos = getHeight() - size;
                        yDelta *= -1;
                    }
                    repaint();
                }
            });
            timer.setRepeats(true);
            timer.setCoalesce(true);
            timer.start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(50, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(getForeground());
            g2d.drawRect(0, yPos, getWidth() - 1, size);
            g2d.dispose();
        }
    }

}

Upvotes: 4

Related Questions