简体   繁体   English

如何创建将响应鼠标单击的Java swing图形对象?

[英]How to create java swing Graphic object which will response to mouse clicks?

I need to draw graphic element (square) dynamically in different positions of Canvas and I need to listen to mouse clicks in order to change place of my square. 我需要在“画布”的不同位置动态绘制图形元素(正方形),并且需要听鼠标单击以更改正方形的位置。 How to add mouse listener to Graphics object? 如何将鼠标侦听器添加到Graphics对象? Do I have to use another approach? 我是否必须使用另一种方法?

int x = 0;
int y = 0;
 Graphics g = getGraphics(); // get Graphics context
                  g.setColor(Color.red);
          g.fillRect( x - 25, y - 15, 60, 30 );
          g.setColor(Color.black);
          g.drawRect( x - 25, y - 15, 60, 30 );
                  g.dispose();

I'd probably use a JPanel as a child element of your larger component that forms the canvas. 我可能会使用JPanel作为构成画布的较大组件的子元素。 A JPanel, since it is a subclass of JComponent, allows you both to add a mouse listener via addMouseListener() , and to override its paintComponent () method. 由于JPanel是JComponent的子类,因此它既可以通过addMouseListener()添加鼠标侦听器,也可以覆盖其paintComponent ()方法。

If you want to move the square, just reposition the JPanel. 如果要移动正方形,只需重新定位JPanel。

(for that matter, if it's a square or rectangle, you don't even need to override paintComponent, you could just accomplish this with appropriate calls to setBorder and setBackground.) (为此,如果它是正方形或矩形,则您甚至不需要覆盖paintComponent,只需对setBorder和setBackground进行适当的调用即可完成此操作。)


Another approach would be to use a JPanel as the entire canvas, override the paintComponent to draw whatever you like, addMouseListener on the JPanel, and then manually determine whether the mouse listener events occur within the geometry of your graphic element. 另一种方法是使用JPanel作为整个画布,覆盖paintComponent以绘制所需的内容,在JPanel上添加addMouseListener,然后手动确定鼠标侦听器事件是否在图形元素的几何内发生。

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

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