简体   繁体   English

Java Swing中的交互式组件

[英]interactive component in Java Swing

I'm required to implement a map in Java Swing, which is connected with a spatial database to handle some queries. 我需要在Java Swing中实现地图,该地图与空间数据库连接以处理一些查询。 I used a jLabel to represent the map image. 我使用jLabel表示地图图像。

I need to drag an area and return all the possible elements within that area. 我需要拖动一个区域并返回该区域内的所有可能元素。 Each return element should be shown on the map as yellow triangle or red circle and these polygons could be clicked to provide further information on somewhere else. 每个返回元素应在地图上显示为黄色三角形或红色圆圈,并且可以单击这些多边形以在其他位置提供更多信息。

Here is my confusion. 这是我的困惑。 Which component should I use to demonstrate the element on the image? 我应该使用哪个组件来演示图像上的元素? It need to be interactive so intuitively I choose JButton , here is my implementation: 它需要是交互式的,所以我直观地选择JButton ,这是我的实现:

    Iterator<JGeometry> it = al.iterator();
    while (it.hasNext()) {
        JButton jButton1 = new JButton();
        jButton1.setText("213");
        jButton1.setBounds(325 + (int)it.next().getPoint()[0], 70 + (int)it.next().getPoint()[1], 30,30);
        jButton1.setVisible(true);
        getContentPane().add(jButton1);
    }

But it doesn't show any button on the panel. 但是它在面板上没有显示任何按钮。 I suppose both the jButton and the jLabel containing the image are on the same level, so there may be some overlap. 我假设包含图像的jButton和jLabel处于同一级别,因此可能存在一些重叠。 How can I deal with that? 我该如何处理? Is there any better solution for this case? 对于这种情况有更好的解决方案吗?

预期表现

Consider having these elements drawn on a JPanel , which listens for mouse events. 考虑将这些元素绘制在侦听鼠标事件的JPanel上 The user will click and drag, creating a bounded box which you can determine if any of your objects intersect, and get their coordinates. 用户将单击并拖动,创建一个有边界的框,您可以确定该框是否与您的任何对象相交,并获取其坐标。

Here's a demo that can help you get started. 这是一个可以帮助您入门的演示

GraphPanel显示了一种通过单击和拖动来进行多项选择的方法。

This is not directly related to your question, but there's another problem in your code which will trouble you. 这与您的问题没有直接关系,但是您的代码中还有另一个问题会困扰您。

You're calling it.next() twice within the loop. 您在循环中两次调用it.next() Each call to next() will move the iterator on by one element, so the first object you get will not be the same as the second one. 每次对next()调用都将使迭代器移动一个元素,因此您获得的第一个对象将与第二个对象不同。 So, not only will your results be wrong, but you'll end up with an exception if the number of elements in al is odd (because you take two elements at a time). 因此,不仅您的结果是错误的,而且如果al的元素数量为奇数(因为一次要使用两个元素),您将最终遇到异常。 Instead, you should only call next() once and assign the value to a local variable, or use the Java 6 for-loop syntax: 相反,您只应调用next()并将该值分配给局部变量,或使用Java 6 for循环语法:

for(JGeometry geom : al) {
    ...
    jButton1.setBounds(325 + (int)geom.getPoint()[0], 70 + (int)geom.getPoint()[1], 30, 30);
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM