In my class Test I create Three panels. In my class Draw I draw by free hand.
I want to add my object d to centerPanel. When I do that nothing draws. But if i add it to the frame (using getContentPane().add) it draws. Does anyone knows where the problem is?
topPanel = new JPanel();
centerPanel = new JPanel();
bottomPanel = new JPanel();
Draw d = new Draw();
getContentPane().add(d, BorderLayout.CENTER); //This works
add(topPanel, BorderLayout.PAGE_START);
add(bottomPanel, BorderLayout.PAGE_END);
/* I WANT THIS TO WORK INSTEAD */
/* centerPanel.add(d); */ //How can I write this line of code?
/* add(topPanel, BorderLayout.PAGE_START); */
/* add(centerPanel, BorderLayout.CENTER); */
/* add(bottomPanel, BorderLayout.PAGE_END); */
Class Draw:
public class FreeHand extends JComponent, MouseListener, MouseMotionListener {
int x;
int y;
int posX;
int posY;
public FreeHand()
{
addMouseListener(this);
addMouseMotionListener(this);
}
@Override
public void mousePressed(MouseEvent me) {
posX = me.getX();
posY = me.getY();
}
@Override
public void mouseDragged(MouseEvent me) {
Graphics g = getGraphics();
g.setColor(Color.RED);
g.drawLine(posX, posY, me.getX(), me.getY());
posX = me.getX();
posY = me.getY();
}
@Override
public void mouseMoved(MouseEvent me) {}
@Override
public void mouseClicked(MouseEvent me) {}
@Override
public void mouseEntered(MouseEvent me) {}
@Override
public void mouseExited(MouseEvent me) {}
@Override
public void mouseReleased(MouseEvent me) {}
}