Java 一帧画线

Java Draw Lines in one Frame

我尝试做一件非常简单的事情.. 在 class Main 我为坐标系画了 2 条线.. 在 class userPaint 我从 x1 y1 x2 y2 (已经初始化)。问题是3条线(坐标系和x1y1x2y2线)不在同一个window/frame。编译器创建 2 windows...我该如何解决?

主要class:

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

public class Main extends JFrame {

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.drawLine(20, 80, 20, 200);
        g.drawLine(20, 200, 140, 200);
    }

    public Main(String title){
        super(title);
        setSize(800, 600);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        Main main = new Main("Graph");
        userPaint up = new userPaint();
    }
}

用户画图class:

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

public class userPaint extends JFrame {
    int x1, y1, x2, y2;

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.drawLine(x1, y1, x2, y2);
    }

    public userPaint(){
        //Gives 4 numbers for points to drawline. Assume that the x1,y1,x2,y2 are given by Scanner.. but im gonna initialize
        x1 = 200;
        y1 = 200;
        x2 = 300;
        y2 = 300;
        setSize(800, 600);
        setVisible(true);
    }
}
  1. 不要直接绘制到 JFrame,而是绘制到 JPanel,您可以通过 JFrame 添加 JFrame 的内容面板' s add 方法
  2. (1) 中的绘制应该通过覆盖 paintComponent 方法(而不是 paint 方法)来完成。

例如:

public class Painter extends JPanel{

    public Painter(){

    }

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawLine(20, 80, 20, 200);
        g.drawLine(20, 200, 140, 200);
        g.drawLine(x1, y1, x2, y2);
    }
}

...
JFrame frame = new JFrame("Title");
frame.add(new Painter());

draw 2 lines for the Coordinate System

您提到了坐标系,因此您可能希望用坐标系的值偏移 x1..y2 值,以便绘制的线落在轴的范围内。例如:

        g.drawLine(20, 80, 20, 200);//y-axis
        g.drawLine(20, 200, 140, 200);//x-axis
        g.drawLine(x1 + 20, 200 - y1, x2 + 20, 200 - y2);//offset by coordinate system

以上将 x 值偏移 x 轴的位置,将 y 值偏移 y 轴的位置(负数,因此图不会反转)- 假设这些值不是已经偏移,并且它们的像素位置是相对于轴的边界的。

最后一点:class名字应该大写