我有一个JLayeredPane。在那我放置了几个组件。这些组件是扩展jPanel的类。所有组件都放在相同的深度层中。每个组件可以具有或不具有完全/部分在其上方/下方的其他组件/组件。当我点击组件时,单击最顶部。
如何在我点击的位置检查topomost下面是否还有更多组件?如何将click事件“传递”到下面的那些组件之一或其中的许多组件?
编辑:一个工作示例
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.*;
public class JavaJLayeredPane {
JFrame frame;
JLayeredPane layeredPane;
JPanel Panel1;
JPanel panel;
public void createUI()
{
frame = new JFrame("Items one ove the other");
frame.setPreferredSize(new Dimension(600, 400));
frame.setLayout(new BorderLayout());
layeredPane = new JLayeredPane();
frame.add(layeredPane, BorderLayout.CENTER);
layeredPane.setBounds(0, 0, 600, 400);
ArrayList<Color> colorList = new ArrayList<Color>();
colorList.add(Color.red);
colorList.add(Color.yellow);
colorList.add(Color.blue);
colorList.add(Color.green);
colorList.add(Color.cyan);
for (int i=0; i<5; i++){
String mytext="no"+ i;
Panel1 = new myarea(mytext);
Panel1.setBackground(colorList.get(i));
if (i==0){Panel1.setBounds(210, 110, 20, 20);}
if (i==1){Panel1.setBounds(200, 100, 150, 150);}
if (i==2){Panel1.setBounds(250, 110, 170, 120);}
if (i==3){Panel1.setBounds(180, 130, 110, 110);}
if (i==4){Panel1.setBounds(450, 150, 50, 50);}
layeredPane.add(Panel1, new Integer(0), 0);
}
panel = new JPanel();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
JavaJLayeredPane overlapPane = new JavaJLayeredPane();
overlapPane.createUI();
}
public class myarea extends JPanel implements MouseListener{
public String areaname;
public myarea(String myname) {
addMouseListener(this);
areaname=myname;
}
//LISTENERS
@Override
public void mousePressed(MouseEvent evt){
}
@Override
public void mouseReleased(MouseEvent evt){
}
@Override
public void mouseClicked(MouseEvent evt){
if(evt.getButton() == MouseEvent.BUTTON1){
JOptionPane.showMessageDialog(null,areaname ) ;
}
}
@Override
public void mouseEntered(MouseEvent evt){
}
@Override
public void mouseExited(MouseEvent evt){
}
}
}
如果我们点击另一个住所的矩形,我们就会得到它的名字。我们如何检查下面是否有另一个矩形,如果是,我们如何获得它的属性?
答案 0 :(得分:3)
基本上有两个任务:
JLayeredPane api帮助第一个,而Component有一个方法来做第二个 - 唯一需要注意的是坐标转换,其中SwingUtilities的帮助方法发挥作用
@Override
public void mouseClicked(MouseEvent evt) {
if (!SwingUtilities.isLeftMouseButton(evt)) return;
Component[] siblings = layeredPane.getComponentsInLayer(JLayeredPane.getLayer(this));
int pos = layeredPane.getPosition(this);
for (Component sibling : siblings) {
// interested in siblings below
if (layeredPane.getPosition(sibling) > pos) {
// convert coordinates
Point p = SwingUtilities.convertPoint(this, evt.getX(), evt.getY(), sibling);
if (sibling.contains(p)) {
// convert event
MouseEvent dispatch = SwingUtilities.convertMouseEvent(
this, evt, sibling);
// manually dispatch the event
sibling.dispatchEvent(dispatch);
break;
}
}
}
// do my own work
System.out.println(getName() + evt);
}