0

My rectangle code:

class Rectangle extends JPanel {

 int x = 105;
 int y= 100;
 int width = 50;
 int height = 100;


  public void paint(Graphics g) {
    g.drawRect (x, y, width, height);  
    g.setColor(Color.WHITE);
  }


Rectangle r = new Rectangle();

and I have a button "rotate". When the user presses the button with the mouse, the rectangle must rotate 15 degrees.

This is my action code:

public void actionPerformed(ActionEvent e){
    Object source  = e.getSource();

    if( source == rotate){
        AffineTransform transform = new AffineTransform();
        transform.rotate(Math.toRadians(15), r.getX() + r.getWidth()/2, r.getY() + height/2);
        r.add(transform);
    }
}

But the code doesn't work. I don't know why? What do you think?

My edited-action-code part:

public void actionPerformed(ActionEvent e){
        Object source  = e.getSource();

        if( source == rotate){

            Paint p = new Paint();              
            panel1.add(r);
             repaint();
        }
        }

    class Paint extends JPanel {
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;

        g2d.setColor(Color.WHITE);
        g2d.translate(r.getX()+(r.WIDTH/2), r.getY()+(r.HEIGHT/2));
        g2d.rotate(Math.toRadians(15));
        r.equals(g2d);
        repaint();
    }
}
Dimitar
  • 4,402
  • 4
  • 31
  • 47
imogen
  • 13
  • 1
  • 4

1 Answers1

3
  1. Custom painting is done by overriding the paintComponent() method, not paint(). Don't forget the super.paintComponent() at the start.

  2. The paintComponent() method is where the painting is done so that is were you need the rotation code. So you could set a variable to indicate if you need to do the rotation or not. So all the ActionListener does is set the variable and then invoke repaint().

Or, I've never tried applying a rotation directly to the Rectangle (I've always applied it to the Graphics object in the painting method). Maybe you just need to invoke repaint() on the panel in your ActionListener. The panel won't know you've changed the Rectangle, so you need to tell it to repaint itself.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • When i do like in this link http://stackoverflow.com/questions/7517688/rotate-a-java-graphics2d-rectangle action part doesnt work. How can i work it? – imogen Nov 29 '15 at 11:59
  • @Imogen, I have no idea why your code doesn't work since you didn't post your code. Post a proper [SSCCE](http://sscce.org/) that demonstrates the problem. – camickr Nov 29 '15 at 18:58
  • yes you right, i am sorry but i dont know how can i put my code in here the comment part :( – imogen Nov 29 '15 at 19:19
  • @Imogen, I can't compile or execute that code. You didn't read the `SSCCE` link. – camickr Nov 29 '15 at 20:08