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

时间:2011-12-03 14:02:43

标签: java swing jlabel graphics2d paintcomponent

我无法在具有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);

}
}

1 个答案:

答案 0 :(得分:4)

您需要跟踪要绘制的所有线条。绘画(你可能真的想要paintComponent)在你绘制之前清除图形。

可能的解决方案:

  1. 跟踪所有线条,并且您想在paintComponent中绘制和绘制它们。

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