62,614
社区成员
发帖
与我相关
我的任务
分享
import javax.swing.*;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(400, 300);
frame.setContentPane(new ImagePanel("Winter.jpg"));
frame.setVisible(true);
}
}
import java.awt.*;
import javax.swing.*;
public class ImagePanel extends JPanel {
private String imgPath;
public ImagePanel(String imgPath) {
this.imgPath = imgPath;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(new ImageIcon(imgPath).getImage(), 0, 0, getWidth(), getHeight(), null);
}
}
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
class ImgLabel extends JLabel {
BufferedImage image,model,dest,img;
Graphics2D destG,modelG;
int posx=0,posy=0;
public ImgLabel(BufferedImage im) throws IOException {
super();
this.init(im);
}
public void init(BufferedImage im) throws IOException {
this.image = im;
dest = new BufferedImage(im.getWidth(), im.getHeight(), BufferedImage.TYPE_INT_ARGB);
this.destG = dest.createGraphics();
this.model = new BufferedImage(im.getWidth(), im.getHeight(), BufferedImage.TYPE_INT_ARGB);
this.modelG = model.createGraphics();
limpaImagem(this.model);
img = ImageIO.read(new File("图片2的路径"));
montaImagemSobreposta();
this.setIcon(new ImageIcon(dest));
}
public void limpaImagem(BufferedImage im) {
Graphics2D g2d = im.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0,0,im.getWidth(),im.getHeight());
}
private void montaImagemSobreposta() {
destG.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f));
destG.drawImage(this.image, 0, 0, null);
destG.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
destG.drawImage(this.img, posx, posy, null);
//System.out.println(posx+" "+posy);
}
public void paintComponent(Graphics g) {
montaImagemSobreposta();
g.drawImage(dest, 0, 0, null);
}
public void mouseDragged(MouseEvent e) {
posx = e.getX();
posy = e.getY();
this.repaint();
}
}
public class Frame1 extends JFrame{
JPanel pane1 = new JPanel();
ImgLabel lab3 = null;
Frame1() throws IOException{
BufferedImage img = null;
try{
img = ImageIO.read(new File("图片1的路径"));
}
catch(IOException e){
e.printStackTrace();
}
lab3 = new ImgLabel(img);
pane1.setLayout(new BorderLayout());
pane1.add(lab3,BorderLayout.CENTER);
pane1.addMouseMotionListener(new MouseAdapter(){
public void mouseDragged(MouseEvent e) {
lab3.mouseDragged(e);
}
});
this.add(pane1);
this.setSize(300,300);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) throws IOException{
Frame1 obj = new Frame1();
}
}