gpt4 book ai didi

java - 我无法使用鼠标监听器(例如按下和释放)在 JLabel 中绘制多条线

转载 作者:行者123 更新时间:2023-12-01 19:11:09 24 4
gpt4 key购买 nike

我无法在具有 map 图片的 JLabel 上绘制多条线。我想做的是在 JLabel 内绘制多条线,但似乎每当我单击/绘制新线时,我绘制的旧线都会被删除。换句话说,我想永久保留我所画的每一条线。我感谢您的帮助。这是我的工作代码(分开的主类和 gui 类)。

主类

package MP2;

import java.awt.Color;

import javax.swing.JFrame;

public class Driver {

public static void main(String[]args){

JFrame g = new JFrame();
Gui gui = new Gui();


g.setSize(900,650);

g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
g.add(gui);

g.setVisible(true);

}
}

GUI 类

package MP2;

import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;


public class Gui extends JPanel {

private JLabel mousepanel;
private JLabel statusbar;


int x;
int y;
int xx;
int yy;
;
ArrayList<Shape> shapes = new ArrayList<Shape>();

public Gui(){

setLayout(null);


mousepanel = new JLabel();
mousepanel.setBounds(20,20,500,450);
mousepanel.setIcon(new ImageIcon("C:\\Users\\Dm\\Desktop\\Programs\\Dim\\src\\MP2\\mpmap.png"));

add(mousepanel);

statusbar = new JLabel();
statusbar.setBounds(20, 550, 300, 20);
add(statusbar);


Handlerclass handlerclass = new Handlerclass();
mousepanel.addMouseListener(handlerclass);
mousepanel.addMouseMotionListener(handlerclass);

}

private class Handlerclass implements MouseListener, MouseMotionListener {


public void mouseClicked(MouseEvent e){
statusbar.setText("clicked at "+ e.getX() +" "+ e.getY());


}

public void mousePressed(MouseEvent e){
statusbar.setText("you pressed it at" + e.getX() +" and " + e.getY());
x = e.getX();
y = e.getY();



}
public void mouseReleased(MouseEvent e){
statusbar.setText("you released the mouse at" + e.getX()+ " and "+ e.getY());
xx= e.getX();
yy= e.getY();
validate();
repaint();

}
public void mouseEntered(MouseEvent e){
statusbar.setText("you're at "+e.getX()+" and " +e.getY());
mousepanel.setBackground(Color.red);
}
public void mouseExited(MouseEvent e){
statusbar.setText("....");
mousepanel.setBackground(Color.blue);


}
public void mouseDragged(MouseEvent e){
statusbar.setText("Dragging at" + e.getX() + " and "+ e.getY());

}
public void mouseMoved(MouseEvent e){
statusbar.setText("moving " + "X = "+e.getX() +" Y = "+e.getY());
}



}


public void paint(Graphics g){

super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.MAGENTA );
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN,1f));


g2d.fillOval(x+15, y+14, 10, 10);
g2d.fillOval(xx+15, yy+15, 10, 10);

g.drawLine(x+20,y+20,xx+20,yy+20);

}
}

最佳答案

您需要跟踪所有要绘制的线条。绘制(您可能实际上需要paintComponent)会在您绘制图形之前清除图形。

可能的解决方案:

  1. 跟踪所有想要绘制的线条并在paintComponent中绘制它们。

  2. 创建一个用于绘图的缓冲区,在其上绘制线条,当组件要求重新绘制时,在 PaintComponent 中的图形上绘制缓冲区。

关于java - 我无法使用鼠标监听器(例如按下和释放)在 JLabel 中绘制多条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8368176/

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