【发布时间】:2015-12-21 13:42:18
【问题描述】:
我已将 2 个 JComponent 添加到 JPanel。这两个 JComponent 上都有自定义绘制的对象,即多个 Circles 和多个 Line2D。这两个 jcomponent 的尺寸都设置为所需的屏幕大小。当我将它们添加到JPanel,鼠标监听器不起作用。但是,如果我评论其中一个,那么该监听器就会开始工作。
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);
}
}
}
【问题讨论】:
-
如果它们都占据了整个屏幕并且必须彼此重叠并且必须添加到同一个组件中,那么它们真的需要是单独的组件吗?
-
subpanels.setOpaque(false) ?
-
问题是为什么?为什么不将绘画功能合并到一个组件中
-
有 Line2ds 和 circle.they 都实现了 mouselisteners。如果一个形状被移动,与之关联的属性也会发生变化,并且它们都有不同的属性集。因此,我觉得将它们分开,否则我将不得不花费大量时间来确定移动的内容,因为有时形状可能会重叠。此外,如果明天在屏幕上添加更多形状会怎样。我猜代码会变得太复杂。
-
发布MCVE。请务必将您的代码复制粘贴到新项目,并确保在将其发布到此处之前编译并运行。
标签: java swing jpanel jcomponent border-layout