2012-12-03 2 views
2

해결 : 나는 g2.scale(1, -1); 감사합니다 ^^뒤집기 모양 (안 이미지)


내가 거울 (수직 플립)와 디지털 시계를 표시하는 프로그램을 작성

으로 g2.rotate(Math.toRadians(180.0));을 대체 @MadProgrammer

감사합니다

이것은 내 코드입니다.

import java.awt.*; 
    import java.awt.font.GlyphVector; 
    import javax.swing.*; 
    import java.util.*; 

    public class DigitalClock extends JFrame implements Runnable { 
     /** 
     * @author HASSAN 
     */ 
     Thread runner; // declare global objects 
     Font clockFont; 
     Shape mirror; 

     public DigitalClock() { 
      super("Digital Clock - Hassan Sharaf 12MCMB33"); 
      setSize(600, 500); 
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      setVisible(true); 
      setResizable(false); // create window 
      setLocationRelativeTo(null); 
      clockFont = new Font("digifacewide", Font.BOLD, 100); // create font 

      Container contentArea = getContentPane(); 
      ClockPanel timeDisplay = new ClockPanel(); 
      contentArea.add(timeDisplay); // add components 
      setContentPane(contentArea); 
      start(); // start thread running 
     } 

     public class ClockPanel extends JPanel { 

      public void paintComponent(Graphics painter) { 
       // super.paintComponent(painter); 
       Graphics2D g2 = (Graphics2D) painter; 
       g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
       g2.setFont(clockFont); // create clock components 
       g2.setColor(Color.black); 
       g2.drawString(timeNow(), 20, 140); 
       GlyphVector v = clockFont.createGlyphVector(getFontMetrics(clockFont).getFontRenderContext(), timeNow()); 
       mirror = v.getOutline(); 
       g2.translate(553, 160); 
       g2.rotate(Math.toRadians(180.0)); 
       g2.fill(mirror); 
         g2.draw(mirror); 

      } 
     } 

     // get current time 
     public String timeNow() { 
      Calendar now = Calendar.getInstance(); 
      int hrs = now.get(Calendar.HOUR_OF_DAY); 
      int min = now.get(Calendar.MINUTE); 
      int sec = now.get(Calendar.SECOND); 
      String time = zero(hrs) + ":" + zero(min) + ":" + zero(sec); 
      return time; 
     } 

     public String zero(int num) { 
      String number = (num < 10) ? ("0" + num) : ("" + num); 
      return number; // Add leading zero if needed 
     } 

     public void start() { 
      if (runner == null) { 
       runner = new Thread(this); 
      } 
      runner.start(); 
      // method to start thread 
     } 

     public void run() { 
      while (runner == Thread.currentThread()) { 
       repaint(); 
       // define thread task 
       try { 
        Thread.sleep(1000); 
       } catch (InterruptedException e) { 
        System.out.println("Thread failed"); 
       } 
      } 
     } 

     // create main method 
     public static void main(String[] args) { 
      DigitalClock clock = new DigitalClock(); 
     } 
    } 

문제: 내가 회전() 메소드를 사용하지만 실제로 내가 원하는 시계를 뒤집어 회전하지 않으려는 수직 질문 :가 어떻게 모양 (안 이미지)를 전환 할 수 있습니다?

답변

3

당신은

당신은 할 수 ...

  • AffineTransform 일치하는 당신의 회전을 사용하여 모양 개체에서 PathIterator 만들기 ... 많은 - 오 - 선택은 당신이 달성하려는 작업에 따라이 요구 사항. 이렇게하면 PathIterator을 추가하여 페인트 할 수 있습니다. 또는
  • 새 경로의 기준으로 회전 할 모양을 사용하고 AffineTransform을 전달하여 새 Path2D을 만듭니다. . 이 여기

는 예를 들어 .... 모두 당신이 원하는 경우

public class SpinningTriangle { 

    public static void main(String[] args) { 
     new SpinningTriangle(); 
    } 

    public SpinningTriangle() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       JFrame frame = new JFrame(); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(new SpinPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class SpinPane extends JPanel { 

     private Triangle triangle; 
     private float angle = 0; 

     public SpinPane() { 
      triangle = new Triangle(50, 100); 
      Timer timer = new Timer(40, new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent e) { 
        angle += 2; 
        repaint(); 
       } 
      }); 
      timer.setRepeats(true); 
      timer.setCoalesce(true); 
      timer.start(); 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(110, 110); 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      Graphics2D g2d = (Graphics2D) g.create(); 
      Rectangle bounds = triangle.getBounds(); 
//   PathIterator pi = triangle.getPathIterator(AffineTransform.getRotateInstance(Math.toRadians(angle), bounds.width/2, bounds.height/2)); 
//   Path2D path = new Path2D.Float(); 
//   path.append(pi, true); 
      Path2D path = new Path2D.Float(triangle, AffineTransform.getRotateInstance(Math.toRadians(angle), bounds.width/2, bounds.height/2)); 
      int x = (getWidth() - bounds.width)/2; 
      int y = (getHeight() - bounds.height)/2; 
      g2d.translate(x, y); 
      g2d.setColor(Color.RED); 
      g2d.fill(path); 
      g2d.setColor(Color.YELLOW); 
      g2d.draw(path); 
      g2d.dispose(); 
     } 

    } 

    public class Triangle extends Path2D.Float { 

     public Triangle(int width, int height) { 

      moveTo(width/2f, 0); 
      lineTo(width, height); 
      lineTo(0, height); 
      closePath(); 

     } 

    } 

} 

업데이트입니다 ... 거의 첫 번째 옵션과 동일하지만, 적은 코드가 필요합니다 do는 "mirror"모양이고, 축의 축척은 -1 ...

public class SpinningTriangle { 

    public static void main(String[] args) { 
     new SpinningTriangle(); 
    } 

    public SpinningTriangle() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       JFrame frame = new JFrame(); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(new FlipPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class FlipPane extends JPanel { 

     private Triangle triangle; 
     private boolean flip; 

     public FlipPane() { 
      triangle = new Triangle(50, 100); 
      Timer timer = new Timer(500, new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent e) { 
        flip = !flip; 
        repaint(); 
       } 
      }); 
      timer.setRepeats(true); 
      timer.setCoalesce(true); 
      timer.start(); 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(110, 110); 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      Graphics2D g2d = (Graphics2D) g.create(); 
      Rectangle bounds = triangle.getBounds(); 

      double scale = 1 * (flip ? -1 : 1); 

      Path2D path = new Path2D.Float(triangle, AffineTransform.getScaleInstance(scale, scale)); 
      int x = (getWidth() - bounds.width)/2; 
      int y = (getHeight() - bounds.height)/2; 
      if (flip) { 

       y += bounds.height; 
       x += bounds.width; 

      } 
      g2d.translate(x, y); 
      g2d.setColor(Color.RED); 
      g2d.fill(path); 
      g2d.setColor(Color.YELLOW); 
      g2d.draw(path); 
      g2d.dispose(); 
     } 

    } 

    public class Triangle extends Path2D.Float { 

     public Triangle(int width, int height) { 

      moveTo(width/2f, 0); 
      lineTo(width, height); 
      lineTo(0, height); 
      closePath(); 

     } 

    } 

} 
+2

비슷한 방법으로 데카르트 좌표 [here] (http://stackoverflow.com/a/9373195/230513). – trashgod