简体   繁体   English

类没有主要方法(红绿灯)

[英]Class doesn't have a main method (Traffic Light)

I found a java code from this link.我从这个链接找到了一个java代码。

and when I tried to run it the error class doesnt have a main method.I know this is a similiar post but I tried searching/trying for different solution but when I tried them they dont work.当我尝试运行它时,错误类没有主要方法。我知道这是一个类似的帖子,但我尝试搜索/尝试不同的解决方案,但是当我尝试它们时,它们不起作用。 Below is the code下面是代码

package trafficlight;


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

public final class TrafficLight extends JPanel implements Runnable{

  int redDuration,  // Time (in seconds) for duration of red light
      yellowDuration,   // Time (in seconds) for duration of yellow light
      greenDuration;    // Time (in seconds) for duration of green light
  PedestrianLight PL;   // Associated coordinated pedestrian light
  Color onLight;    // To indicate which color light is on

  int TLWidth = 0;  // Width of traffic light
  int TLHeight;     // Height of traffic light
  int xOrigin;      // Coordinates of upper left-hand corner of
  int yOrigin;          // traffic light
  int xLCoor;       // x coordinate of lights
  int yLCoor;       // y coor of red light
  int LDiam;        // Diameter of each light
  int interLSpace;  // Space between lights

  /*************************************
   * Constructors
   *************************************/

  TrafficLight( PedestrianLight PL )    // One-parameter constructor
  {
      this.PL = PL;
      onLight = Color.green;
      redDuration = 15000;      // Set red duration to 15 secs
      yellowDuration = 5000;        // Set yellow duration to 5 seconds
      greenDuration = 15000;        // Set green duration to 15 secs
  }



  TrafficLight( PedestrianLight PL,Color c ) // Two-parameter constructor
  {
      this.PL = PL;
      setOnLight( c );    // Verify color setting
      redDuration = 15000;      // Set red duration to 15 secs
      yellowDuration = 5000;        // Set yellow duration to 5 seconds
      greenDuration = 15000;        // Set green duration to 15 secs
  }


  TrafficLight( PedestrianLight PL,int redDur,int yellowDur,int greenDur ){
      this.PL = PL;
      onLight = Color.green;
      redDuration = 1000*redDur;    // Duration params given in secs
      yellowDuration = 1000*yellowDur;  // Convert to milliseconds
      greenDuration = 1000*greenDur;
  }

  /**************************************
   * Setters and getters
     * @return 
   **************************************/

  public Color getOnLight()
  {
      return onLight;
  }

  public void setOnLight( Color c )
  {
      // Setters and constructors should insure that class variables
      // are set to valid values.
      if ( c == Color.red || c == Color.yellow || c == Color.green )
          {
              onLight = c;
          }
      else
          {
              System.out.println("TrafficLight.setOnLight:  cannot set " +
                                 "traffic light to color " + c +
                                 "\nSetting color to default green.");
              onLight = Color.green;
          }
  }

  public void setColor( Color c ){
      setOnLight( c );
      repaint();
  }

  /************************************************
   * Paint
   ************************************************/

  @Override
  public void paintComponent(Graphics g)
  {
   super.paintComponent( g );       // For background
   System.out.println("Painting traffic light again");
   if ( TLWidth == 0 ){
       Dimension d = getSize();     // Get size of panel
       System.out.println("d = " + d);
       TLWidth = d.width/2;     // Set width of traffic light
       TLHeight = 3*d.height/4;     // Set height of traffic light
       xOrigin = (d.width - TLWidth)/2; // Center traffic light on panel
       yOrigin = (d.height - TLHeight)/2;
       LDiam = TLHeight/6;          // Diameter of each light
       xLCoor = xOrigin + (TLWidth - LDiam)/2;  // x coordinate of lights
       interLSpace = (TLHeight - 3*LDiam)/4;    // Space between lights
       yLCoor = yOrigin + interLSpace;      // y coor of red light
   }

   Color colorSave = g.getColor();  // Save current color

   //Draw outline of traffic light
   g.setColor( Color.lightGray );
   g.fill3DRect(xOrigin,yOrigin,TLWidth,TLHeight,true);

   Color Red, Yellow, Green;        // Colors to change light to
   // Change the light
   if ( onLight == Color.red ){
       Red = turnOn( Color.red );
       Yellow = turnOff( Color.yellow );
       Green = turnOff( Color.green );
   }
   else if ( onLight == Color.yellow ){
       Red = turnOff( Color.red );
       Yellow = turnOn( Color.yellow );
       Green = turnOff( Color.green );
   }
   else{
       Red = turnOff( Color.red );
       Yellow = turnOff( Color.yellow );
       Green = turnOn( Color.green );
   }

   // Now color the lights.  onLight is bright others are darkened.

   g.setColor( Red );
   g.fillOval(xLCoor,yLCoor,LDiam,LDiam);

   g.setColor( Yellow );
   g.fillOval(xLCoor,yLCoor+LDiam+interLSpace,LDiam,LDiam);

   g.setColor( Green );
   g.fillOval(xLCoor,yLCoor+2*LDiam+2*interLSpace,LDiam,LDiam);

   // Now draw black outline around each light
   g.setColor(Color.black);
   // Red light
   g.drawOval(xLCoor,yLCoor,LDiam,LDiam);
   // Yellow light
   g.drawOval(xLCoor,yLCoor+LDiam+interLSpace,LDiam,LDiam);
   // Green light
   g.drawOval(xLCoor,yLCoor+2*LDiam+2*interLSpace,LDiam,LDiam);

   g.setColor(colorSave);       // Restore original color
  }

 /************************************************
  * Auxillary methods used by paintComponent
  ************************************************/

  Color turnOn( Color c )
  { return c.brighter().brighter(); }

  Color turnOff( Color c )
  { return c.darker().darker(); }

 /************************************************
  * run method as required by Runnable interface
  ************************************************/

  @Override
  public void run(){
      System.out.println("Entering TrafficLight.run()");
      long startTime;
      PL.setMessage( "Don't Walk" );
      while ( true )
      {
         setColor( Color.red );      // Change traffic light to red
         try{ 
             System.out.println( "TL.run() sleep for " + redDuration +
                                 "milliseconds." );
             Thread.sleep( redDuration ); 
         }
         catch ( InterruptedException e ) {}

         startTime = System.currentTimeMillis();
         setColor( Color.green );       // Change traffic light to green
         PL.setMessage( "Walk" );       // Change ped light to "Walk"
         try{               // Sleep for 2/3 green dur minus time
             startTime += 2*greenDuration/3; // to change lights
             Thread.sleep( Math.max( 0,startTime-System.currentTimeMillis() ) );
         }
         catch ( InterruptedException e ) {}

         //PL.setMessage( "Don't Walk" ); // change ped light to "Don't Walk"
         //PL.setFlashing( true );        // & start ped light flashing.
         startTime = System.currentTimeMillis(); 
         PL.setMessage( "Don't Walk",true ); //Atomize above two calls
         try{ 
             startTime += greenDuration/3; // Sleep 1/3 green duration
             Thread.sleep( Math.max( 0,startTime-System.currentTimeMillis() ) );
         }
         catch ( InterruptedException e ) {}

         startTime = System.currentTimeMillis();
         PL.setFlashing( false );    // Chg ped light from flash to solid
         setColor( Color.yellow );   // Change traffic light to yellow
         try{ 
             startTime += yellowDuration;
             Thread.sleep( Math.max( 0,startTime-System.currentTimeMillis() ) );
         }
         catch ( InterruptedException e ) {}
      }
  }

    private static class PedestrianLight {

        public PedestrianLight() {
        }

        private void setFlashing(boolean b) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        private void setMessage(String dont_Walk, boolean b) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        private void setMessage(String walk) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    }

Your question have the answer, you don't have a main method in your code/class which you are trying to execute.您的问题有答案,您的代码/类中没有您尝试执行的主要方法。

As you mentioned in your comment you are new to java use IDEs like Eclipse, Netbeans or IntelliJ IDEA where they gives you proper warnings and hints.正如您在评论中提到的,您是 Java 新手,请使用 Eclipse、Netbeans 或 IntelliJ IDEA 等 IDE,它们会为您提供适当的警告和提示。

I think the code you found is derived from this:我认为您找到的代码源自于此:

If you look at the linked file, there is a block comment at the start that says this:如果您查看链接的文件,会发现开头有一个块注释:

/**
 * The <code>class TrafficLight</code> defines a panel on which the
 * <code>paintComponent( Graphics )</code> method draws a traffic light.
 * This code uses JDK 1.2.
 * This version of the class also implements Runnable with a run method
 * that animates the traffic light and sends signals to a coordinated
 * pedestrian light (whose name must be provided to the Traffic light 
 * constructor) to change and flash the pedestrian light at the appropriate
 * times.  This is done by synchronized getters and setters in the
 * associated pedestrian light class.
 *
 * To use (or install) such a light, it is only necessary in the applet
 * to declare the associated pedestrian light, declare the traffic light
 * and pass it the name of the associated pedestrian light and the desired
 * time durations for each of the red (default 15 secs), yellow 
 * (default 5 secs), and green (default 15 secs) lights.  The pedestrian
 * light will be a solid "Don't Walk" during the red and yellow lights.
 * On the green light, the pedestrian light will display a solid "Walk"
 * for the first 2/3 of the green duration and the last 1/3 of the
 * green duration, the "Walk" will flash.  All of the animation is 
 * provided by the run methods in the traffic light and pedestrian light
 * classes.
 */

Code up an Applet that does that, and you can run the code.编写一个 Applet 来执行此操作,然后您就可以运行该代码。

Your posted class TrafficLight.java is part of an Applet .您发布的类TrafficLight.javaApplet一部分。 So it cannot be run on it's own.所以它不能自己运行。

Applets itself normally are embedded into a webpage and run inside a browser.小程序本身通常嵌入到网页中并在浏览器中运行。 See more about applets on Oracles Applet tutorial .Oracles Applet 教程中查看有关 Applet 的更多信息。

To run it within an applet you could download the following files from here要在小程序中运行它,您可以从这里下载以下文件

The you can run the applet as:您可以将小程序运行为:

appletviewer TLApplet.html

To run the applet code from commandline without the appletviewer you need some graphic container where the applet can be executed.要在没有小程序查看器的情况下从命令行运行小程序代码,您需要一些可以执行小程序的图形容器。

An example snippet looks like一个示例片段看起来像

import javax.swing.JFrame;
import javax.swing.JApplet;

class TLAppletFrame {

    public static void main(String[] args) {
        JApplet applet = new TLApplet();
        applet.init();

        JFrame frame = new JFrame("Applet in Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( applet );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );

        applet.start();
    }   
}

To run it you have to execute (assumed the file TLAppletFrame.java is in the same directory as the downloaded files)要运行它,您必须执行(假设文件TLAppletFrame.java与下载的文件在同一目录中)

javac TLAppletFrame.java
java TLAppletFrame

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM