Ryel
Ryel

Reputation: 87

Exit program using keylistener without a loop

I am currently studying Java and I'm trying to create a screen saver program. The most important rule is not to use any loops. another key criteria is to use 'x' to exit the program and 'z' to change from fullscreen to halfscreen. My first inclination was to use setDefaultCloseOperation along with a keylistener to exit the program, but I haven't found any way to do that. can anyone please help me understand how to do this without using a loop.

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

public class ScreenSaver1 extends JPanel {
    private JFrame frame = new JFrame("FullSize");
    private Rectangle rectangle;
    boolean full;

    ScreenSaver1() {
        // Remove the title bar, min, max, close stuff
        frame.setUndecorated(true);
        // Add a Key Listener to the frame
        frame.addKeyListener(new KeyHandler());
        // Add this panel object to the frame
        frame.add(this);
        // Get the dimensions of the screen
        rectangle = GraphicsEnvironment.getLocalGraphicsEnvironment()
        .getDefaultScreenDevice().getDefaultConfiguration().getBounds();
        // Set the size of the frame to the size of the screen
        frame.setSize(rectangle.width, rectangle.height);
        frame.setVisible(true);
        // Remember that we are currently at full size
        full = true;
    }
    // This method will run when any key is pressed in the window
class KeyHandler extends KeyAdapter {
    public void keyPressed(KeyEvent e) {
        // Terminate the program.
        System.exit(0);
    }

}

public static void main(String[] args) {
        ScreenSaver1 obj = new ScreenSaver1();
    }
}
  1. You can NOT use loops of any kind in this program.
  2. Your member variables must be private.
  3. Your screen saver class must inherit from the JPanel class and it must have a JFrame member variable.
  4. Your program must keep track of the number of shapes it draws on the screen and after 30 shapes have been drawn, it must clear the screen. This is most easily done by calling the base class (JPanel’s) paintComponent method.
  5. You should use the Timer object to generate ActionEvents to drive your Screen Saver. Set the timer to fire an ActionEvent once every 500 milliseconds. This will cause your actionPerformed method execute, which should simply call the repaint method. Calling the repaint method causes your paintComponent method to execute.
  6. Your paintComponent method will do all the work to select a random color, random shape and random position within the boundaries of your panel, and draw that shape, keeping count of the number of shapes which have been drawn.
  7. Create a private method that returns a random color whenever called that can be any possible random color value. This method will be called from your paintComponent method and from your KeyListener event handler as described below.
  8. Your paintComponent method must use at least four different shapes that you randomly select from… oval, rectangle, filled ovals, filled rectangles, polygons, lines, etc.
  9. The size and position of the shapes that you draw must vary based on the size of the screen. At least part of each shape drawn must be visible on the screen.
  10. Make your screen saver the full size of the screen.
  11. Add a KeyListener to your frame. The KeyListener must handle KeyPressed events.
  12. Your KeyListener must call System.exit when the ‘x’ key is pressed.
  13. When the ‘z’ key is pressed, your KeyListener must change the size of the window from full screen size to half size (half the width and height of the screen), or from half size back to full size. That is, each time the ‘z’ key is pressed the size of the display toggles between full and half size. This requires changing the size of the frame and calling repaint. HINT: Remember, in order to get the background to be redrawn, you will need to set count back to 0.
  14. When the ‘r’ key is pressed, your KeyListener must change the color of the background of the display to a random color. This means it must get a new random color and call the panel’s setBackground with the new random color. It must then call repaint as well. HINT: Remember, in order to get the background to be redrawn, you will need to set count back to 0.

Upvotes: 3

Views: 3360

Answers (2)

Ashwinee K Jha
Ashwinee K Jha

Reputation: 9317

Your key handler should implement keyPressed like this:

            public void keyPressed(KeyEvent e)
            {                
                if (e.getKeyChar() == 'x') {
                    System.out.println("Exiting");
                    System.exit(0);
                }
                else if (e.getKeyChar() == 'z') {
                    System.out.println("Resizing");
                }
            }

Upvotes: 2

Thomas W
Thomas W

Reputation: 14164

I would read the problem/assignment as being to rely on the standard AWT event loop.. and not code any additional loops. So this a matter of events, handlers & re-triggering. (Pseudo-loops -- switch inside recursive fn -- would not play well with the AWT event-dispatch thread, so I think we can rule that approach out).

Here are some possible means:

The 'Timer' approach would enable you to resume execution by scheduling a timer event/ or events, at a later interval.

The 'EventQueue' approach would enable you to post yourself an event, nearly immediately, to resume execution.

Both approaches would avoid needing any explicit loops in your code, instead enabling it to be repeatedly invoked by the existing event-dispatch loop.

Upvotes: 2

Related Questions