java中在面板上怎么画直线?
发布网友
发布时间:2022-05-11 20:46
我来回答
共3个回答
热心网友
时间:2023-10-19 23:11
方法1:
public static void main(String[] args) {
//JPanel p = new JPanel(); 注释掉这句
JFrame frame = new JFrame("DrawLine");
frame.add(new DrawLine());//将p对象换成本类
//因为本类继承了JPanel重写paintComponent进行绘制,是绘制到本类的panel上的,
//而不是绘制到new Panel()对象
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(50, 50, 200, 250);
}
方法2:
//这种方式可能 让你更理解
public static void main(String[] args) {
DrawLine dl = new DrawLine();//新建对象
dl.init();//执行初始化
}
private void init(){
//JPanel p = new JPanel(); 注释掉这句
JFrame frame = new JFrame("DrawLine");
frame.add(this);//将p对象换成本类
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(50, 50, 200, 250);
}
热心网友
时间:2023-10-19 23:12
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphcis2D g2d = (Graphics2D)g;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setStroke(new BasicStroke(2f));
g.setPaint(Color.BLUE);
g.drawLine(x1,y1,x2,y2);
g.draw(new Line2D.Double(x1d,y1d,x2d,y2d));
}
在JPanel子类的paintComponent方法里绘制。
热心网友
时间:2023-10-19 23:12
drawLine()