0

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

}
}

图形界面类

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);

}
}
4

1 回答 1

4

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

可能的解决方案:

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

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

于 2011-12-03T14:08:57.283 回答