I'm trying to make it so when I press ESC, it RestoreScreen() but it doesn't work. Now I don't know whether it's my method RestoreScreen() or my listeners.
This is my code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class main extends JFrame implements MouseListener,KeyListener{
	
		public void keyPressed(KeyEvent e) {
			int rsKey = e.getKeyCode();
			if(rsKey == KeyEvent.VK_ESCAPE || rsKey == 27){
				s.RestoreScreen();
			}
		}

		
		public void keyReleased(KeyEvent e) {
				
		}

		
		public void keyTyped(KeyEvent e) {
			
		}
	public static void main(String[] args) {
		DisplayMode dm = new DisplayMode(800,600,16,DisplayMode.REFRESH_RATE_UNKNOWN);
		main m = new main();
		m.run(dm);
		
	}
	
	private title s;
	private JTextField command;
	private Image bg;
	private Image ball;
	private static int x = 0;
	private static int y = 0;
	private static boolean right = false;
	private static boolean down = false;
	private boolean loaded = false;
	private boolean dojustonce = false;
	Timer moveball = new Timer(50,new ActionListener(){
		public void actionPerformed(ActionEvent e){
			if(right == false){x-=6;}if(right == true){x+=6;}
			if(down == false){y-=6;}if(down == true){y+=6;}
			if(x <= 0){right = true;}if(x >= 750){right = false;}
			if(y <= 0){down = true;}if(y >= 550){down = false;}
			repaint();
		}
	});
	public void DoJustOnce(){
		repaint();
		dojustonce = true;
	}
	public void paint(Graphics g){
		if(!dojustonce){
			g.clearRect(0,0,getWidth(),getHeight());
		}
		if(g instanceof Graphics2D){
			Graphics2D g2 = (Graphics2D)g;
			g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
			
		}
		if(loaded){
			g.drawImage(bg,0,0,null);
			g.drawImage(ball,x,y,null);
		}
		g.drawString("Click To Start or Press Esc To Exit",180,500);
		
	}
	public void run(DisplayMode dm){
		setBackground(Color.BLACK);
		setForeground(Color.YELLOW);
		setFont(new Font("Comic Sans MS",Font.PLAIN,24));
		loaded = false;
		loadpics();
		command = new JTextField("Enter your command here. Press ESC to exit or press Enter to start.");
		addMouseListener(this);
		addKeyListener(this);
		title s = new title();
		setFocusTraversalKeysEnabled(true);
		moveball.start();
		try{
			s.setFullScreen(dm,this);
		}
		catch(Exception ex){}
	}
	public void loadpics(){
		bg = new ImageIcon("C:\\Documents and Settings\\Lam\\My Documents\\My Pictures\\fun.png").getImage();
		ball = new ImageIcon("C:\\Documents and Settings\\Lam\\My Documents\\My Pictures\\ball_c.png").getImage();
		loaded = true;
		repaint();
	}
	@Override
	public void mouseClicked(MouseEvent arg0) {
		if(arg0.getClickCount() > 1){
			s.RestoreScreen();
		}
	}
	@Override
	public void mouseEntered(MouseEvent arg0) {
		
	}
	@Override
	public void mouseExited(MouseEvent arg0) {
		
	}
	@Override
	public void mousePressed(MouseEvent arg0) {
		
	}
	@Override
	public void mouseReleased(MouseEvent arg0) {
		
	}
	
}

My mouse listener won't work and nor will my KeyListener. Please help.

OR

This could be my RestoreScreen() method which is in my title.java.
Code:

import javax.swing.*;
import java.awt.*;
public class title extends JFrame{
	
		private GraphicsDevice vc;
		
		public title(){
			GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
			vc = env.getDefaultScreenDevice();
			
		}
		
		public void setFullScreen(DisplayMode dm,JFrame window){
			window.setUndecorated(true);
			window.setResizable(false);
			vc.setFullScreenWindow(window);
			
			if(dm != null && vc.isDisplayChangeSupported()){
				try{
					vc.setDisplayMode(dm);
				}catch(Exception ex){}
			}
		}
		
		public Window getFullScreenWindow(){
			return vc.getFullScreenWindow();
		}
		
		public void RestoreScreen(){
			Window w = vc.getFullScreenWindow();
			if(w != null){
				w.dispose();
			}
			vc.setFullScreenWindow(null);
		}
		
}

Dani AI

Generated

Quick summary: the root problem was a local-variable shadowing bug that left the title/manager field uninitialized, so your event handlers were calling a null reference — spotted that and the fix resolved the immediate failure. 's suggestion to add simple debug output (prints or logging) is still excellent for verifying which methods run and whether an exception is being thrown or focus is missing.

A few follow-up points and practical fixes you can apply now:

  • Key events: KeyListener only receives events when its component has keyboard focus. In fullscreen setups focus can be tricky, so prefer Swing Key Bindings on the root pane (they work even if a child has focus). Example:

    getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
        .put(KeyStroke.getKeyStroke("ESCAPE"), "restore");
    getRootPane().getActionMap().put("restore", new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            // call your restore logic (use the initialized manager instance)
        }
    });
  • Painting and structure: do custom drawing inside a JPanel by overriding paintComponent(Graphics) and calling super.paintComponent(g). Add that panel to the frame’s content pane, make it focusable, and call requestFocusInWindow() when it’s shown. Keep animation on a Swing Timer (it runs on the EDT), and avoid drawing directly in the top-level window.

  • Robustness tips: follow Java naming conventions (capitalize class names), avoid swallowing exceptions silently (print stack traces during development), and stop using raw numeric key codes — use KeyEvent.VK_ESCAPE. Create and show your GUI on the Event Dispatch Thread (SwingUtilities.invokeLater). Finally, use the instance field (not a new local variable) for the fullscreen manager so all handlers reference the same object.

These small changes will make the app more reliable and much easier to debug if something else crops up.

Recommended Answers

All 4 Replies

So put some System.out.println statements into the relevant parts of the code to see which code is being executed and whether the variables have the values you expect.
(It's called "debugging").

Hi, mangopearapples. I think you have a mistake on your code.

Here:

private title s;

is still null. And you make a new variable with the same name here:

public void run(DisplayMode dm){
    .
    .
    .
    title s = new title();

    setFocusTraversalKeysEnabled(true);
 
    moveball.start();

You should remove the variable type there, because you make a new local variable with that code instead instantiate the instance variable. So, your code should be like this:

public void run(DisplayMode dm){
    .
    .
    .
    s = new title();
 
    setFocusTraversalKeysEnabled(true);

    moveball.start();

I hope that is helping. Sorry for my bad english. :)

Thank you so much! Everything works now. Your English is fine.
Thanks again!

Nice to help you. :D

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.