-1

I asked a question last week about Gui and Timers... well after lots of research i found nothing that would work with my code... If anyone could take my code and somehow manipulate it to work that would be amazing... I want my code to display a box and then making it overlap with a box with the same color as the back ground and then a new box being displayed right beside it with a delay

first code:

import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.Color;

public class MovingSomething extends JPanel
{
    public void paintComponent (final Graphics g)
    {     
        int i = 20;
        int cons = 50;
        int red = 40;
        int green = 50;

        g.setColor(Color.GREEN);
        g.fillRect(50, 50, 100, 100);

        while (i >= 0)
        {
            i -= 1;

            g.setColor(Color.RED);
            g.fillRect(red, cons, 100, 100);
            red += 10;

            g.setColor(Color.GREEN);
            g.fillRect(green, cons, 100, 100);
            green += 10;
        }
    }
}
Wojciech Wirzbicki
  • 3,887
  • 6
  • 36
  • 59
AAA
  • 39
  • 4
  • 3
    biggest mistake from code posted without testing, there is no call to `super.paintComponent(g);` which should be 1st call in overridden `paintComponent` method. And dont forget @Override annotation to ensure you are overriding the correct method. Also please post an SSCCE which is runnable/compilable from copy and paste. not many like having to recreate JFrame each time (sometimes a few times a day) – David Kroukamp Dec 17 '12 at 16:35
  • 3
    `"If anyone could take my code and somehow manipulate it to work that would be amazing... I want my code to ..."`: This looks to be more of a code-dump than an actual question. Please don't simply dump your code and ask others to fix it for you, but instead show your attempt at solution and ask questions about this attempt. Voting to close as being too localized. – Hovercraft Full Of Eels Dec 17 '12 at 16:38
  • Also you've been given good advice in your [previous post](http://stackoverflow.com/questions/13864385/javax-swing-timer-with-gui-eclipse). I don't see in the code above where you show the results of your trying to follow this advice. Where's your attempt at coding a Timer? – Hovercraft Full Of Eels Dec 17 '12 at 16:39

1 Answers1

2

Just for your little help to start with, I am posting this code. Though Please do try to learn from it and ask valid questions, that might will arise, to get a taste of the whole thingy. If you had searched it a little bit harder, no doubt, you could have reached this wonderful Doc, that explains exactly your needs in this example.

Code to programatically repaint the component whenever the user clicks or drags the mouse

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MovingSquare
{
    private int x = 0;
    private int y = 100;
    private final int WIDTH = 100;
    private CustomPanel canvas;
    private Timer drawingTimer;
    private ActionListener timerAction = 
        new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent ae)
        {
            if ((x + WIDTH == 500))
            {
                x = 0;
                canvas.setValues(x, y, Color.BLUE);
            }
            else
            {
                x += WIDTH;
                canvas.setValues(x, y, Color.BLUE);
            }
        }
    };

    private void displayGUI()
    {
        JFrame frame = new JFrame("Moving Sqaure");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        canvas = new CustomPanel();
        frame.setContentPane(canvas);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);

        drawingTimer = new Timer(1000, timerAction);
        drawingTimer.start();
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new MovingSquare().displayGUI();
            }
        });
    }
}

class CustomPanel extends JPanel
{
    private final int WIDTH = 500;
    private final int HEIGHT = 500;
    private final int WSQUARE = 100;
    private final int HSQUARE = 50;

    private int x = 0;
    private int y = 100;
    private Color cSquare = Color.BLUE;

    /* 
     * This is where we updating the state
     * of different variables needed, and
     * thus calling repaint.
     */
    public void setValues(int x, int y, Color color)
    {
        cSquare = color;
        repaint(this.x, this.y, WSQUARE, HSQUARE);
        this.x = x;
        this.y = y;
        repaint(x, y, WSQUARE, HSQUARE);
    }

    /*
     * Always make this one customary
     * habbit, to override this method
     * when you extending a JComponent.
     */
    @Override
    public Dimension getPreferredSize()
    {
        return (new Dimension(WIDTH, HEIGHT));
    }

    /* 
     * This is where the actual Painting
     * Portion of the whole thingy will
     * reside. Better is, not to put any
     * calculations in this part, just
     * update the state at some another
     * location and convey it to repaint
     * as needed.
     */
    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.setColor(cSquare);
        g.fillRect(x, y, WSQUARE, HSQUARE);
    }
}

LATEST EDIT :

Please try this modified code, the CustomPanel Class is same as before :

import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;

public class MovingSquare
{
    private int x = 0;
    private int y = 100;
    private final int WIDTH = 100;
    private final int HEIGHT = 100;
    private Random random;
    private CustomPanel canvas;
    private Timer drawingTimer;
    private ActionListener timerAction = 
        new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent ae)
        {
            /*if ((x + WIDTH > 500) && (y + HEIGHT > 500))
            {
                x = random.nextInt(500 - WIDTH);
                canvas.setValues(x, y, Color.BLUE);
            }
            else
            {
                x += WIDTH;
                canvas.setValues(x, y, Color.BLUE);
            }*/
            x = random.nextInt(500 - WIDTH);
            y = random.nextInt(500 - HEIGHT);
            canvas.setValues(x, y, new Color(
                random.nextFloat(), random.nextFloat()
                , random.nextFloat(), random.nextFloat()));
        }
    };

    public MovingSquare()
    {
        random = new Random();
    }

    private void displayGUI()
    {
        JFrame frame = new JFrame("Moving Sqaure");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        canvas = new CustomPanel();
        frame.setContentPane(canvas);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);

        drawingTimer = new Timer(1000, timerAction);
        drawingTimer.start();
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new MovingSquare().displayGUI();
            }
        });
    }
}
nIcE cOw
  • 24,468
  • 7
  • 50
  • 143
  • 1
    Thank you so much... i know i may have seem like a jerk trying to cheat my way threw this code but in all honesty ive been looking around and trying for weeks now... adding to the fact that in my course right now the teacher isnt teaching gui... (my choice to take up GUI) and my biggest problem is that there arent many templates for a lack of words for me to go off.. i will take this code and master it in my own writing ... You are a life saver -Andrew – AAA Dec 18 '12 at 04:31
  • 1
    You're MOST WELCOME and KEEP SMILING :-). Do try to go through these [**trails**](http://docs.oracle.com/javase/tutorial/uiswing/), if you do wanted to learn Swing, and also have a look at [**Java FX 2**](http://docs.oracle.com/javafx/index.html), for Rich Internet Applications, here lies the future for Java Swing IMHO. – nIcE cOw Dec 18 '12 at 04:40
  • I have a question regarding some of the code... when you are calling the Public Static Void main(String.. args) why do you need to add the "..." ? – AAA Dec 18 '12 at 16:07
  • Also at what point during this code does the x component change... like what line of code dictates how far its moves? – AAA Dec 18 '12 at 16:13
  • 1
    Well `String...` is the other way of writing `String[]` or you can also write `String\u005B\u005D`, they all are same thingies, though one difference b/w the two is given on this [thread](http://stackoverflow.com/a/301599/1057230). Regarding your second question, do watch the `actionPerformed()` method of **ActionListener Class** inside the **Moving Square class**, x is changed in that `if-else` **block, saying x += WIDTH or x = 0** :-) – nIcE cOw Dec 18 '12 at 16:24
  • @AAA : Here is one more link from Java Docs relating to [**Pssing Information to methods**](http://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html), which might be able to help you more. – nIcE cOw Dec 18 '12 at 16:55
  • So now i was asked to modify the code so that the square goes from left to right (already done) then from the top to them bottom... – AAA Dec 20 '12 at 16:45
  • i was thinking of just changing some code around and putting in some new excuations – AAA Dec 20 '12 at 16:45
  • i do have a question regarding the animation aspect of the code, When i go to change the y of the code and then run it, it starts and the same y as before and then the next box that is shown moves to a different y..... how would i make the box start at lets say y = 0 from the get go – AAA Dec 21 '12 at 15:47
  • Do have a look at the edit made to the answer, hope that will be able to give you more idea about what is happening. – nIcE cOw Dec 21 '12 at 17:32