0

Hey Guys need your help with this java problem that has developed in my code, I have Created a GUI which is essentially being used as a Car Race Simulator, My Events work for my GUI apart for my startrace event which is a button to start the race , iv only done the first part of the race but it didnt work so i would like to fix the problem before i move on. its difficult to explain it would be easier for me to show the code(Which is below), i am not trying to be spoon fed so please dont start giving me bad votes and saying i am not giving enough detail as i dont really know what more i can say that what i am about to write. i have no inclination as to what the problem is. when i debug it(as im using Eclipse IDE) the part that doesnt work simply makes the The whole window go black and nothing shows up for about a minute and then it skips most of the code and doesnt even do the rest. if you need any more information please ask me and i will tell you im only human and dont know every detail you want me to put off head. I have many classes but they will probably make it more confusing to you guys so il only paste the class in which i have the problem in.

(note: SportCar- is a super class with 5 subclasses (Astonmatin,Audi,Ferrari,Porsche,Lamborghini))

(note: Track is a Class on its own with the GUI interface it is a large class and uses Variable and Methods from the SportsCar and its subclass all there methods and variable work they are not the problem)

(note: The problem lies within the actionPerformed(ActionEvent startrace)) I Hope ive given enough detail and any help is welcome. Thanking you in advance.

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




public class Track extends JFrame {

    private JComboBox ChooseYourCar;
    private JComboBox ChooseOppsCar; 
    private JButton StartRace;
    private JTextArea CheckYourCarAtts;
    private JTextArea CheckOppsCarAtts;
    private JTextArea Commentry; 
    private String temp;
    private String temp1;
    private String[] Cars = {"Choose Car Please ","Aston martin","Audi","Ferrari","Porsche","Lamborghini"};
    private int counter=0;
    private JTextField[] Green= new JTextField[11];
    private JTextField[] Green1= new JTextField[11];
    private JPanel Track = new JPanel();
    private SportCar first;
    private SportCar Second;

    public Track(){
        JPanel Center = new JPanel();
        JPanel West = new JPanel();
        JPanel East= new JPanel();
        JPanel North = new JPanel();
        Track.setLayout(new GridLayout(2,11,0,3));


        while (counter!=11)
        {

            Green[counter]= new JTextField("");
            Green[counter].setBackground(Color.GREEN);
            Green1[counter]= new JTextField("");
            Green1[counter].setBackground(Color.GREEN);
            counter++;  
             }


        counter= 0;
        while (counter!=11){
        Track.add(Green[counter]);
        counter++;

        }

        counter= 0;
        while (counter!=11){
            Track.add(Green1[counter]);
            counter++;

        }



        add(West, BorderLayout.WEST);
        add(Center, BorderLayout.CENTER);
        add(East, BorderLayout.EAST);
        add(North,BorderLayout.NORTH);
        add(Track,BorderLayout.SOUTH);



        ChooseYourCar = new JComboBox(Cars);
        West.add(ChooseYourCar);
        ChooseOppsCar = new JComboBox(Cars);
        West.add(ChooseOppsCar);
        StartRace = new JButton("Start Race");
        East.add(StartRace);
        CheckYourCarAtts = new JTextArea(12,30);
        CheckYourCarAtts.setBackground(Color.RED);
        Center.add(CheckYourCarAtts);
        CheckOppsCarAtts = new JTextArea(12,30);
        CheckOppsCarAtts.setBackground(Color.RED);
        Center.add(CheckOppsCarAtts);
        Commentry = new JTextArea(2,50);
        North.add(Commentry);



        event chooseyourcar = new event();
        ChooseYourCar.addActionListener(chooseyourcar);
        event1 Chooseoppscar = new event1();
        ChooseOppsCar.addActionListener(Chooseoppscar);
        event2 startrace = new event2();
        StartRace.addActionListener(startrace);



    }
    public class event implements ActionListener{
        public void actionPerformed(ActionEvent chooseyourcar){
            if(ChooseYourCar.getSelectedItem()=="Aston martin")
            {
                SportCar AstonMartin = new Astonmartin(400,1.0,1200,220);
                String str=("ASTON MARTIN\n"+"This is the Car You have currently Selected \n" +"Horsepower: " +AstonMartin.getHorsepower()+"\n"+ "Weight: "+ AstonMartin.getWeight()+ "\n"+ "Topspeed: "+ AstonMartin.getTopspeed()+ "\n"+ "The car goes from 0-60Mph(secs) in: "+ AstonMartin.acceleration()+ "\n"+ "The Fuel Consumption is: "+ AstonMartin.GetFuelConsumption());
                CheckYourCarAtts.setText(str);
            }
            if(ChooseYourCar.getSelectedItem()=="Audi")
            {
                SportCar Audi = new Audi(300,1.2,1200,200);
                String str=("AUDI\n"+"This is the Car You have currently Selected\n" +"Horsepower: " +Audi.getHorsepower()+"\n"+ "Weight: "+ Audi.getWeight()+ "\n"+ "Topspeed: "+ Audi.getTopspeed()+ "\n"+ "The car goes from 0-60Mph(secs) in: "+ Audi.acceleration()+ "\n"+ "The Fuel Consumption is: "+ Audi.GetFuelConsumption());
                CheckYourCarAtts.setText(str);
            }
            if(ChooseYourCar.getSelectedItem()=="Ferrari")
            {
                SportCar Ferrari = new Ferrari(440,0.8,900,260);
                String str=("FERRARI\n"+"This is the Car You have currently Selected\n" +"Horsepower: " +Ferrari.getHorsepower()+"\n"+ "Weight: "+ Ferrari.getWeight()+ "\n"+ "Topspeed: "+ Ferrari.getTopspeed()+ "\n"+ "The car goes from 0-60Mph(secs) in: "+ Ferrari.acceleration()+ "\n"+ "The Fuel Consumption is: "+ Ferrari.GetFuelConsumption());
                CheckYourCarAtts.setText(str);
            }
            if(ChooseYourCar.getSelectedItem()=="Porsche")
            {
                SportCar Porsche = new Porsche(380,0.9,1000,220);
                String str=("PORSCHE\n"+"This is the Car You have currently Selected\n" +"Horsepower: " +Porsche.getHorsepower()+"\n"+ "Weight: "+ Porsche.getWeight()+ "\n"+ "Topspeed: "+ Porsche.getTopspeed()+ "\n"+ "The car goes from 0-60Mph(secs) in: "+ Porsche.acceleration()+ "\n"+ "The Fuel Consumption is: "+ Porsche.GetFuelConsumption());
                CheckYourCarAtts.setText(str);
            }
            if(ChooseYourCar.getSelectedItem()=="Lamborghini")
            {
                SportCar Lamborghini = new Lamborghini(440,0.7,900,250);
                String str=("LAMBORGHINI\n"+"This is the Car You have currently Selected\n" +"Horsepower: " +Lamborghini.getHorsepower()+"\n"+ "Weight: "+ Lamborghini.getWeight()+ "\n"+ "Topspeed: "+ Lamborghini.getTopspeed()+ "\n"+ "The car goes from 0-60Mph(secs) in: "+ Lamborghini.acceleration()+ "\n"+ "The Fuel Consumption is: "+ Lamborghini.GetFuelConsumption());
                CheckYourCarAtts.setText(str);
            }


}

}

        public class event1 implements ActionListener{
            public void actionPerformed(ActionEvent chooseoppscar){
                if(ChooseOppsCar.getSelectedItem()=="Aston martin")
                {
                    SportCar AstonMartin = new Astonmartin(400,1.0,1200,220);
                    String str=("ASTON MARTIN\n"+"This is the Car You have currently Selected\n" +"Horsepower: " +AstonMartin.getHorsepower()+"\n"+ "Weight: "+ AstonMartin.getWeight()+ "\n"+ "Topspeed: "+ AstonMartin.getTopspeed()+ "\n"+ "The car goes from 0-60Mph(secs) in: "+ AstonMartin.acceleration()+ "\n"+ "The Fuel Consumption is: "+ AstonMartin.GetFuelConsumption());
                    CheckOppsCarAtts.setText(str);
                }
                if(ChooseOppsCar.getSelectedItem()=="Audi")
                {
                    SportCar Audi = new Audi(300,1.2,1200,200);
                    String str=("AUDI\n"+"This is the Car You have currently Selected\n" +"Horsepower: " +Audi.getHorsepower()+"\n"+ "Weight: "+ Audi.getWeight()+ "\n"+ "Topspeed: "+ Audi.getTopspeed()+ "\n"+ "The car goes from 0-60Mph(secs) in: "+ Audi.acceleration()+ "\n"+ "The Fuel Consumption is: "+ Audi.GetFuelConsumption());
                    CheckOppsCarAtts.setText(str);
                }
                if(ChooseOppsCar.getSelectedItem()=="Ferrari")
                {
                    SportCar Ferrari = new Ferrari(440,0.8,900,260);
                    String str=("FERRARI\n"+"This is the Car You have currently Selected\n" +"Horsepower: " +Ferrari.getHorsepower()+"\n"+ "Weight: "+ Ferrari.getWeight()+ "\n"+ "Topspeed: "+ Ferrari.getTopspeed()+ "\n"+ "The car goes from 0-60Mph(secs) in: "+ Ferrari.acceleration()+ "\n"+ "The Fuel Consumption is: "+ Ferrari.GetFuelConsumption());
                    CheckOppsCarAtts.setText(str);
                }
                if(ChooseOppsCar.getSelectedItem()=="Porsche")
                {
                    SportCar Porsche = new Porsche(380,0.9,1000,220);
                    String str=("PORSCHE\n"+"This is the Car You have currently Selected\n" +"Horsepower: " +Porsche.getHorsepower()+"\n"+ "Weight: "+ Porsche.getWeight()+ "\n"+ "Topspeed: "+ Porsche.getTopspeed()+ "\n"+ "The car goes from 0-60Mph(secs) in: "+ Porsche.acceleration()+ "\n"+ "The Fuel Consumption is: "+ Porsche.GetFuelConsumption());
                    CheckOppsCarAtts.setText(str);
                }
                if(ChooseOppsCar.getSelectedItem()=="Lamborghini")
                {
                    SportCar Lamborghini = new Lamborghini(440,0.7,900,250);
                    String str=("LAMBORGHINI\n"+"This is the Car You have currently Selected\n" +"Horsepower: " +Lamborghini.getHorsepower()+"\n"+ "Weight: "+ Lamborghini.getWeight()+ "\n"+ "Topspeed: "+ Lamborghini.getTopspeed()+ "\n"+ "The car goes from 0-60Mph(secs) in: "+ Lamborghini.acceleration()+ "\n"+ "The Fuel Consumption is: "+ Lamborghini.GetFuelConsumption());
                    CheckOppsCarAtts.setText(str);
                }
    }
}   

        public class event2 implements ActionListener{
            public void actionPerformed(ActionEvent startrace){ 
                if(ChooseYourCar.getSelectedItem()=="Aston martin")
                {
                    SportCar AstonMartin = new Astonmartin(400,1.0,1200,220);
                    first= AstonMartin;
                }
                if(ChooseYourCar.getSelectedItem()=="Audi")
                {
                    SportCar Audi = new Audi(300,1.2,1200,200);
                     first= Audi;
                }
                if(ChooseYourCar.getSelectedItem()=="Ferrari")
                {
                    SportCar Ferrari = new Ferrari(440,0.8,900,260);
                      first= Ferrari;
                }
                if(ChooseYourCar.getSelectedItem()=="Porsche")
                {
                    SportCar Porsche = new Porsche(380,0.9,1000,220);
                     first= Porsche;
                }
                if(ChooseYourCar.getSelectedItem()=="Lamborghini")
                {
                    SportCar Lamborghini = new Lamborghini(440,0.7,900,250);
                    first= Lamborghini;
                }


                if(ChooseOppsCar.getSelectedItem()=="Aston martin")
                {
                    SportCar AstonMartin = new Astonmartin(400,1.0,1200,220);
                    Second= AstonMartin;
                }
                if(ChooseOppsCar.getSelectedItem()=="Audi")
                {
                    SportCar Audi = new Audi(300,1.2,1200,200);
                     Second= Audi;
                }
                if(ChooseOppsCar.getSelectedItem()=="Ferrari")
                {
                    SportCar Ferrari = new Ferrari(440,0.8,900,260);
                      Second= Ferrari;
                }
                if(ChooseOppsCar.getSelectedItem()=="Porsche")
                {
                    SportCar Porsche = new Porsche(380,0.9,1000,220);
                    Second= Porsche;
                }
                if(ChooseOppsCar.getSelectedItem()=="Lamborghini")
                {
                    SportCar Lamborghini = new Lamborghini(450,0.7,900,250);
                    Second= Lamborghini;
                }

                ChooseYourCar.setVisible(false);
                ChooseOppsCar.setVisible(false);

                Commentry.setText("IT IS TIME TO GET THE SIMLATION UNDER WAY, THE TWO CARS HAVE BEEN CHOOSEN AND THERE ATTRIBUTES ARE BELOW.");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Track.setLocation(1, 1);
                Track.setBackground(Color.BLACK);
                Track.setLocation(2, 1);
                Track.setBackground(Color.ORANGE);
                Commentry.setText("THE CARS ARE NOW IN PLACE IN BLACK WE HAVE "+ first.getName()+"\n"+"WHILE OUR OTHER CAR IN ORANGE, WE HAVE "+ Second.getName());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Commentry.setText("LETS RACE");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Commentry.setText("3");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Commentry.setText("2");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Commentry.setText("1");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Commentry.setText("GO");


                double firstCurrentPosition = (first.getcurrentspeed()+first.getGrip());
                double secondCurrentPosition = (Second.getcurrentspeed()+Second.getGrip());
                if(firstCurrentPosition>secondCurrentPosition){
                    Track.setLocation(1, 1);
                    Track.setBackground(Color.GREEN);
                    Track.setLocation(2, 1);
                    Track.setBackground(Color.GREEN);

                    Track.setLocation(1, 3);
                    Track.setBackground(Color.BLACK);
                    Track.setLocation(2, 2);
                    Track.setBackground(Color.ORANGE);
                   Commentry.setText("WOW "+ firstCurrentPosition+ " "+ secondCurrentPosition);
                  }

        }

        }


    public static void main(String[] args) {
        // TODO Auto-generated method stub
       Track window = new Track();
       window.setDefaultCloseOperation(EXIT_ON_CLOSE);
       window.setSize(750,530);
       window.setVisible(true);
       window.setTitle("Car Race Simulator");


       }


}
dawodus
  • 1
  • 3
  • 2
    Surely not all that code is relevant. Try reducing your code sample by removing GUI elements and functionality until you find the bit that makes it crash. – millimoose Mar 19 '13 at 23:08
  • 4
    Also, for a crash, you should provide the stack trace, and comment where in your code sample the stack trace elements point to. – millimoose Mar 19 '13 at 23:09
  • lol this was me trying to lower it but previously if i took code out of a class people got angry at me so trying to appease everyone, most of it is relevant in the sense that it shows what i am trying to achieve else some people would have no idea :). as for the stack trace how do i do that is it within the debug section as i didnt have any errors on the compiler it ran? – dawodus Mar 19 '13 at 23:09
  • stack trace. Trust me. – DigCamara Mar 19 '13 at 23:11
  • 1
    The Stacktrace comes after the exception is thrown. It's inside the console. – Langusten Gustel Mar 19 '13 at 23:14
  • 1
    This `if (ChooseYourCar.getSelectedItem() == "Aston martin") {` is not how to compare `String`s in Java, use `"Aston martin".equals(ChooseYourCar.getSelectedItem())` instead. – MadProgrammer Mar 19 '13 at 23:21
  • If im correct in saying the stack trace is in the console then, my console is empty and shows nothing? And MadProgrammer if (ChooseYourCar.getSelectedItem() == "Aston martin") works if i took out the startrace event and it worked fine thats not the problem i dont think – dawodus Mar 19 '13 at 23:25
  • 1: you did not mention which Java version you use, and on which OS! 2: MadProgrammer is right, but since Java 7 the comparision with "==" has more chances to work. 3: the title of your question is "... keeps Crashing", so what crashes, resp. how does the "crash" manifest itself while running the application without debugger? – t0r0X Mar 19 '13 at 23:32
  • 3
    `Thread.sleep(2000);` Don't do that in a GUI. *"if i took code out of a class people got angry at me so trying to appease everyone"* One of the first principles of trimming code is that if the problem can be seen with just 2 of something for which the main app. has 5, just reduce it to the 2. That code covers 5 car makes, so take 3 out. For more tips, see [SSCCE](http://sscce.org/). – Andrew Thompson Mar 20 '13 at 01:25
  • @dawodus Also, people getting angry at you for posting too little code was probably a wrong reaction on their part. (Unless it was absurdly little or a blatantly incomplete / unpolished sample.) Ideally, you want a code sample that can (modulo boilerplate like imports or a class declaration if your code is procedural) be copy-pasted into the IDE and will manifest the same kind of error as in your actual app, while being short enough to read easily. (Or at least as easily as can be expected.) – millimoose Mar 20 '13 at 03:02
  • @dawodus if my answer was helpful to you and has led to a solution, please don't forget to mark the answer as 'accepted' – t0r0X Apr 16 '13 at 16:14

1 Answers1

3

It was very hard for me to grab your question, and after a while I understood that the title "Java GUI keeps Crashing" in fact means "Java GUI hangs".

Very clear case: you're doing too much work in the "event2.actionPerformed()" method [because of the Thread.sleep() calls], so the event dispatch thread [also called EDT], which calls the "actionPerfomed()" methods of all listeners, is blocked until that long running method has completed. Therefore the GUI "hangs" a good while after you pressed the StartRace button!

Simple answer: use a SwingWorker (available in the Java runtime since Java 6)! Here two good examples:

I would have explained the need for SwingWorker in more detail, but there are already many excellent explanations on the web, e.g.

PS
More info: move the long running code in a worker class, e.g.

    class RaceWorker extends SwingWorker<Void, Void> {
        @Override
        protected Void doInBackground() throws Exception {
            // ... long running code here ...
            return null;
        }
    }

so the "actionPerformed()" method will look like e.g.:

    public void actionPerformed(ActionEvent startrace) {
        new RaceWorker().execute();
    }

PPS
By the way... I predict you a very hard time, not with the implementation, but with the code: e.g. as soon you'll try to access the member variable currently named "Track" from the StartWorker, the compiler will confuse it with the "Track" class name and will refuse to compile. My (unasked) advice: cleanup first the naming of methods, variables and member variables, and after that do the refactoring with SwingWorker. This way you'll save lots of time and trouble. A succint overview on usual Java code conventions is in this Wikipedia article on Naming convention/Java and that should be enough for your code [I personally do use the "underscore on instance variables", but this is a matter of taste and experience]. For the sake of completeness: the "official" Java code conventions are from Oracle.

Community
  • 1
  • 1
t0r0X
  • 4,212
  • 1
  • 38
  • 34
  • You sir are a legend this information had helped me alot thank you very much for your help and patience with my bad explanation. Very much appreciated – dawodus Mar 20 '13 at 13:32