gpt4 book ai didi

java - 不断的重画问题

转载 作者:行者123 更新时间:2023-12-01 13:41:38 24 4
gpt4 key购买 nike

背景:我正在制作一款“图画”或类似于“画东西”的多人游戏。

问题:当我徒手绘制时,它会不断调用 repaint()。当我按下按钮并单击 jpanel 时,按钮将在 jpanel 上重新绘制或重绘。

代码:

public class DrawP extends JPanel implements MouseListener, MouseMotionListener{
private int x1;
private int y1;
private int cx,cy;

public DrawP(){
super();
JFrame fr = new JFrame("Test");

JButton btn = new JButton("Test");

fr.setSize(500, 500);
Container c = fr.getContentPane();
c.add(btn, BorderLayout.SOUTH);
c.add(this);
this.addMouseListener(this);
this.addMouseMotionListener(this);
fr.setVisible(true);
c.validate();
c.repaint();
}

public void paintComponent(Graphics g){
super.paintComponents(g);
g.drawLine(cx, cy, x1, y1);
}
@Override
public void mouseDragged(MouseEvent e) {
x1 = e.getX();
y1 = e.getY();
cx = x1;
cy = y1;
repaint();
}

@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub

}

@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
cx = e.getX();
cy = e.getY();
x1 = cx;
y1 = cy;
repaint();
}

@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub

}

@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub

}

public static void main (String [] args){
DrawP d = new DrawP();

}
}

这张图显示了我点击按钮并绘制后发生的情况: /image/xMi7N.jpg

最佳答案

super.paintComponent's'(g);

您似乎有一个拼写错误。您不希望在 PaintComponent(...); 中使用“s”;

c.validate();
c.repaint();

此外,您不需要上面两行。当您使框架可见时,框架将被重新验证并绘制。唯一一次使用 revalidate() 和 repaint() 方法是当您从可见 GUI 添加/删除组件时。

编辑:

it only shows a dot on the application

如果您想进行增量绘画,请查看 Custom Painting Approaches例如执行此操作的两种常见方法:

  1. 使用列表来跟踪所有要绘制的线条
  2. 直接在 BufferedImage 上绘图。

关于java - 不断的重画问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20706377/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com