// RJC.java - Rotate Component Image and Text
// Compiled and tested under
// NT 4.0, SP5, JDK: Sun 1.2.2
// Joe Sam Shirah   jshirah@ibm.net
// Autumn Software

import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;


public class RJC extends JPanel
                 implements ActionListener,
                            WindowListener
{
  double dPIMult = ( java.lang.Math.PI / 180 );

  int rotation;
  JFrame jf;
  JTextField jtf;

  public RJC( JFrame jfM, JTextField jtfM )
  {
    rotation = 0;

    jf  = jfM;
    jtf = jtfM;
    jtf.addActionListener( this );

  } // end constructor


  public void setRotation(int degrees)
  {
    rotation = degrees;
    repaint();
  }  // end setRotation


  public void paint(Graphics g)
  {
    super.paint( g );

    double dRadians = 0;
    Graphics2D g2d = (Graphics2D)g.create();

    g2d.translate( getWidth() >> 1, getHeight() >> 1 );

    if(rotation != 0)
    {
      dRadians = ( rotation *  dPIMult );
      g2d.rotate( dRadians );
    }
    Caret cjtf = jtf.getCaret();
    cjtf.setVisible( false );
    jtf.update( g2d );  // send our Graphics
    cjtf.setVisible( true );

    g2d.setFont( jtf.getFont() );  // use TextComponent Font
    g2d.setColor( Color.red.darker() );
    g2d.drawString( "Text is " + jtf.getText() + ".",
                     10, jtf.getHeight() + 20 );

    if(rotation != 0) { g2d.rotate( -(dRadians) ); }

    g2d.translate( 0, 0 );
    g2d.dispose();

  } // end paint


  public void actionPerformed(ActionEvent e)
  {
//This will work for any JTextComponent
    setRotation( Integer.parseInt(
                 ((JTextComponent)e.getSource()).getText() ) );
  } // end actionPerformed


// Window Listener Implementation
    public void windowOpened(WindowEvent e) {}
     public void windowClosing(WindowEvent e)
     {
       jf.dispose();
       System.exit(0);
     }
    public void windowClosed(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowActivated(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}
// End Window Listener Implementation


  public static void main(String[] args)
  {
    Container cp;
    JFrame jfM;
    JLabel jlM;
    JPanel jpM;
    JTextField jtfM;

    jfM = new JFrame("Rotate Data");
    jpM = new JPanel();
    jlM = new JLabel("Key Degrees, Press Enter/Return");
    jtfM = new JTextField( "0", 10 );
    jpM.add( jlM );
    jpM.add( jtfM );

    RJC rjc = new RJC( jfM, jtfM );

    cp = jfM.getContentPane();
    cp.add( jpM, BorderLayout.NORTH );
    cp.add( rjc, BorderLayout.CENTER );
    jfM.addWindowListener( rjc );
    jfM.pack();

    int jtfMW = jtfM.getWidth();
    jfM.setSize( jfM.getWidth(), (jtfMW << 1) + jtfMW );
    jfM.show();

  } // end main

} // end class RJC
