I need simplest way to draw a line in java in AWT panel

本小妞迷上赌 提交于 2021-02-10 23:50:55

问题


I need the simplest way to draw a line between to coordinates. Since this drawing line in my code will be repeated more than 200 times in a loop i need the easiest way. I'm drawing the lines in a AWT panel component.


回答1:


If you want to switch to Swing you would use the JPanel and overwrite the paintComponent() method.

import java.awt.Graphics;

import javax.swing.JPanel;

public class PanelWithLine extends JPanel {

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

}

You can than redraw everything by calling repaint() on your Jpanel.
You would probably change the coordinates and then call the repaint() method in your loop.




回答2:


It's been a long time since I've used java.awt.Panel, but it should be something like:

class Foo extends Panel {
  public void paint(Graphics g) {
    super.paint(g);
    g.drawLine(x1,y1,x2,y2);
    g.drawLine(x3,y3,x4,y4);
    //...
  }
}


来源:https://stackoverflow.com/questions/29904039/i-need-simplest-way-to-draw-a-line-in-java-in-awt-panel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!