簡體   English   中英

如何在Java中旋轉矩形?

[英]How can I rotate rectangle in Java?

我的矩形代碼:

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

我有一個按鈕“旋轉”。 當用戶用鼠標按下按鈕時,矩形必須旋轉15度。

這是我的動作代碼:

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

但是代碼不起作用。 不知道為什么 你怎么看?

我的編輯操作代碼部分:

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. 通過覆蓋paintComponent()方法而不是paint()來完成自定義繪制。 開始時不要忘記super.paintComponent()。

  2. paintComponent()方法是完成繪制的地方,因此您需要旋轉代碼。 因此,您可以設置一個變量來指示是否需要旋轉。 因此, ActionListener所做的全部工作就是設置變量,然后調用repaint()。

或者,我從未嘗試將旋轉直接應用於Rectangle(我一直將其應用於繪畫方法中的Graphics對象)。 也許您只需要在ActionListener的面板上調用repaint() 面板不知道您已更改矩形,因此您需要告訴它重新繪制自身。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM