Using addMouseListener() and paintComponent() for JPanel

后端 未结 4 513
不知归路
不知归路 2020-11-30 12:18

This is a follow-up to my previous question. I\'ve simplified things as much as I could, and it still doesn\'t work! Although the good thing I got around using getGrap

4条回答
  •  忘掉有多难
    2020-11-30 12:37

    You must add the mouseListener to the panel. That doesn't happen by default as you might have expected ;-)

    MainClass1() {
        addMouseListener(this);
    }
    

    BTW: it's not recommended to expose public api that's only meant to be used internally. So instead of letting the panel implement MouseListener (which enforces the public exposure), let the panel create and use a MouseListener:

    private MouseListener mouseListener;
    MainClass1() {
       mouseListener = createMouseListener();
       addMouseListener(mouseListener);
    }
    
    protected MouseListener createMouseListener() {
        MouseListener l = new MouseListener() {
    
        }
       return l;
    }
    

    BTW 2: calling the repaint on the limited area isn't exactly what you want (?) - it temporarily adds the squares to the painting, they are lost whenever the whole panel is repainted (same effect as with getGraphics). Depending on what you really want,

    • paint a single square at the most recently clicked position: call repaint()
    • paint squares at all locations ever clicked: store the locations in a list and implement repaint to loop over that list. Here you may call the repaint with parameters, but why bother?

提交回复
热议问题