简体   繁体   中英

How can I rotate rectangle in Java?

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();
    }
}
  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM