第2章 Java程序设计环境

安装Java开发工具包

下载JDK

Download the Latest Java LTS Free
image

设置JDK

image

安装源文件和文档

使用命令行工具

image

$ java Welcome.java
$ java Welcome

image

程序清单 2-1 Welcome/Welcome.java
/**
 * This program displays a greeting for the reader.
 * @version 1.30 2014-02-27
 * @author Cay Horstmann
 */
public class Welcome
{
   public static void main(String[] args)
   {
      String greeting = "Welcome to Core Java!";
      System.out.println(greeting);
      for (int i = 0; i < greeting.length(); i++)
         System.out.print("=");
      System.out.println();
   }
}

✅ 提示:教程(提到初学者经常容易犯的错误)
Lesson:The"Hello World!" Application

使用集成开发环境

image

image

image

运行图形化应用程序

image

image

image

image

image

image

程序清单 2-2 ImageViewer/ImageViewer.java
import java.awt.*;
import java.io.*;
import javax.swing.*;

/**
 * A program for viewing images.
 * @version 1.30 2014-02-27
 * @author Cay Horstmann
 */
public class ImageViewer
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() -> {
         JFrame frame = new ImageViewerFrame();
         frame.setTitle("ImageViewer");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }
}

/**
 * A frame with a label to show an image.
 */
class ImageViewerFrame extends JFrame
{
   private JLabel label;
   private JFileChooser chooser;
   private static final int DEFAULT_WIDTH = 300;
   private static final int DEFAULT_HEIGHT = 400;

   public ImageViewerFrame()
   {
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

      // use a label to display the images
      label = new JLabel();
      add(label);

      // set up the file chooser
      chooser = new JFileChooser();
      chooser.setCurrentDirectory(new File("."));

      // set up the menu bar
      JMenuBar menuBar = new JMenuBar();
      setJMenuBar(menuBar);

      JMenu menu = new JMenu("File");
      menuBar.add(menu);

      JMenuItem openItem = new JMenuItem("Open");
      menu.add(openItem);
      openItem.addActionListener(event -> {
         // show file chooser dialog
            int result = chooser.showOpenDialog(null);

            // if file selected, set it as icon of the label
            if (result == JFileChooser.APPROVE_OPTION)
            {
               String name = chooser.getSelectedFile().getPath();
               label.setIcon(new ImageIcon(name));
            }
         });

      JMenuItem exitItem = new JMenuItem("Exit");
      menu.add(exitItem);
      exitItem.addActionListener(event -> System.exit(0));
   }
}

构建并运行applet

image

image

程序清单 2-3 RoadApplet/RoadApplet.html
<html xmlns="http://www.w3.org/1999/xhtml">
   <head><title>A Traffic Simulator Applet</title></head>
   <body>    
      <h1>Traffic Simulator Applet</h1>
      
      <p>I wrote this traffic simulation, following the article &quot;Und nun die
      Stauvorhersage&quot; of the German Magazine <i>Die Zeit</i>, June 7,
      1996. The article describes the work of Professor Michael Schreckenberger
      of the University of Duisburg and unnamed collaborators at the University
      of Cologne and Los Alamos National Laboratory. These researchers model
      traffic flow according to simple rules, such as the following: </p>
      <ul>
         <li>A freeway is modeled as a sequence of grid points. </li>
         <li>Every car occupies one grid point. Each grid point occupies at most
         one car. </li>
         <li>A car can have a speed of 0 - 5 grid points per time interval. </li>
         <li>A car with speed of less than 5 increases its speed by one unit in
         each time interval, until it reaches the maximum speed. </li>
         <li>If a car's distance to the car in front is <i>d</i> grid points, its
         speed is reduced to <i>d</i>-1 if necessary to avoid crashing into it.
         </li>
         <li>With a certain probability, in each time interval some cars slow down
         one unit for no good reason whatsoever. </li>
      </ul>
      
      <p>This applet models these rules. Each line shows an image of the same
      stretch of road. Each square denotes one car. The first scrollbar lets you
      adjust the probability that some cars slow down. If the slider is all the
      way to the left, no car slows down. If it is all the way to the right,
      every car slows down one unit. A typical setting is that 10% - 20% of the
      cars slow down. The second slider controls the arrival rate of the cars.
      When it is all the way to the left, no new cars enter the freeway. If it
      is all the way to the right, a new car enters the freeway every time
      interval, provided the freeway entrance is not blocked. </p>
      
      <p>Try out the following experiments. Decrease the probability of slowdown
      to 0. Crank up the arrival rate to 1. That means, every time unit, a new
      car enters the road. Note how the road can carry this load. </p>
      
      <p>Now increase the probability that some cars slow down. Note how traffic
      jams occur almost immediately. </p>
      
      <p>The moral is: If it wasn't for the rubberneckers, the cellular phone
      users, and the makeup-appliers who can't keep up a constant speed, we'd all
      get to work more quickly. </p>
      
      <p>Notice how the traffic jam is stationary or even moves backwards, even
      though the individual cars are still moving. In fact, the first car
      causing the jam has long left the scene by the time the jam gets bad. 
      (To make it easier to track cars, every tenth vehicle is colored red.) </p>
      
      <p><applet code="RoadApplet.class" archive="RoadApplet.jar" 
                 width="400" height="400" alt="Traffic jam visualization">
      </applet></p>
      
      <p>For more information about applets, graphics programming and
      multithreading in Java, see
      <a href="http://horstmann.com/corejava">Core Java</a>. </p>
   </body>
</html>

在浏览器显示(非必要,现在大多数浏览器不支持)

image

image

为什么 Java、Silverlight、Adobe Acrobat 和其他一些插件不再工作了

参考浏览器说明解决
Firefox中使用插件

程序清单 2-4 RoadApplet/RoadApplet.java
import java.awt.*;
import java.applet.*;
import javax.swing.*;

public class RoadApplet extends JApplet
{  
   private RoadComponent roadComponent;
   private JSlider slowdown;
   private JSlider arrival;

   public void init()
   {
      EventQueue.invokeLater(() ->
         {
            roadComponent = new RoadComponent();
            slowdown = new JSlider(0, 100, 10);    
            arrival = new JSlider(0, 100, 50);
        
            JPanel p = new JPanel();
            p.setLayout(new GridLayout(1, 6));
            p.add(new JLabel("Slowdown"));
            p.add(slowdown);
            p.add(new JLabel(""));
            p.add(new JLabel("Arrival"));
            p.add(arrival);
            p.add(new JLabel("")); 
            setLayout(new BorderLayout());
            add(p, BorderLayout.NORTH);
            add(roadComponent, BorderLayout.CENTER);
         });
   }
   
   public void start()
   {
      new Thread(() -> 
         {
            for (;;) 
            {
               roadComponent.update(
                  0.01 * slowdown.getValue(),
                  0.01 * arrival.getValue());
               try { Thread.sleep(50); } catch(InterruptedException e) {}
            }
         }).start();
   }
}
posted @   手持六脉神剑的外星人  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示