Hi, I am trying to create a graphical program that visually stimulates the path of the sun over a city skyline. I've created a Time button but I don't know how to move my sun to the right each time I click on "Time". The program should works like this: When I click on the "Time" button a fifth time, the view returns to the first image. By clicking on the "Time" button repeatedly should step my program through its skyline images in chronological order: 9AM-11AM-1PM-4PM-7PM). Any help will be appreciated. Thank you!

This is my driver:

public class CityTester{

  public static void main(String[] args)
  {
      DisplayWindow display = new DisplayWindow();
      CityPanel p = new CityPanel();
      display.addPanel(p);
      display.showFrame();
    }
  }

This is my code so far:

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

public class CityPanel extends JPanel implements ActionListener{
  
  JButton quit = new JButton("Quit");
  JButton time = new JButton("Time");
  
  public CityPanel(){
    setPreferredSize(new Dimension(800,400));
    setBackground(Color.gray);
    this.add(quit);
    quit.addActionListener(this);
    this.add(time);
    time.addActionListener(this);
  }
  
  public void actionPerformed(ActionEvent e){
    if(e.getSource() == quit)
    System.exit(0);
        else
    if(e.getSource() == time) // this is where i get confuse on. 
  }
  
  public void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawRect(350,300,75,50);
    g.fillRect(260,250,50,100);
    g.drawRect(200,300,60,50);
    g.drawOval(310,300,25,50);
    g.fillOval(20,280,100,30);
    g.drawOval(365,265,50,15);
    g.drawArc(60,330,80,40,360,180);
    g.drawLine(0,350,800,350);
    g.setColor(new Color(255,255,0));
    g.fillOval(40,40,60,60); // this is my sun. 
  }
}

Should I put this

for(int j=0; j<=4; j++)
    g.fillOval(40+80*j,40,60,60)

under the

if(e.getSource() == time)

and call it somehow?

Hey! I think you need some state variables. For example state variables holding the current position of the sun in the coordinate system(int currentX, currentY) and another state variable holding the number of button presses(int buttonPress). And in the actionPerformed method you must change the values of the above mentioned state variables and call repaint() method.(the result is that your sun is redrawn in its new position and buttonPress is incremented by 1). Try to take this advice, if anithing wrong just let me know I think we can figure out smthng.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.