Adding a MouseListener to a panel

前端 未结 5 1704
轻奢々
轻奢々 2021-01-29 07:10

I am trying to add the mouse actions to my panel. This is what the program is supposed to do:

Write a program that allows the user to specify a triangle

5条回答
  •  爱一瞬间的悲伤
    2021-01-29 07:55

    I would strongly recommend you start by having a read through How to Write a Mouse Listener. When ever you get stuck, these tutorials (and the JavaDocs) are the best place to get started

    The "immediate" answer to your question is, you need to register an instance of the MouseListener with your component, maybe something like...

    private JPanel createCenterPanel() {
    
        panel.addMouseListener(new MouseListen());
        //panel.setLayout(null);
    
    
        return panel;
    }
    

    This will "answer" your immediate issue.

    However, you'll find it hard to try and marry up the actions of the MouseListener with the panel, which needs to paint the results.

    A better solution might be to start with a JPanel which manages it's own MouseListener

    Also, Graphics g = panel.getGraphics() isn't how custom painting should be performed. Take a look at Performing custom painting for more details

    So, instead, it might look something more like...

    public class TrianglePanel extends JPanel {
    
        private List points = new ArrayList<>(3);
    
        public TrianglePanel() {
            addMouseListener(new MouseListen());
        }
    
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
    
            if (points.size() < 1) {
                return;
            }
            for (int index = 0; index < points.size(); index++) {
                Point nextPoint = points.get(index);
                g.fillOval(nextPoint.x - 2, nextPoint.y - 2, 4, 4);
            }
    
            Point startPoint = points.get(0);
            Point lastPoint = startPoint;
            for (int index = 1; index < points.size(); index++) {
                Point nextPoint = points.get(index);
                g.drawLine(lastPoint.x, lastPoint.y, nextPoint.x, nextPoint.y);
                lastPoint = nextPoint;
            }
            g.drawLine(lastPoint.x, lastPoint.y, startPoint.x, startPoint.y);
        }
    
        class MouseListen extends MouseAdapter {
    
            public void mouseReleased(MouseEvent e) {
                if (points.size() < 3) {
                    points.add(e.getPoint());
                    repaint();
                }
            }
        }
    
    }
    

提交回复
热议问题