问题描述
我正在尝试在 Eclipse 上做一个小程序.程序是这样的:当我在框架上的 thr Panel 上第一次单击时,必须绘制一条关于我的鼠标侦听器的 Y 位置的线.该线占据了面板的所有宽度.在第二次单击时,必须绘制另一条线,同样是关于我单击的 Y 位置.之后,我会在两条线之间放一个小圆圈并用它制作一个小动画.但是现在,我有一个问题.当我点击面板时,会画一条线,但如果我再点击一次,第一条线消失,第二条线取而代之......这是painComponent 和我的mousr 监听器的代码.有什么问题吗?
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 是绘制整个组件的事件.你不能依赖过去的事件,因为每次重绘发生时它们都会被删除.
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.
您需要保留类似于 List
的内容,并且每次创建新行时,都将其添加到 List
.
You would need to keep something like a List
and each time you create a new line, you add it to the List
.
List<Integer> 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();
}
还有:
- 永远不要在
paintComponent
中调用repaint
!这将导致无休止的重绘循环. paintComponent
是一种受保护的方法,除非有令人信服的理由将其公开,否则应保持如此.- 小心更改传递给
paintComponent
的Graphics
对象的状态,因为它在别处使用.通常我们会创建一个本地副本,当我们完成时它会被处理掉.
- Never call
repaint
insidepaintComponent
! 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 topaintComponent
because it is used elsewhere. Usually we create a local copy which is disposed when we are done.
这篇关于在java中画线(图形2D)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!