java 绘制图形2d,绘制线在java(图形2D)

I am trying to do a little program on Eclipse. The program goes like this: when I click for the 1st time on thr Panel on the frame, a line has to be drawn regarding the Y position of my mouse listener.The line takes all the width of the panel. On the 2nd click, another line has to be drawn, again regarding the Y position of where I clicked. After, I'll put a little circle between the 2 lines and make a little animation with it.

But now, I have a problem. When I click on the panel, a line is drawn, but if i click another time, the first line disappears and the 2nd line takes it place...

This is the code of the painComponent and my mousr listener. What is wrong with it ?

public Lines() {

addMouseListener(new MouseAdapter() {

@Override

public void mouseClicked(MouseEvent e) {

posY=e.getY();

posX=e.getX();

nbClic=e.getClickCount();

repaint();

}

});

setBackground(Color.black);

}

@Override

public void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

g2d.setColor(Color.blue);

if(nbClic>=1){

line1=new Line2D.Double(0, posY, getWidth(), posY);

g2d.draw(line1);

repaint();

}

if(nbClic>=2){

g2d.setColor(Color.YELLOW);

line2=new Line2D.Double(0, posY, getWidth(), posY);

g2d.draw(line2);

}

repaint();

}

解决方案

Painting is an event that draws the entire component. You can't depend on past events because they are erased each time a repaint happens.

You would need to keep something like a List and each time you create a new line, you add it to the List.

List yClicks = new ArrayList<>();

... {

addMouseListener(new MouseAdapter() {

@Override

public void mouseClicked(MouseEvent e) {

yClicks.add(e.getY());

repaint();

}

});

}

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2d = (Graphics2D)g.create();

for(int y : yClicks) {

g2d.draw(new Line2D.Double(0, y, getWidth(), y));

}

g2d.dispose();

}

Also:

Never call repaint inside paintComponent! This will cause an endless cycle of repaints.

paintComponent is a protected method and should remain so unless there is a compelling reason to make it public.

Be careful changing the state of the Graphics object passed in to paintComponent because it is used elsewhere. Usually we create a local copy which is disposed when we are done.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值