简体   繁体   English

如何在Java中旋转矩形?

[英]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. 当用户用鼠标按下按钮时,矩形必须旋转15度。

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(). 通过覆盖paintComponent()方法而不是paint()来完成自定义绘制。 Don't forget the super.paintComponent() at the start. 开始时不要忘记super.paintComponent()。

  2. The paintComponent() method is where the painting is done so that is were you need the rotation code. paintComponent()方法是完成绘制的地方,因此您需要旋转代码。 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(). 因此, ActionListener所做的全部工作就是设置变量,然后调用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). 或者,我从未尝试将旋转直接应用于Rectangle(我一直将其应用于绘画方法中的Graphics对象)。 Maybe you just need to invoke repaint() on the panel in your ActionListener . 也许您只需要在ActionListener的面板上调用repaint() The panel won't know you've changed the Rectangle, so you need to tell it to repaint itself. 面板不知道您已更改矩形,因此您需要告诉它重新绘制自身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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