Hello. I'm quite new to Java, but I've worked on Graphics before.

I have a couple of questions which are:

I want to make a night sky in Java with stars which randomly switch to big stars from small and back, repeating for a set time. I also want the changes of the star size to occur with opacity, so that they appeared to glisten.

Another thing I want to consider is I want to create a crescent moon, which will get off of the screen in a smooth movement across the screen, replaced with a smooth movement of sun with the background color to change in order to imitate the sky during the morning’s sunrise, and stars disappear as the sun gets to the center of the screen.

This is what I have so far, didn’t want to make any mistakes in the beginning in order to make the path easier to go.

import java.awt.*;
import java.applet.*;


public class NightSky extends Applet
{

    public void paint(Graphics g)
    {

    }
}

Recommended Answers

All 13 Replies

  1. use JApplet not Applet (I'd suggest to use JFrame instead)

  2. put there JPanel ant to override paintComponent instad of paint()

  3. 1st. code line should be super.paintComponent(), otherwise all painting will be cumulating

  4. rest is described in Oracle tutorial Performing Custom Painting

You probably also want to use a timer or a thread for the animation

Here's a minimal runnable exmple that illustrates the key things you need to do - in particular a "model" that has the current values for whatever changes overe time (pahse/position of moon, brightness of sky etc), a timer-based method that updates those variables in a predictable steady way, and a paintComponent that updates the display using the latest values.

import java.awt.*;
import java.util.TimerTask;
import javax.swing.*;

public class Animation0 extends JPanel {
   // absolutely minimal example of how to structure animation in Swing.
   // One method that steps the simulation model through time
   // One method that updates the screen with the latest data

   public static void main(String[] args) {
      // create and display the animation in a JFrame
      final JFrame frame = new JFrame("Animation 0 (close window to exit)");
      Animation0 animationPanel = new Animation0();
      animationPanel.setPreferredSize(new Dimension(400, 150));
      frame.add(animationPanel);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }

   // this is the "model" - just a single object moving L-R at constant speed
   private int xPos = 0; // current position of animated object

   Animation0() {
      // start Timer to update the model every 30 milliseconds...
      // uses a java.util Timer rather than javax.swing Timer
      // to avoid running intensive simulation code on the swing thread
      java.util.Timer timer = new java.util.Timer();
      TimerTask timerTask = new TimerTask() {
         @Override
         public void run() {
            updateSimulation();
         }
      };
      timer.scheduleAtFixedRate(timerTask, 0, 30);
   }

   public void updateSimulation() {
      // reliably called by Timer every 30 milliseconds
      xPos += 1; // update position of object
      repaint(); // notify that screen refresh is now needed
   }

   // this is the GUI - draws the model on the screen
   @Override
   public void paintComponent(Graphics g) {
      // screen refresh - called by Swing as needed
      // Never update positions etc here because there are no
      // guarantees about when or how many times this will be called.
      super.paintComponent(g); // ensure background etc is painted
      g.fillOval(xPos, 35, 100, 100); // draw object at current position
   }

}

So, how could I make the screen be full screen upon rununig the program, and also how would I make the stars to change size and glinter at the same time with opacity. Thanks for the code example to get me started.

Maximizing depends on which Java class you are using for your window. Assuming JFrame you can use its setExtendedState method.
Making the stars sparkle depeneds on exactly how you are going to draw them. Maybe you are taking too many steps in one go? It would be a good idea to just draw the stars as 1 or 2 pixels of white until the whole thing is working, then go back and upgrade the star paint code.

It would be nice to have an example of code please.

You have an example to start with, so maybe you would like to update us with what you have done so far... you'll find on DaniWeb the help you get is porportional to the effort you seem to be making...

It's little hard to code anything since I'm just beginning to code in java.
I've tried to find how to make the program run full screen upon runing it, but had no success at all, just more confused.

I also noticed that the object moves from left to right in a straight line, is it possible in any way to make it move in a curve, like going from left side of the screen, to the top of the center of the screen, and to the same position as it started from only on the right side?

Well, yes, nobody said it's easy. There's only one way to develop that skill.
Why not start with the code I posted. Get that running on your computer. Change it to be a bit more like what you want. You'll be learning every step of the way. I'll check this thread again tomorrow.
J

I've searched for the code to make the program run in maximized screen, but when I've ran the code, there were errors. Don't know why it doesn't work, but here is the code:

public final class FullscreenSample {

    public static final void main(final String[] args) throws Exception {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

        final JFrame fullscreenFrame = new JFrame();
        fullscreenFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        fullscreenFrame.setUndecorated(true);
        fullscreenFrame.setResizable(false);
        fullscreenFrame.add(new JLabel("Press ALT+F4 to exit fullscreen.", SwingConstants.CENTER), BorderLayout.CENTER);
        fullscreenFrame.validate();

        GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(fullscreenFrame);
    }

 }

I've also found this code but I don't know where to plug it in to make it work:

public void run() {
    MyFrame myFrame = new MyFrame();
    myFrame.setVisible(true);
    myFrame.setExtendedState(myFrame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
}

Try it understand the concepts behind rather than try putting code snippets together.

Use JFrame#setUndecorated(true); to remove the title bar of the JFrame,JFrame#setResiable(false); to make the window static( unresizable) and make the window size full. This combination makes the window fullscreen).

See the edited code of JamesCherill below:

import java.awt.*;
import java.util.TimerTask;
import javax.swing.*;

public class Animation0 extends JPanel {
   // absolutely minimal example of how to structure animation in Swing.
   // One method that steps the simulation model through time
   // One method that updates the screen with the latest data

   public static void main(String[] args) {
      // create and display the animation in a JFrame
      final JFrame frame = new JFrame("Animation 0 (close window to exit)");
      Animation0 animationPanel = new Animation0();
      frame.add(animationPanel);
      frame.setLocationRelativeTo(null);
      frame.setUndecorated(true);
      frame.setResizable(false);
      GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(frame);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }

   // this is the "model" - just a single object moving L-R at constant speed
   private int xPos = 0; // current position of animated object

   Animation0() {
      // start Timer to update the model every 30 milliseconds...
      // uses a java.util Timer rather than javax.swing Timer
      // to avoid running intensive simulation code on the swing thread
      java.util.Timer timer = new java.util.Timer();
      TimerTask timerTask = new TimerTask() {
         @Override
         public void run() {
            updateSimulation();
         }
      };
      timer.scheduleAtFixedRate(timerTask, 0, 30);
   }

   public void updateSimulation() {
      // reliably called by Timer every 30 milliseconds
      xPos += 1; // update position of object
      repaint(); // notify that screen refresh is now needed
   }

   // this is the GUI - draws the model on the screen
   @Override
   public void paintComponent(Graphics g) {
      // screen refresh - called by Swing as needed
      // Never update positions etc here because there are no
      // guarantees about when or how many times this will be called.
      super.paintComponent(g); // ensure background etc is painted
      g.fillOval(xPos, 35, 100, 100); // draw object at current position
   }

}

All the best! Happy learning!

Thanks for your reply challarao, however my goal is to make the program not to be in full screen (as you provided above, thanks) but to make the program after compiling run in Maximized size. There is a difference beteween a full screen and a maximized screen. I want the maximized screen, instead of the user clicking on the maximize button in the upper right corner every time s/he runs the program.

It's handled through the "extendedState" attributes for your window - they are a set of multiple selection options that you can OR together. The following takes all the existing exetnded states and adds the values for maximised in both h and v directions...
frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH);

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.