背景: 我正在制作一个“pictionary”或类似于“画画”的多人游戏。
问题: 当我手绘它不断调用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();
}
}
此图显示了点击按钮后绘制的内容: http://imgur.com/o9QCTjF
答案 0 :(得分:1)
super.paintComponent's'(g);
看起来你有一个错字。你不想要paintComponent(...);中的“s”;
c.validate();
c.repaint();
此外,您不需要以上两行。当框架可见时,框架将重新生效并绘制。您使用revalidate()和repaint()方法的唯一时间是从可见GUI添加/删除组件。
编辑:
它只在应用程序上显示一个点
如果您想进行渐进式绘画,请查看Custom Painting Approaches,了解执行此操作的两种常用方法示例: