Draw shapes with random colors - java

I created a program that draws 4 shapes with MousePressed Listiner. The program should draws shapes with random colors. My program draws shapes correctrly but didn't draw them with random color. Can you give me some idea how to program that.
Thanks
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JToolBar;
import javax.swing.border.EmptyBorder;
public class Pole extends JFrame {
public static int i;
public static void main(String[] args) {
JFrame frame= new JFrame("Shape Stamper!");
JPanel container;
JButton circle = new JButton("Circle");
JButton square = new JButton("Square");
JButton rectangle = new JButton("Rectangle");
JButton oval = new JButton("Oval");
container = new JPanel(new GridLayout(1, 4));
container.add(circle);
container.add(square);
container.add(rectangle);
container.add(oval);
circle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
i = 1;
}
});
square.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
i = 2;
}
});
rectangle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
i = 3;
}
});
oval.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
i = 4;
}
});
MyComponent shape = new MyComponent();
frame.setSize(500, 500);
frame.add(shape, BorderLayout.CENTER);
frame.add(container, BorderLayout.SOUTH);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JComponent;
/**
*
* #author Taras
*/
public class MyComponent extends JComponent {
int i;
Color randColor;
public MyComponent()
{
this.i = i;
addMouseListener(new MouseHandler());
}
private ArrayList<Rectangle2D> arrOfRect=new ArrayList<>();
private ArrayList<Ellipse2D> arrOfEllipse=new ArrayList<>();
// private ArrayList<Color> randColor = new ArrayList<>();
public void paintComponent(Graphics g)
{
Graphics2D g2=(Graphics2D) g;
g.setColor(new Color(randRed(), randGreen(), randBlue()));
for(Rectangle2D r: arrOfRect){
//g2.setColor(Color.GREEN);
g2.draw(r);
}
for(Ellipse2D e: arrOfEllipse){
g2.draw(e);}
repaint();
}
public void add(Point2D p)
{
double x=p.getX();
double y=p.getY();
if (Pole.i == 1){
Ellipse2D ellipse = new Ellipse2D.Double(x, y, 100,100);
//randColor = new Color(randRed(), randGreen(), randBlue());
arrOfEllipse.add(ellipse);
}
if (Pole.i == 2){
Rectangle2D rectangls=new Rectangle2D.Double(x, y, 100, 100);
arrOfRect.add(rectangls);
}
if (Pole.i == 3){
Rectangle2D rectangls=new Rectangle2D.Double(x, y, 150, 100);
arrOfRect.add(rectangls);
}
if (Pole.i == 4){
Ellipse2D ellipse = new Ellipse2D.Double(x, y, 100,50);
arrOfEllipse.add(ellipse);
}
}
private class MouseHandler extends MouseAdapter {
public void mousePressed(MouseEvent event)
{
add(event.getPoint());
//Color rColor = new Color(randRed(), randGreen(), randBlue());
//randColor.add(rColor);
randColor = new Color(randRed(), randGreen(), randBlue());
}
}
private int randRed() {
int red;
Random randomNumber = new Random();
red = randomNumber.nextInt(255);
return red;
}
private int randGreen() {
int green;
Random randomNumber = new Random();
green = randomNumber.nextInt(255);
return green;
}
private int randBlue() {
int blue;
Random randomNumber = new Random();
blue = randomNumber.nextInt(255);
return blue;
}
}

Your problem in next you set Color only once for all components here:
g.setColor(new Color(randRed(), randGreen(), randBlue()));
but if you want to change color for each shape you need to call setColor() each time.
You can use one instance of Random change your paintComponent() method like next and your shapes will have different colors :
Random rand = new Random();
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (Rectangle2D r : arrOfRect) {
g.setColor(new Color(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()));
g2.draw(r);
}
for (Ellipse2D e : arrOfEllipse) {
g.setColor(new Color(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()));
g2.draw(e);
}
}
Also it's wrong to call repaint() inside paintComponent() method, remove that line and repaint your panel after adding new shape, for example:
private class MouseHandler extends MouseAdapter {
public void mousePressed(MouseEvent event) {
add(event.getPoint());
repaint();
}
}

If the objective is to paint every shape with a random color then you'd have to update graphics color for every shape that is drawn. Ie:
for (Rectangle2D r : arrOfRect) {
g.setColor(getRandomColor());
g2.draw(r);
}
There is no need to allocate new Random in every call, you can make it a private member. For example:
private Random randomNumber = new Random();
private Color getRandomColor() {
return new Color(randomNumber.nextFloat(),
randomNumber.nextFloat(), randomNumber.nextFloat());
}
If you want to assign a random color to each shape in add() method and keep it then you'd have to maintain a map of colors, or some other structure that serves the goal.
Other minor but important notes:
Don't forget to call super.paintComponent() inside your implementation of paintComponent.
Do not call repaint() in paintComponent(), as it eventually triggers paintComponent. So you're creating unnecessary repaints.
Do call repaint() inside add() to repaint the component with a newly created shape.
See Performing Custom Painting for more details and examples.

Related

How to make ball drawn with Java bounce off the edges of the panel?

I have java code that draws a red ball inside a class that extends the JPanel class, I have a timer that is enabled by a button that updates the position of the ball with timer ctor variable elapse. I am trying to get the difference of the height of the panel and the YPOSITION where the circle is drawn if its less than 0 the the bounce ball needs to keep moving down else it should move up, my ball hits the wall and keeps hitting it. Help me debug the code that is causing that to happen.
RightPanel class
import javax.swing.*;
import java.awt.*;
public class RightPanel extends JPanel {
//define the position where the circle will be drawn
private int positionX=150;
private int positionY=150;
private int radius=100;//as the shape is a circle
//override the paint method to draw the bounce ball on the second panel
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d= (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.RED);
g2d.fillOval(positionX,positionY,radius,radius);
}
//let's us update the position of the ball from another class
public int getPositionY(){
public void setPositionX(int positionX) {
this.positionX = positionX;
}
public void setPositionY(int positionY){
this.positionY=positionY;
}
public int getPositionX(){
return this.positionX;
}
return this.positionY;
}
}
The logic in the timer class below is the one I need help with
GameInterface class
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class GameInterface extends JFrame {
//declare a Timer object to start the movement
Graphics ctx;
RightPanel rightpanel;
private int height;
//declare a timer to start moving the ball
Timer mytimer= new Timer(50, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
//check this and keep moving the ball down
if(rightpanel.getPositionY()- rightpanel.getHeight()<0){
rightpanel.setPositionY(rightpanel.getPositionY()+5);
rightpanel.paint(rightpanel.getGraphics());
}else{
//move the ball up
rightpanel.setPositionY(rightpanel.getPositionY()-5);
rightpanel.paint(rightpanel.getGraphics());
}
}
});
public GameInterface(){
setSize(new Dimension(800, 600));
height=this.getHeight();
setResizable(false);
setTitle("Bounce Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBackground(Color.black);
//define a new JSplitPane and use it to add two JPanels
JPanel leftpanel= new JPanel();
//add buttons to the left panel programatically
JButton up= new JButton("Move up");
//set the event listeners for the buttons
up.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
//start he timer
mytimer.start();
}
});
JButton down = new JButton("Move down");
down.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
//move my ball down
rightpanel.setPositionX(rightpanel.getPositionX());
rightpanel.setPositionY(rightpanel.getPositionY()+5);
rightpanel.paint(rightpanel.getGraphics());
}
});
leftpanel.add(up);
leftpanel.add(down);
rightpanel= new RightPanel();
JSplitPane splitpane= new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,leftpanel,rightpanel);
this.add(splitpane);
setVisible(true);
ctx=this.getGraphics();
}
}
The basic idea is, when you "drop" the ball, you need to determine the direction of movement that the ball should move in. When the timer ticks, it will apply that direction of movement until it either reaches the bottom, at which time the delta is reversed, or it reaches the top.
The important part here is, all the state the timer needs should be determined before the timer is started and not calculated within the timer itself, as the state it needs is no longer relevant.
For example...
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.GridBagLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Ball ball = new Ball(20);
JFrame frame = new JFrame();
frame.add(new MainPane(ball));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Ball {
private Point location;
private Dimension size;
private Shape shape;
public Ball(int radius) {
location = new Point(0, 0);
size = new Dimension(radius * 2, radius * 2);
shape = new Ellipse2D.Double(0, 0, radius * 2, radius * 2);
}
public Rectangle getBounds() {
return new Rectangle(location, size);
}
public void setLocation(Point p) {
location = new Point(p);
}
public void paint(Graphics2D g2d) {
g2d = (Graphics2D) g2d.create();
g2d.setColor(Color.RED);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.translate(location.x, location.y);
g2d.fill(shape);
g2d.dispose();
}
}
public class SurfacePane extends JPanel {
private Ball ball;
private Timer timer;
private int yDelta;
public SurfacePane(Ball ball) {
this.ball = ball;
this.ball.setLocation(new Point(200 - (ball.getBounds().width / 2), 0));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
ball.paint(g2d);
g2d.dispose();
}
public void moveBallDown() {
Rectangle bounds = ball.getBounds();
Dimension size = ball.size;
Point location = bounds.getLocation();
location.y += size.height;
if (location.y + size.height > getHeight()) {
location.y = getHeight() - size.height;
}
ball.setLocation(location);
repaint();
}
public void dropBall() {
if (timer != null) {
return;
}
Rectangle bounds = ball.getBounds();
Dimension size = ball.size;
Point location = bounds.getLocation();
if (location.y + size.height > getHeight()) {
yDelta = -1;
} else {
yDelta = 1;
}
timer = new Timer(5, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Rectangle bounds = ball.getBounds();
Dimension size = ball.size;
Point location = bounds.getLocation();
location.y += yDelta;
if (location.y < 0) {
location.y = 0;
yDelta = 0;
timer.stop();
timer = null;
} else if (location.y + size.height > getHeight()) {
location.y = getHeight() - size.height;
yDelta *= -1;
}
ball.setLocation(location);
repaint();
}
});
timer.start();
}
}
public class MainPane extends JPanel {
private Ball ball;
private SurfacePane surfacePane;
public MainPane(Ball ball) {
setLayout(new BorderLayout());
this.ball = ball;
surfacePane = new SurfacePane(ball);
add(surfacePane);
JPanel actionPane = new JPanel(new GridBagLayout());
JButton up = new JButton("Up");
JButton down = new JButton("Down");
actionPane.add(up);
actionPane.add(down);
add(actionPane, BorderLayout.SOUTH);
up.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
surfacePane.dropBall();
}
});
down.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
surfacePane.moveBallDown();
}
});
}
}
}

How to achieve non-destructive painting in Java?

I want to plot many sinusoids with different frequencies on a panel, but because painting is destructive, I cannot achieve this. I can only see the last sinusoid plotted.
In the code, the generateSinus() method is called only three times, but it might be called many times and I don't want to call g.fillOval() method for each sinusoid in the paintComponent() method.
Is there a way to achieve non-destructive painting and see all sinusioids with different frequencies?
Please see the code below:
package testdrawsinus;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestDrawSinus extends JPanel
{
private static double[] x;
private static double[] y;
private static boolean buttonClicked = false;
private static JPanel panel = new TestDrawSinus();
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.GREEN);
if (buttonClicked)
{
for (int i=0; i<x.length; i++)
{
g.fillOval((int)x[i] + panel.getWidth()/2, -1*((int)y[i]) + panel.getHeight()/2, 10, 10);
}
buttonClicked = false;
}
}
private static void generateSinus(int freq)
{
x = new double[200];
y = new double[200];
for (int i=0; i<=199; i++)
{
x[i]= (double)i;
y[i] = 100*Math.sin(2*Math.PI*freq*i/200);
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
panel.setLayout(null);
panel.setBounds(20,20, 700,400);
panel.setBackground(Color.BLACK);
frame.add(panel);
JButton button1 = new JButton();
button1.setText("plot");
button1.setBounds(300, 500, 150, 50);
frame.add(button1);
button1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
buttonClicked = true;
generateSinus(1);
panel.repaint();
generateSinus(2);
panel.repaint();
generateSinus(3);
panel.repaint();
}
});
}
}
Thanks for your help.
There are a number of ways you might do this, one way would be to seperate each series into its own model, then have the panel paint each model, for example...
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.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
new Main();
}
private Color[] masterColors = new Color[]{
Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY,
Color.GREEN, Color.MAGENTA, Color.ORANGE, Color.PINK,
Color.RED, Color.WHITE, Color.YELLOW
};
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
TestDrawSinus sinusPane = new TestDrawSinus();
JFrame frame = new JFrame();
frame.add(sinusPane);
JButton button1 = new JButton();
button1.setText("plot");
frame.add(button1, BorderLayout.SOUTH);
button1.addActionListener(new ActionListener() {
private List<Color> colors = new ArrayList<>();
private int freq = 0;
#Override
public void actionPerformed(ActionEvent e) {
sinusPane.addSinusPlot(generateSinus(++freq, nextColor()));
sinusPane.addSinusPlot(generateSinus(++freq, nextColor()));
sinusPane.addSinusPlot(generateSinus(++freq, nextColor()));
}
protected Color nextColor() {
if (colors.isEmpty()) {
colors.addAll(Arrays.asList(masterColors));
Collections.shuffle(colors);
}
return colors.remove(0);
}
});
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private Random rnd = new Random();
private SinusPlot generateSinus(int freq, Color color) {
double[] x = new double[200];
double[] y = new double[200];
for (int i = 0; i < 200; i++) {
x[i] = (double) i;
y[i] = 100 * Math.sin(2d * Math.PI * freq * i / 200d);
}
return new SinusPlot(x, y, color);
}
public class SinusPlot {
private double[] x;
private double[] y;
private Color color;
public SinusPlot(double[] x, double[] y, Color color) {
this.x = x;
this.y = y;
this.color = color;
}
public int getSize() {
return x.length;
}
public double getXAt(int index) {
return x[index];
}
public double getYAt(int index) {
return y[index];
}
public Color getColor() {
return color;
}
}
public class TestDrawSinus extends JPanel {
private List<SinusPlot> plots = new ArrayList<>(8);
public void addSinusPlot(SinusPlot plot) {
plots.add(plot);
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
for (SinusPlot plot : plots) {
System.out.println(plot.getColor());
g2d.setColor(plot.getColor());
for (int i = 0; i < plot.getSize(); i++) {
Ellipse2D dot = new Ellipse2D.Double(((getWidth() - plot.getSize()) / 2) + plot.getXAt(i), plot.getYAt(i) + getHeight() / 2, 10, 10);
g2d.fill(dot);
}
}
g2d.dispose();
}
}
}
null layouts aren't going to help you, take the time to learn understand how the layout management system works, it will save you lot of time and effort. See Laying Out Components Within a Container for more details.
static is not your friend (especially in this context), make the effort to understand how to live without it (and when to use it)

Repaint in Panel method not updated

I am trying to make a program that work like this:
In Window class every time I click on the button, the method panel2 of Panel is called: first it is drawing a first circle, then a second one (after the time defined in the timer). Then, I click again on the button, and it is drawing a fist circle, then a second one then a third one. etc.
The problem is that it when I click to obtain 3 circles appearing one after the other, the two first circles drawn at the previous step (before I pressed a second time the button) stay on the screen and only the third circle is drawn when i press the button (instead of having : first circle drawn, second circle drawn, third circle drawn). I hope I am clear.
Here is a simple code:
Window
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Window extends JFrame implements ActionListener{
int h = 2;
Panel b = new Panel();
JPanel container = new JPanel();
JButton btn = new JButton("Start");
JButton bouton = new JButton();
Panel boutonPane = new Panel();
public Window(){
this.setTitle("Animation");
this.setSize(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
container.setBackground(Color.white);
container.setLayout(new BorderLayout());
JPanel top = new JPanel();
btn.addActionListener(this);
top.add(btn);
container.add(top);
this.setContentPane(container);
this.setVisible(true);
}
public void window2(){
this.setTitle("ADHD");
this.setSize(1000,700);
this.setLocationRelativeTo(null);
if (h < 11){
boutonPane.panel2(h);
bouton.addActionListener(this);
boutonPane.add(bouton);
this.add(boutonPane);
this.setContentPane(boutonPane);
updateWindow2();
}
this.setVisible(true);
}
public void updateWindow2(){
boutonPane.panel2(h);
this.revalidate();
this.repaint();
}
public void actionPerformed(ActionEvent e){
if ((JButton) e.getSource() == btn){
System.out.println("pressed0");
window2();
}
if ((JButton) e.getSource() == bouton){
h++;
System.out.println("pressed" + h);
updateWindow2();
}
}
public static void main(String[] args){
Window w = new Window();
}
}
Panel
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Panel extends JPanel implements ActionListener{
int m;
int u=0;
int lgi, lrgi;
int [] ta;
Timer timer1 = new Timer(300, this);
Panel(){
}
public void panel2(int n){
m=n;
ta = new int [n];
for(int it=0; it<m;it++){
ta[it]=100*it;
}
timer1.start();
}
public void paintComponent(Graphics gr){
super.paintComponent(gr);
gr.setColor(Color.red);
for(int i=0;i<m;i++){
gr.fillOval(ta[i],ta[i], 150, 150);
}
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(u<m){
u++;
revalidate();
repaint();
}
}
}
Your code needs use two int values to decide how many circles to draw and when:
The first int should be the count of current circles to draw, say called, currentCirclesToDraw.
The second int will be the number of circles to draw total.
If you use a List<Ellipse2D> like I suggest, then this number will be the size of the list. So if the List is called ellipseList, then the 2nd number will be ellipseList.size().
The first variable will be incremented in the timer up to the size of the list, but no larger, and will be used by paintComponent method to decide how many circles to draw.
Key point here: the first number, the currentCirclesToDraw, must be re-set to 0 when the button is pressed. This way your paintComponent method will start out drawing 0 circles, then 1, then 2, ...
For example, the paintComponent method could look like so:
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(CIRCLE_COLOR);
for (int i = 0; i < currentCirclesToDraw && i < ellipseList.size(); i++) {
g2.fill(ellipseList.get(i));
}
}
I use the second term in the for loop conditional statement, i < currentCirclesToDraw && i < ellipseList.size() as an additional fail-safe to be sure that we don't try to draw more circles then we have in our list.
My Timer's ActionListener would increment the currentCirclesToDraw variable and call repaint. It would stop the Timer once currentCirclesToDraw reaches the size of the ellipseList:
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (currentCirclesToDraw < ellipseList.size()) {
currentCirclesToDraw++;
repaint();
} else {
// stop the Timer
((Timer)e.getSource()).stop();
}
}
}
And my button's actionPerformed method would reset currentCirclesToDraw to 0, would add a new Ellipse2D to my ellipseList (if we've not yet reached the MAX_CIRCLE_INDEX), would call repaint() to clear the JPanel, and would construct and start the Timer:
public void actionPerformed(java.awt.event.ActionEvent arg0) {
currentCirclesToDraw = 0; // this is key -- reset the index used to control how many circles to draw
if (ellipseList.size() < MAX_CIRCLE_INDEX) {
double x = (ellipseList.size()) * CIRCLE_WIDTH / Math.pow(2, 0.5);
double y = x;
double w = CIRCLE_WIDTH;
double h = CIRCLE_WIDTH;
ellipseList.add(new Ellipse2D.Double(x, y, w, h));
}
repaint(); // clear image
new Timer(TIMER_DELAY, new TimerListener()).start();
};
Edit 3/30/14
Note it all can be put together like this:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
/**
* http://stackoverflow.com/a/22714405/522444
* http://stackoverflow.com/questions/22712655/repaint-in-panel-method-not-updated
* #author Pete
*
*/
#SuppressWarnings("serial")
public class TimerCircles extends JPanel {
private static final int PREF_W = 1000;
private static final int PREF_H = 700;
private static final Color CIRCLE_COLOR = Color.RED;
public static final int MAX_CIRCLE_INDEX = 11;
public static final int TIMER_DELAY = 300;
public static final int CIRCLE_WIDTH = 100;
private final List<Ellipse2D> ellipseList = new ArrayList<>();
private int currentCirclesToDraw = 0;
public TimerCircles() {
add(new JButton(new ButtonAction("New Circle", KeyEvent.VK_C)));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(CIRCLE_COLOR);
for (int i = 0; i < currentCirclesToDraw && i < ellipseList.size(); i++) {
g2.fill(ellipseList.get(i));
}
}
private class ButtonAction extends AbstractAction {
public ButtonAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
public void actionPerformed(java.awt.event.ActionEvent arg0) {
currentCirclesToDraw = 0; // this is key -- reset the index used to control how many circles to draw
if (ellipseList.size() < MAX_CIRCLE_INDEX) {
double x = (ellipseList.size()) * CIRCLE_WIDTH / Math.pow(2, 0.5);
double y = x;
double w = CIRCLE_WIDTH;
double h = CIRCLE_WIDTH;
ellipseList.add(new Ellipse2D.Double(x, y, w, h));
}
repaint(); // clear image
new Timer(TIMER_DELAY, new TimerListener()).start();
};
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (currentCirclesToDraw < ellipseList.size()) {
currentCirclesToDraw++;
repaint();
} else {
// stop the Timer
((Timer)e.getSource()).stop();
}
}
}
private static void createAndShowGui() {
TimerCircles mainPanel = new TimerCircles();
JFrame frame = new JFrame("TimerCircles");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Moving objects and timers

I have a screen with say 500 width and 400 height, and I have a vector with a bunch of shapes. let say the vector has 2 different shapes for example. I want the object to randomly pop up from the bottom of the screen reach a certain ascent and then fall back down (similar to game fruit ninja, where the fruits are my shapes).
In my main (view) I have a vector of shapes of which i instantiate the timers, add to array and place them in the buttom of the screen using the translate function. My timer takes in an action listener which basically changes the translate of the shape to move up till ascent and then down, but my problem is that all the shapes start at the same time regardless.
Something like this:
Shape f = new Shape(new Area(new Ellipse2D.Double(0, 50, 50, 50)));
f.translate(0, 400);
f.timer = new Timer( 10 , taskPerformer);
f.timer.start();
vector.add(f);
Shape f2 = new Shape(new Area(new Rectangle2D.Double(0, 50, 50, 50)));
f2.translate(200, 400);
f2.timer = new Timer( 10 , taskPerformer);
f2.timer.setInitialDelay(5000);
f2.timer.start();
vector.add(f2);
and my action listener:
Random generator = new Random();
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
for (Shape s : model.getShapes()) {
// Scale object using translate
// once reached ascent drop down
// translate to diffrenet part of the bottom of the screen
// delay its timer
}
update();
//basically repaints
}
};
I'm running into problems that all shapes follow the same timer, and begin to pop up at the same time (no delay) ...
Any suggestions on how to avoid this or if there is a different approach i should try
"I want the object to randomly pop up from the bottom of the screen reach a certain ascent and then fall back down"
See the runnable example below. What I do is pass a radomDelayedStart to the Shape. Every tick of the timer, the randomDelayedStart decreases til it reaches 0, that's when the flag to be drawn in raised. Most of the logic is in the Shape class methods, which are called in the Timers Actionlistener. Everything is done in one Timer. For the ascent, I just used a hard coded 50, but you can also pass a random ascent to the Shape. Let me know if you have any questions. I tried to made the code as clear as possible.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class RandomShape extends JPanel {
private static final int D_HEIGHT = 500;
private static final int D_WIDTH = 400;
private static final int INCREMENT = 8;
private List<Shape> shapes;
private List<Color> colors;
private Timer timer = null;
public RandomShape() {
colors = createColorList();
shapes = createShapeList();
timer = new Timer(30, new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (Shape shape : shapes) {
shape.move();
shape.decreaseDelay();
repaint();
}
}
});
JButton start = new JButton("Start");
start.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
timer.start();
}
});
JButton reset = new JButton("Reset");
reset.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
shapes = createShapeList();
timer.restart();
}
});
JPanel panel = new JPanel();
panel.add(start);
panel.add(reset);
setLayout(new BorderLayout());
add(panel, BorderLayout.PAGE_START);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Shape shape : shapes) {
shape.drawShape(g);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(D_WIDTH, D_HEIGHT);
}
private List<Color> createColorList() {
List<Color> list = new ArrayList<>();
list.add(Color.BLUE);
list.add(Color.GREEN);
list.add(Color.ORANGE);
list.add(Color.MAGENTA);
list.add(Color.CYAN);
list.add(Color.PINK);
return list;
}
private List<Shape> createShapeList() {
List<Shape> list = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < 20; i++) {
int randXLoc = random.nextInt(D_WIDTH);
int randomDelayedStart = random.nextInt(100);
int colorIndex = random.nextInt(colors.size());
Color color = colors.get(colorIndex);
list.add(new Shape(randXLoc, randomDelayedStart, color));
}
return list;
}
class Shape {
int randXLoc;
int y = D_HEIGHT;
int randomDelayedStart;
boolean draw = false;
boolean down = false;
Color color;
public Shape(int randXLoc, int randomDelayedStart, Color color) {
this.randXLoc = randXLoc;
this.randomDelayedStart = randomDelayedStart;
this.color = color;
}
public void drawShape(Graphics g) {
if (draw) {
g.setColor(color);
g.fillOval(randXLoc, y, 30, 30);
}
}
public void move() {
if (draw) {
if (y <= 50) {
down = true;
}
if (down) {
y += INCREMENT;
} else {
y -= INCREMENT;
}
}
}
public void decreaseDelay() {
if (randomDelayedStart <= 0) {
draw = true;
} else {
randomDelayedStart -= 1;
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.add(new RandomShape());
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

MousePressed not working

I've been trying to do this assignment and for it to work I need the event mousePressed to work but for some reason it's not responding to the mouse. Its purpose is to paint another yellow circle when the mouse is pressed.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class CatchMonster extends JPanel
{
private int height = 300;
private int width = 600;
private final int delay = 4001;
private ImageIcon image;
private Timer timer;
private int x, y, moveX, moveY, xPoint, yPoint;
public CatchMonster() {
DotListener dot = new DotListener();
addMouseListener(dot);
timer = new Timer(delay, new timerListener());
x = 40;
y = 40;
moveX = moveY = 3;
setPreferredSize(new Dimension(width, height));
setBackground(Color.black);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponents(g);
g.setColor(Color.yellow);
g.fillOval(x, y, 60, 60);
}
private class timerListener implements ActionListener
{
public void actionPerformed(ActionEvent e) {
Random gn = new Random();
x = gn.nextInt(width);
y = gn.nextInt(height);
repaint();
}
}
private class DotListener implements MouseListener
{
public void mousePressed(MouseEvent event)
{
repaint();
}
#Override
public void mouseClicked(MouseEvent event) {
}
#Override
public void mouseEntered(MouseEvent event) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent event) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent event) {
// TODO Auto-generated method stub
}
}
}
I need the event mousePressed to work but for some reason it's not responding to the mouse. Its purpose is to paint another yellow circle when the mouse is pressed.
But it won't paint another circle as all it does is call repaint(), and how is that going to paint anything new? If you want it to create another circle, you'll have to give it logic to do so. For instance, if you want to paint more than one yellow oval, you'll want to create an ArrayList of Point objects and add a Point into that array list in the mousePressed method. Then in the paintComponent method, you can iterate through the array list, painting ovals for each Point it contains.
In addition, you want to change this:
public void paintComponent(Graphics g) {
super.paintComponents(g); // this is not the "super" method of paintComponent
g.setColor(Color.yellow);
g.fillOval(x, y, 60, 60);
}
to this:
public void paintComponent(Graphics g) {
super.paintComponent(g); // See the difference?
g.setColor(Color.yellow);
g.fillOval(x, y, 60, 60);
}
For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class CatchMonster extends JPanel {
private int height = 300;
private int width = 600;
private final int delay = 4001;
private ImageIcon image;
private Timer timer;
private int x, y, moveX, moveY, xPoint, yPoint;
private List<Point> points = new ArrayList<Point>();
public CatchMonster() {
DotListener dot = new DotListener();
addMouseListener(dot);
timer = new Timer(delay, new timerListener());
x = 40;
y = 40;
moveX = moveY = 3;
setPreferredSize(new Dimension(width, height));
setBackground(Color.black);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.yellow);
g.fillOval(x, y, 60, 60);
int radius = 30;
g.setColor(Color.green);
for (Point p : points) {
int x = p.x - radius;
int y = p.y - radius;
g.fillOval(x, y, 2 * radius, 2 * radius);
}
}
private class timerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Random gn = new Random();
x = gn.nextInt(width);
y = gn.nextInt(height);
repaint();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new CatchMonster());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private class DotListener extends MouseAdapter {
public void mousePressed(MouseEvent event) {
points.add(event.getPoint());
repaint();
}
}
}

Categories

Resources