0

我试图弄清楚如何在鼠标单击时重绘面板。我可以很好地捕捉鼠标点击,但不能为我的生活获取组件来绘制。这是我为简单起见设置的简化测试类。我的测试类扩展了 JComponent。

有任何想法吗?

这是我的主要内容:

public static void main(String[] args) {
        JFrame frame = new JFrame("Point Capture Test");
        frame.setContentPane(new Test().panelMain);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();

        frame.setVisible(true);
    }

这是我的测试构造函数:

 public Test() {

        mPanel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {

                JOptionPane.showMessageDialog(panelMain, e.getPoint());
                JOptionPane.showMessageDialog(panelMain, "clicked "+ e.getSource() + " at " + e.getPoint());

                 //removed a bunch of stuff here that captures the clicked coordinates so I can use them to draw lines on the panel

                repaint();
            }
        });

    }

这是我的测试 paintComponent 方法:

    public void paintComponent(Graphics g){

        Graphics2D g2 = (Graphics2D) g;
        if (this.mClicks > 2) { //draw polygon
            Polygon polyTest = new Polygon();

            for (Point point : this.mPntPoints){
                polyTest.addPoint(point.x, point.y);
            }

            g2.setColor(Color.RED);
            g2.fill(polyTest);
            g2.draw(polyTest);
        }

        //just added this as a test and it doesn't draw either
        g2.drawLine(10, 30, 20, 40);

}
4

0 回答 0