且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用paintComponent镜像JFrame中的对象

更新时间:2023-12-05 18:07:46

  Box box = new Box(BoxLayout.X_AXIS); 
BufferedImage image = ImageIO.read(
new URL(http://sstatic.net/***/img/logo.png));
AffineTransform xfrm1 = new AffineTransform();
xfrm1.scale(1,1);
box.add(new ImageView(image,xfrm1));
AffineTransform xfrm2 = new AffineTransform();
xfrm2.scale(-1,1);
box.add(new ImageView(image,xfrm2));


I created a class which is a "mirror" object. The class constructor has mirrors coordinates and direction. In this class also there is a paintComponent method. I am trying to create a mirror object with this class in my frame and automatically paint a mirror with coordinates and direction. There is the "mirror" class. Can I do this like that?

import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JComponent;

@SuppressWarnings("serial")
    class Mirror extends JComponent{

        public static int xm, ym;
        public static boolean direction;

        public Mirror(int xmm, int ymm, boolean directionm){

            xm=xmm;
            ym=ymm;
            direction=directionm;;
            repaint();
        }

        public int getX(){
            return xm;
        }

        public int getY(){
            return ym;
        }

        public boolean getDirection(){
            return direction;
        }

        public int getIntDirection(){
            int a;

            if(direction==true){
                a=1;
            }else{
                a=0;
            }

            return a;
        }

        public void setDirection(boolean status){
            direction=status;
        }

        @Override
        public void paintComponent(Graphics g){
            super.paintComponent(g);

            switch(getIntDirection()){
            case 0: ImageIcon mirrorr = new ImageIcon("imagess/mirrorrigt.jpg");
                    Image mirrorrImage = mirrorr.getImage();
                    g.drawImage(mirrorrImage,xm,ym,null);
                    break;
            case 1: ImageIcon mirrorl = new ImageIcon("imagess/mirrorleft.jpg");
                    Image mirrorlImage = mirrorl.getImage();
                    g.drawImage(mirrorlImage,xm,ym,null);
                    break;
            }
        }
    }

As shown here, you can invert rendering with respect to an axis by applying a suitable AffineTransform to the graphics context. In this example, you could apply a scale(1.0, 1.0) to the left and scale(-1.0, 1.0) to the right to get a mirror effect.

Box box = new Box(BoxLayout.X_AXIS);
BufferedImage image = ImageIO.read(
    new URL("http://sstatic.net/***/img/logo.png"));
AffineTransform xfrm1 = new AffineTransform();
xfrm1.scale(1, 1);
box.add(new ImageView(image, xfrm1));
AffineTransform xfrm2 = new AffineTransform();
xfrm2.scale(-1, 1);
box.add(new ImageView(image, xfrm2));