这个是画在JPanel上的
本例背景更换时,不能更新的,
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
public class Hufan extends JFrame implements ActionListener{
HuPanel hp;
static Hufan hu;
int x,y,w,h;
Timer tt=new Timer(10,this);
public static void main(String[] args) {
hu=new Hufan();
}
public Hufan(){
hp=new HuPanel();
this.add(hp);
tt.start();
this.setSize(400, 300);
this.setLocation(400, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void actionPerformed(ActionEvent arg0) {
x=this.getLocationOnScreen().x;
y=this.getLocationOnScreen().y;
w=this.getWidth();
h=this.getHeight();
hp.setPoint(x,y,w,h);
this.repaint();
}
}
class HuPanel extends JPanel{
BufferedImage img1,img2;
public HuPanel(){
try {
img1=new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
} catch (AWTException e) {
e.printStackTrace();
}
}
public void setPoint(int x,int y,int w,int h){
try {
img2=img1.getSubimage(x, y, w, h);
} catch (Exception e) {
e.printStackTrace();
}
}
public void paint(Graphics g){
super.paint(g);
g.drawImage(img2, 0, -23,null);
}
}
这个是画在JFrame上的
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
public class Hufan extends JFrame implements ActionListener{
BufferedImage img1,img2;
int x,y,w,h;
Timer tt=new Timer(100,this);
public static void main(String[] args) {
new Hufan();
}
public Hufan(){
try {
img1=new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
} catch (AWTException e) {
e.printStackTrace();
}
tt.start();
this.setSize(400, 300);
this.setLocation(400, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void actionPerformed(ActionEvent arg0) {
x=this.getLocationOnScreen().x;
y=this.getLocationOnScreen().y;
w=this.getWidth();
h=this.getHeight();
img2=img1.getSubimage(x, y, w, h);
this.repaint();
}
public void paint(Graphics g){
super.paint(g);
g.drawImage(img2, 0, 0,this);
}
}