Java在一个框架中绘制线条

时间:2015-05-31 01:15:17

标签: java swing jframe jpanel awt

我尝试做一个非常简单的事情..在主类我为协调系统绘制2行..在类userPaint我从x1 y1 x2 y2(已经初始化)绘制1行。问题是3条线(坐标系和x1y1x2y2线)不在同一个窗口/框架中。编译器创建了2个窗口......我该如何解决?

主要课程:

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();
    }
}

userPaint类:

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 个答案:

答案 0 :(得分:4)

  1. 不要直接绘制到JFrame,而是绘制到JPanel,您可以通过JFrame {JFrame添加add的内容窗格{1}}方法
  2. (1)中的绘画应该通过覆盖paintComponent方法(而不是paint方法)来完成。
  3. 例如:

    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());
    
      

    为坐标系绘制2行

    您提到了坐标系,因此您可能希望将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轴的位置(负值使图不反转) - 假设这些值未被抵消,它们的像素位置相对于轴的边界。

    最后一点:类名应为大写