为了使程序绘制图1中所示的图像,我应该对代码进行什么更改?

时间:2018-10-29 17:25:36

标签: java draw

这是预期的输出:

这是我的代码产生的:

这是代码。我应该对其进行哪些更改以使其产生正确的图像?

package blatt03;

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

public class LoesungKegel extends JFrame {
private static final long serialVersionUID = 1L;

public LoesungKegel() {
    super();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setSize(610, 417);
    this.setTitle("Lösung in der Klasse " + this.getClass().getName());
    this.setVisible(true);
}

public static void main(String[] args) {
    new LoesungKegel();
}

public void paint(Graphics g) {
    int x25 = this.getWidth() / 4;
    int x75 = this.getWidth() * 3 / 4;
    int y25 = this.getHeight() / 4;
    int y75 = this.getHeight() * 3 / 4;

    double stepX = getWidth() / 40;
    double step1 = getHeight()  / 40;

    g.drawLine(x75, y25, x25, y25);

    g.drawLine(x75, y25, x25, y75);

    g.drawLine(x25, y75, x75, y75);

    g.drawLine(x25, y25, x75, y75);

    for (int i = 0; i < 40; i++) {

         g.drawLine(x25, y25, x25/2 + (int) (stepX * i), y25/2 - (int) (step1 * i));

        g.drawLine(x25/2 + (int) (stepX * i), y25/2 - (int) (step1 * i), x75, y75);

    }

}
}

不是图片2,而是我的代码当前显示的图片。

2 个答案:

答案 0 :(得分:2)

您试图生成的图像比您试图用于生成图像的代码要简单得多。它只是行的一端水平前进,而另一端则后退相同量。这样便可以达到这样的效果(假设您试图绘制40条线)。

@Override
public void paint(Graphics g) {
    // fill background
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, getWidth(), getHeight());

    int x25 = this.getWidth() / 4;
    int x75 = this.getWidth() * 3 / 4;
    int y25 = this.getHeight() / 4;
    int y75 = this.getHeight() * 3 / 4;

    // draw inner lines
    g.setColor(Color.LIGHT_GRAY);
    int width = x75 - x25;
    double step = width / 40.0;
    for (double i = 0; i < width; i += step) {
        g.drawLine((int)(x25 + i), y25, (int)(x75 - i), y75);
    }

    // draw outer lines
    g.setColor(Color.BLACK);
    g.drawLine(x25, y25, x75, y25);
    g.drawLine(x25, y75, x75, y75);
    g.drawLine(x25, y25, x75, y75);
    g.drawLine(x75, y25, x25, y75);
}

答案 1 :(得分:0)

这很接近,同时保持了您的方法要旨。

public void paint(Graphics g) {
    int x25 = this.getWidth() / 4;
    int x75 = this.getWidth() * 3 / 4;
    int y25 = this.getHeight() / 4;
    int y75 = this.getHeight() * 3 / 4;
    int x50 = this.getWidth() / 2;
    int y50 = this.getHeight() / 2;

    int stepX = (x75 - x25) / 40;

    g.drawLine(x75, y25, x25, y25);

    g.drawLine(x75, y25, x25, y75);

    g.drawLine(x25, y75, x75, y75);

    g.drawLine(x25, y25, x75, y75);

    for (int i = 1; x25 + (i * stepX) < x75; i++) {

        g.drawLine(x50, y50, x25 + (stepX * i), y25);

        g.drawLine(x50, y50, x25 + (stepX * i), y75);

    }

}