I have added 2 JComponent to JPanel.Both these JComponent have custom painted objects on them i.e multiple Circles and multiple Line2Ds.The dimensions of both these jcomponent's are set to the size of the screen which is required.When I add them to JPanel,the mouselisteners are not working.However if I comment one of them then that listener starts working.
public class MapXMLBuilder extends JFrame {
public void initialize() {
panel = new Jpanel();
addLine();//ading lines
addCircle();//adding cirlces
add(panel)
}
private void addLine() {
mDrawLine = new DrawLine(panel);
mDrawCircle.setDimensions(screenWidth, screenWidth);
panel.add(mDrawLine); //adding JComponent1 to panel
for (int i = 0; i < 10; i++) { //adding 10 circles
mDrawLine.addLine(new Point2D.Double(x, y));
}
}
private void addCircle() {
mDrawCircle = new DrawCircle(panel);
mDrawCircle.setDimensions(screenWidth, screenWidth);
panel.add(mDrawCircle); //adding JComponent1 to panel
for (int i = 0; i < 10; i++) { //adding 10 circles
mDrawCircle.addCircle(new Point2D.Double(x, y));
}
}
}
public class DrawLine extends JComponent {
public DrawLine(JPanel jpanel) {
lineList = new ArrayList();
addMouseListener(mouseAdapter);
addMouseMotionListener(mouseAdapter);
setBackground(Color.white);
}
public void addLine(int x1, int y1, int x2, int y2, Color color) {
Shape currentShape = new Line2D.Float(x1, y1, x2, y2);
lineList.add(currentShape);
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(Color.BLACK);
for (Shape shape: lineList) {
if (shapes != null && shapes.size() > 0) {
g2d.setColor(Color.YELLOW);
g2d.draw(shape);
}
}
}
public void setDimensions(int width, int height) {
setSize(new Dimension(width, height));
}
}
public class DrawCircle extends JComponent {
public DrawCircle(JPanel jpanel) {
circleList = new ArrayList();
addMouseListener(mouseAdapter);
addMouseMotionListener(mouseAdapter);
setBackground(Color.white);
}
public void addCircle(Point2D p) {
Ellipse2D e = new Ellipse2D.Double(p.getX(), p.getY(), 5, 5);
circleList.add(e);
selectedPoint = null;
repaint();
}
public void setDimensions(int width, int height) {
setSize(new Dimension(width, height));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
int diameter = 75;
Ellipse2D e;
Color color;
for (int j = 0; j < circleList.size(); j++) {
e = (Ellipse2D) circleList.get(j);
float alpha = 0.75f;
color = new Color(1, 0, 0, alpha); //Red
g2.setPaint(color);
Ellipse2D.Double circle = new Ellipse2D.Double(e.getX(), e.getY(), diameter, diameter);
g2.fill(circle);
}
}
}