gpt4 book ai didi

java - 单击鼠标时如何使形状出现在图像顶部?

转载 作者:行者123 更新时间:2023-12-04 06:07:22 24 4
gpt4 key购买 nike

我的目标是单击鼠标时出现矩形。
这是我当前代码的片段:

    try{
image = ImageIO.read(file);
g.setColor(new Color(255,0,0));
g.drawRect(x, y, 100, 100);
}

icon = new ImageIcon(image);
label = new JLabel(icon);
label.addMouseListener(this);

public void mouseReleased(MouseEvent event) {
// TODO Auto-generated method stub

if(event.getSource() == label){

x = event.getX();
y = event.getY();

repaint();

input = JOptionPane.showInputDialog("Something:");
System.out.println(input);
}
}

最佳答案

您可以扩展 JPanel 以完全执行您想要的操作:

class MyPanel extends JPanel{
//....
private java.awt.Rectangle rectangle = null;
private Image imageToDraw;
private Point imageLocation;
public setImageToDraw(Image toDraw,Point p){
imageToDraw=toDraw;
imageLocation = p;
}
public void setRectangle(java.awt.Rectangle rectangle overlayRect){
rectangle = overlayRect;
}
// Override paintComponent to draw image and rectangle
@Override
public void paintComponent(Graphics g) {
g.drawImage(imageToDraw,imageLocation.getX(),imageLocation.getY(),this);
if(rectangle != null) {
// Draw your rectangle here...
}
}
}

在鼠标监听器中,执行以下操作:
// Declare a field of type MyPanel
private MyPanel drawingPanel = new MyPanel
// ... Initialization stuff...
drawingPanel.setImageToDraw(toDraw,p);
public void mouseReleased(MouseEvent event) {
// TODO Auto-generated method stub
if(event.getSource() == label){
// Compute rectangle boundaries
drawingPanel.setRectangle(overlayRect);
}
drawingPanel.repaint();
}

基本上,一个 MyPanel对象将始终具有要绘制的图像集。这样,图像一直在面板上绘制。当你想要一个叠加矩形时,你所要做的就是设置 MyPanel.rectangle字段并刷新您的 MyPanel实例。这将首先重绘图像,然后在图像顶部绘制叠加矩形。

关于java - 单击鼠标时如何使形状出现在图像顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8200943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com