Search code examples
javaswingjava-2daffinetransform

problems with AffineTransform


Hello I am new to affineTransform in java. I want to use it to shear some GUI I have to use later. For now I just wanted to test a sample code but i cannot explain its output. Here is the code

    package main;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.AffineTransform;

    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JPanel;

    public class MainClass{
    public static void main(String[] args) {
    JFrame jf = new JFrame("Demo");

    jf.getContentPane().add(new MyCanvas());

    jf.setSize(600, 600);
    jf.setVisible(true);
  }
}

    class Left extends JPanel {

    Left(){
        setPreferredSize(new Dimension(450,450));
        setBorder(BorderFactory.createLineBorder(Color.green));
        setBackground(Color.gray);

    }


      public void paintComponent(Graphics g) {

            super.paintComponent(g);

            Graphics2D g2 = (Graphics2D) g;

            AffineTransform at = new AffineTransform();

            g2.setTransform(at);

            g2.drawRect(getWidth()/2 - 10, getHeight()/2 - 10, 20, 20);

          }
}

    class MyCanvas extends JPanel {

    MyCanvas()
    {
        setBorder(BorderFactory.createLineBorder(Color.red));
        setLayout(new FlowLayout(FlowLayout.CENTER));
        add(new Left());
    }


}

The rectangle I want to draw in the Left class show appear in the center right?? But its coming shifted to left.. It seems its taking its coordinates with relative to the outer frame. If I remove the g2.setTransform(at); it comes normal.. Can you explain me why??


Solution

  • I know where is you problem, you draw on same graphics as parent. "super.paintComponent(g);"

    you should try something like super.repaint();