添加组件时,JPanel不起作用或任何方法

时间:2015-05-30 13:48:33

标签: java swing jpanel

我正在尝试向JPanel添加一个组件,但是当我这样做时JPanel中的方法没有被调用或者根本不起作用。

我要做的是拍摄现有图像并在该图像上绘图。

以下是一些代码:

drawPanel = new MyDrawPanel(MainActivity.this);
drawPanel.add(component);
MyListener alpha = new MyListener(MainActivity.this);
drawPanel.addMouseMotionListener(alpha);
drawPanel.addMouseListener(alpha);
mframe.getContentPane().setBackground(Color.WHITE);
mframe.getContentPane().add(drawPanel);

DrawPanel类:

private class MyDrawPanel extends JPanel {

    private static final long serialVersionUID = 1L;
    private MainActivity drawingTest;

    public MyDrawPanel(MainActivity drawingTest) {
        this.drawingTest = drawingTest;
        setVisible(true);

    }

    @Override
    public void paintComponent(Graphics g) {
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, this.getWidth(), this.getHeight());
        g.setColor(Color.RED);
        for (int i = 1; i < drawingTest.getPoints().size(); i++) {
            Point p1 = drawingTest.getPoints().get(i - 1);
            Point p2 = drawingTest.getPoints().get(i);
            g.drawLine(p1.x, p1.y, p2.x, p2.y);
        }
    }
}

MyListener类:

private class MyListener extends MouseInputAdapter {

    private MainActivity drawingTest;

    public MyListener(MainActivity drawingTest) {
        this.drawingTest = drawingTest;
    }

    @Override
    public void mouseDragged(MouseEvent event) {
        drawingTest.setPoint(event.getX(), event.getY());
        drawingTest.getDrawingPanel().repaint();
        System.out.println("DRAWING : ");

    }

    @Override
    public void mouseReleased(MouseEvent event) {
        drawingTest.resetPoints();
    }
}

1 个答案:

答案 0 :(得分:1)

mframe.getContentPane().add(drawPanel);
// what you forgot
mframe.getContentPane().revalidate();
mframe.getContentPane().repaint();