⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 exercise11_15.java

📁 Introduction to java programming 一书中所有编程练习部分的源码
💻 JAVA
字号:
// Exercise11_15.java: Draw a diagram for function f(x) = x*x
import java.awt.*;
import javax.swing.*;

public class Exercise11_15 extends JFrame {
  public Exercise11_15() {
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(new DrawXSquare(), BorderLayout.CENTER);
  }

  public static void main(String[] args) {
    Exercise11_15 frame = new Exercise11_15();
    frame.setSize(400, 400);
    frame.setTitle("Exercise11_15");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }

  // Inner class
  class DrawXSquare extends JPanel {
    double f(double x) {
      return x*x;
    }

    // Draw the function
    public void drawFunction() {
      repaint();
    }

    protected void paintComponent(Graphics g) {
      super.paintComponent(g);

      g.drawLine(10, 200, 390, 200);
      g.drawLine(200, 30, 200, 390);

      // Draw arrows
      g.drawLine(390, 200, 370, 190);
      g.drawLine(390, 200, 370, 210);
      g.drawLine(200, 30, 190, 50);
      g.drawLine(200, 30, 210, 50);

      // Draw x, y axises
      g.drawString("X", 390, 170);
      g.drawString("Y", 220, 40);

      // Draw function
      Polygon p = new Polygon();

      double scaleFactor = 0.01;

      for (int x = -100; x <= 100; x++) {
        p.addPoint(x + 200, 200 - (int)(scaleFactor * f(x)));
      }

      g.drawPolyline(p.xpoints, p.ypoints, p.npoints);
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -