0

Sorry I am a newbie. In this situation my if statement does not work.

import java.awt.Color;    
import javax.swing.JFrame;    

public class Map implements Runnable{

    JFrame map = new JFrame("Hunter Prey Game");
    Map(){          
        map.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        map.setSize(400,400);
        map.setResizable(false);
        map.setBackground(Color.BLACK);
        map.setVisible(true);
    }

    public void run() {
        for(int i = 0 ; i < 20 ; i++){
            System.out.println("hello"+i);
            if(i == 1)
                map.setBackground(Color.BLACK);
            else
                map.setBackground(Color.BLUE);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // choose to ignore this exception
            }
        }
    }
    public static void main(String[] args){
        Thread t = new Thread(new Map());
        t.start();
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
mertk
  • 19
  • 1
  • 10
  • Use the right tool for the job: a [Swing Timer](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html). Why? The timer can replace your for loop, is easy to implement, and most importantly is Swing-thread-safe. – Hovercraft Full Of Eels Jul 23 '17 at 16:40
  • Actually I was trying to practice threads and gui for my school project. Still thanks for the help sir. – mertk Jul 23 '17 at 16:42
  • Your if blocks are working fine (test them with a debugger), but you shouldn't set a JFrame's background, but rather should set the background of its contentPane: `map.getContentPane().setBackground(Color.BLACK);`. Also all blocks should be surrounded by curly braces. – Hovercraft Full Of Eels Jul 23 '17 at 16:46
  • But having said that, your code is not thread safe as you're making state changes to a Swing GUI off of its event thread. This can lead to intermittent hard to debug exceptions. – Hovercraft Full Of Eels Jul 23 '17 at 16:47
  • Thanks a lot sir. – mertk Jul 23 '17 at 16:49
  • What is your suggestion for making it thread safe. – mertk Jul 23 '17 at 16:50
  • Easiest: use a [Swing Timer](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html). Else you would have to wrap each call to `setBacktround` within a Runnable and then queue that Runnable onto the event thread using `SwingUtilities.invokeLater(...)`, which is a whole lot of mess for little benefit. – Hovercraft Full Of Eels Jul 23 '17 at 16:52

0 Answers0