简体   繁体   中英

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. I used a jLabel to represent the map image.

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:

    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. 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. 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. 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. 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). Instead, you should only call next() once and assign the value to a local variable, or use the Java 6 for-loop syntax:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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