JLabel rotation

hi friends..I'm new to this forums and in need of help..
i have a jpanel with jlabel added.
i want to move the location of the jlabel in the panel in an angular manner from a fixed pivot point...from 0 to 90 degrees.
i have tried using jlabel.setlocation method but its setting the location to some abrupt locations..some problem with my trignometric logic..kindly help!..code 'll be highly appriciated..:)
thank you!

private void jLayeredPane2MouseDragged(java.awt.event.MouseEvent evt) {                                          
        // TODO add your handling code here:
        if(clb1.getX()<evt.getX() && (clb1.getX()+clb1.getWidth()>evt.getX()))
            if(clb1.getY()<evt.getY() && (clb1.getY()+clb1.getHeight()>evt.getY()))
                int x=evt.getX();
                //shifting the origin to left bottom
                int y=labelHeight-evt.getY();
                  float theta=Math.atan2(y,x);
                  clb1.setlocation(labelwidth*Math.cos(theta),labelwidth*Math.sin(theta));
            }heres the part of my code..clb1 is my jlabel with a circle imageicon..i want to move this label at 0 to 90 angle
its moving at abrupt locations..:(

Similar Messages

  • Rotate JLabel containing a imgicon

    I want to rotate a jlabel when its clicked. The label is containing a imgicon.
    I have tried to do like
    http://www.codeguru.com/java/articles/199.shtml
    but the label dont rotate, just the image (i think).
    The image image is a vertical filled rectangle, but when i try to click it, it becomes a square...
    The code for adding the ship to the contentpane
    ImageIcon img = new ImageIcon("bigship.gif");
    JLabel jLship =      new JLabel( "ship", img, SwingConstants.LEFT );
    jLship.setName("ship");
    jLship.setBounds(
         ship.getPosition().x * (jlPOpoGame.getWidth() / 11) + 5,
         ship.getPosition().y * (jlPOpoGame.getHeight() / 11) + 5,
         img.getIconWidth(),
         img.getIconHeight());
    getJPOwnGame().add(jLship ,new Integer(1), 0);And the code for changing the label inside a mouselistener.
    selected.setUI(new VerticalLabelUI(true));And the code for the UI:
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.plaf.basic.*;
    class VerticalLabelUI extends BasicLabelUI
         static {
              labelUI = new VerticalLabelUI(false);
         protected boolean clockwise;
         VerticalLabelUI( boolean clockwise )
              super();
              this.clockwise = clockwise;
        public Dimension getPreferredSize(JComponent c)
             Dimension dim = super.getPreferredSize(c);
             return new Dimension( dim.height, dim.width );
        private static Rectangle paintIconR = new Rectangle();
        private static Rectangle paintTextR = new Rectangle();
        private static Rectangle paintViewR = new Rectangle();
        private static Insets paintViewInsets = new Insets(0, 0, 0, 0);
         public void paint(Graphics g, JComponent c)
            JLabel label = (JLabel)c;
            String text = label.getText();
            Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon();
            if ((icon == null) && (text == null)) {
                return;
            FontMetrics fm = g.getFontMetrics();
            paintViewInsets = c.getInsets(paintViewInsets);
            paintViewR.x = paintViewInsets.left;
            paintViewR.y = paintViewInsets.top;
             // Use inverted height & width
            paintViewR.height = c.getWidth() - (paintViewInsets.left + paintViewInsets.right);
            paintViewR.width = c.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);
            paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0;
            paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0;
            String clippedText =
                layoutCL(label, fm, text, icon, paintViewR, paintIconR, paintTextR);
             Graphics2D g2 = (Graphics2D) g;
             AffineTransform tr = g2.getTransform();
             if( clockwise )
                  g2.rotate( Math.PI / 2 );
                  g2.translate( 0, - c.getWidth() );
             else
                  g2.rotate( - Math.PI / 2 );
                  g2.translate( - c.getHeight(), 0 );
             if (icon != null) {
                icon.paintIcon(c, g, paintIconR.x, paintIconR.y);
            if (text != null) {
                int textX = paintTextR.x;
                int textY = paintTextR.y + fm.getAscent();
                if (label.isEnabled()) {
                    paintEnabledText(label, g, clippedText, textX, textY);
                else {
                    paintDisabledText(label, g, clippedText, textX, textY);
             g2.setTransform( tr );
    }Why dont the JLabel rotate?

    I found the error, but one new occured... :(
    I rotate the label with
    selected.setBounds(e.getX(), e.getY(), selected.getHeight(), selected.getWidth());But the rotation works fine only one time, then it gets wrong! Look at
    http://mrserver.pointclark.net/tmp/rotate.jpg
    to how it looks.
    Picture 1: Start position.
    Picture 2: First click, rotate around where i clicked, OK.
    Picture 3: Second click, the image gets cropped! The label is rotated thoug, i can select it and drag it if i click where the image should be.
    Picture 4: Third click. The image is back to horizontal, looks ok!
    And then it switched between 3 and 4 when i continue to click!
    Can somebody help me?

  • Applet Event Handler

    Would someone please help me. I am new to applet development and I get a compile error associated with the event handling in my first ever applet code as follows:
    C:\j2sdk1.4.2_01\bin>javac trajectory_j.java
    trajectory_j.java:248: illegal start of expression
    private class Handler implements ActionListener {
    ^
    trajectory_j.java:248: ';' expected
    private class Handler implements ActionListener {
    ^
    2 errors
    de.
    This is the code:
    // trajectory Analysis Program: trajectory_j.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class trajectory_j extends JApplet implements ActionListener {
         private JTextArea introductionArea, resultsArea;
         private JLabel spanLabel, chordLabel,
              thicknessLabel, massLabel, altitudeLabel, velocityLabel,
              trajectory_angleLabel, time_incrementLabel, rotation_factorLabel,
              calculationLabel, resultsLabel;
         private JTextField spanField, chordField, thicknessField,
              massField, altitudeField, velocityField, trajectory_angleField,
              time_incrementField, rotation_factorField;
         private JButton startButton, resetButton, contButton, termButton;
         String introduction_string, span_string, chord_string, thickness_string, mass_string,
              altitude_string, velocity_string, trajectory_angle_string,
              time_increment_string, rotation_factor_string, results_string;
         double span, chord, thickness, mass, altitude, velocity, trajectory_angle, time_increment,
              rotation_factor, distance, velocity_fps, elapsed_time;
         int status_a;
         int status_b;
         int status_c;
    /* deletion of code segment a
              span = 0;
              chord = 0;
              thickness = 0;
              mass = 0;
              altitude = 0;
              velocity = 0;
              trajectory_angle = 0;
              time_increment = 0;
              rotation_factor = 0;
              distance = 0;
              velocity_fps = 0;
              elapsed_time = 0;
              velocity_fps = 0;
              elapsed_time = 0;
         // create objects
         public void init()
              status_a = 0;
              status_b = 0;
              status_c = 0;
              // create container & panel
              Container container = getContentPane();     
              Panel panel = new Panel( new FlowLayout( FlowLayout.LEFT));
              container.add( panel );
              // set up vertical boxlayout
              Box box = Box.createVerticalBox();
              Box inputbox1 = Box.createHorizontalBox();
              Box inputbox2 = Box.createHorizontalBox();
              Box inputbox3 = Box.createHorizontalBox();
              Box buttonbox = Box.createHorizontalBox();
              introduction_string = "This is the introduction";
              // set up introduction
              introductionArea = new JTextArea( introduction_string, 10, 50 );
              introductionArea.setEditable( false );
              box.add( new JScrollPane( introductionArea ) );
              box.add( Box.createVerticalStrut (10) );
              box.add( inputbox1);
              // set up span
              spanLabel = new JLabel( "span (feet)" );
              spanField = new JTextField(5 );
              inputbox1.add( spanLabel );
              inputbox1.add( spanField );
              Dimension minSize = new Dimension(5, 15);
              Dimension prefSize = new Dimension(5, 15);
              Dimension maxSize = new Dimension(Short.MAX_VALUE, 15);
              inputbox1.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up chord
              chordLabel = new JLabel( "chord (feet)" );
              chordField = new JTextField(5 );
              inputbox1.add( chordLabel );
              inputbox1.add( chordField );
              inputbox1.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up thickness
              thicknessLabel = new JLabel( "thickness (feet)" );
              thicknessField = new JTextField(5 );
              inputbox1.add( thicknessLabel );
              inputbox1.add( thicknessField );
              inputbox1.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up mass
              massLabel = new JLabel( "mass (slugs)" );
              massField = new JTextField(5);
              inputbox1.add( massLabel );
              inputbox1.add( massField );
              box.add( Box.createVerticalStrut (10) );
              box.add( inputbox2);
              // set up altitude
              altitudeLabel = new JLabel( "altitude (feet)");
              altitudeField = new JTextField(5 );
              inputbox2.add( altitudeLabel );
              inputbox2.add( altitudeField );
              inputbox2.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up velocity
              velocityLabel = new JLabel( "velocity (Mach Number)");
              velocityField = new JTextField(5);
              inputbox2.add( velocityLabel );
              inputbox2.add( velocityField );
              inputbox2.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up trajectory_angle
              trajectory_angleLabel = new JLabel( "trajectory angle ( -90 degrees <= trajectory angle <= 90 degrees )");
              trajectory_angleField = new JTextField(5);
              inputbox2.add( trajectory_angleLabel );
              inputbox2.add( trajectory_angleField );
              box.add( Box.createVerticalStrut (10) );
              box.add( inputbox3);
              Dimension minSizeF = new Dimension(70, 15);
              Dimension prefSizeF = new Dimension(70, 15);
              Dimension maxSizeF = new Dimension(Short.MAX_VALUE, 15);
              inputbox3.add(new Box.Filler(minSizeF, prefSizeF, maxSizeF));
              // set up time_increment
              time_incrementLabel = new JLabel( "time increment (seconds)" );
              time_incrementField = new JTextField(5);
              inputbox3.add( time_incrementLabel );
              inputbox3.add( time_incrementField );
              inputbox3.add(new Box.Filler(minSizeF, prefSizeF, maxSizeF));
              // set up rotation_factor
              rotation_factorLabel = new JLabel( "rotation factor ( non-negative number)" );
              rotation_factorField = new JTextField(5);
              inputbox3.add( rotation_factorLabel );
              inputbox3.add( rotation_factorField );
              inputbox3.add(new Box.Filler(minSizeF, prefSizeF, maxSizeF));
              box.add( Box.createVerticalStrut (10) );
              box.add( buttonbox);
              // set up start
              startButton = new JButton( "START" );
              buttonbox.add( startButton );
              Dimension minSizeB = new Dimension(10, 30);
              Dimension prefSizeB = new Dimension(10, 30);
              Dimension maxSizeB = new Dimension(Short.MAX_VALUE, 30);
              buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
              // set up reset
              resetButton = new JButton( "RESET" );
              buttonbox.add( resetButton );
              buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
              // set up cont
              contButton = new JButton( "CONTINUE" );
              buttonbox.add( contButton );
              buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
              // set up term
              termButton = new JButton( "END" );
              buttonbox.add( termButton );
              box.add( Box.createVerticalStrut (10) );          
              // set up results
              resultsArea = new JTextArea( results_string, 10, 50 );
              resultsArea.setEditable( false );
              box.add( new JScrollPane( resultsArea ) );
              // add box to panel
              panel.add( box );
              // register event handlers
              Handler handler = new Handler();
              spanField.addActionListener( handler );
              chordField.addActionListener( handler );          
              thicknessField.addActionListener( handler );
              massField.addActionListener( handler );
              altitudeField.addActionListener( handler );
              velocityField.addActionListener( handler );          
              trajectory_angleField.addActionListener( handler );
              time_incrementField.addActionListener( handler );
              rotation_factorField.addActionListener( handler );
              startButton.addActionListener( handler );
              resetButton.addActionListener( handler );
              contButton.addActionListener( handler );
              termButton.addActionListener( handler );
    // private inner class for event handling
    private class Handler implements ActionListener {
         // process handler events
         public void actionPerformed( ActionEvent event )
              // process resetButton event
              if ( event.getSource() == resetButton )
                   reset();
              // process contButton event
              if ( event.getSource() == contButton )
                   cont();
              // process endButton event
              if ( event.getSource() == termButton )
              // process span event
              if( event.getSource() == spanField ) {
                   span = Double.parseDouble( event.getActionCommand() );
                   spanField.setText( span_string );
                   status_b++;
              // process chord event
              if( event.getSource() == spanField ) {
                   span = Double.parseDouble( event.getActionCommand() );
                   spanField.setText( chord_string );
                   status_b++;     
              // process thickness event
              if( event.getSource() == thicknessField ) {
                   thickness = Double.parseDouble( event.getActionCommand() );
                   spanField.setText( thickness_string );     
                   status_b++;
              // process mass event
              if( event.getSource() == massField ) {
                   mass = Double.parseDouble( event.getActionCommand() );
                   spanField.setText( mass_string );
                   status_b++;     
              // process altitude event
              if( event.getSource() == altitudeField ) {
                   altitude = Double.parseDouble( event.getActionCommand() );
                   spanField.setText( altitude_string );     
                   status_b++;
              // process velocity event
              if( event.getSource() == velocityField ) {
                   velocity = Double.parseDouble( event.getActionCommand() );
                   spanField.setText( velocity_string );
                   status_b++;
              // process trajectory_angle event
              if( event.getSource() == trajectory_angleField ) {
                   trajectory_angle = Double.parseDouble( event.getActionCommand() );
                   spanField.setText( trajectory_angle_string );
                   status_b++;
              // process time_increment event
              if( event.getSource() == time_incrementField ) {
                   time_increment = Double.parseDouble( event.getActionCommand() );
                   spanField.setText( time_increment_string );
                   status_b++;
              // process rotation_factor event
              if( event.getSource() == rotation_factorField ) {
                   rotation_factor = Double.parseDouble( event.getActionCommand() );
                   spanField.setText( rotation_factor_string );
                   status_b++;
              // process startButton event
              if ( event.getSource() == startButton && status_b == 9 ) {
                   status_c = 1;
         } // end method event handler
    } // end Handler class
         } // end method init
         public void strtb()
    /* deletion of code segment 1
              startButton.addActionListener(
                   new ActionListener() {  // anonymous inner class
                        // set text in resultsArea
                        public void actionPerformed( ActionEvent event )
                        if( status_c == 1 ){
                        calculate();
                        results();
                        resultsArea.setText( results() );
    /* deletion of code segment 2                    
                        }// end method actionPerformed1
                   } // end anonymous inner class1
              ); // end call to addActionlistener1
         } // end method strtb
         public void reset()
    /* deletion of code segment 3
              resetButton.addActionListener(
                   new ActionListener() {  // anonymous inner class
                        // set text in resultsArea
                        public void actionPerformed( ActionEvent event )
                        span_string = "";
                        chord_string = "";
                        thickness_string = "";
                        mass_string = "";
                        altitude_string = "";
                        velocity_string = "";
                        trajectory_angle_string = "";
                        time_increment_string = "";
                        rotation_factor_string = "";
                        results_string = "";
                        spanField.setText( span_string );
                        chordField.setText( chord_string );
                        thicknessField.setText( thickness_string );
                        massField.setText( mass_string );
                        altitudeField.setText( altitude_string );
                        velocityField.setText( velocity_string );
                        trajectory_angleField.setText( trajectory_angle_string );
                        time_incrementField.setText( time_increment_string );
                        rotation_factorField.setText( rotation_factor_string );
    resultsArea.setEditable( true );
                        resultsArea.setText( results_string );
    resultsArea.setEditable( false );
                        span = 0;
                        chord = 0;
                        thickness = 0;
                        mass = 0;
                        altitude = 0;
                        velocity = 0;
                        trajectory_angle = 0;
                        time_increment = 0;
                        rotation_factor = 0;
                        distance = 0;
                        velocity_fps = 0;
                        elapsed_time = 0;
    /* deletion of code segment 4               
                        } // end method actionPerformed2
                   } // end anonymous inner class2
              ); // end call to addActionlistener2
         } // end method reset
         public void cont()
         //later
         public void calculate()
         distance = 1;
         altitude = 2;
         trajectory_angle = 3;
         velocity_fps = 4;
         elapsed_time = 5;
         public String results()
         results_string =
         "Distance =\t\t" + distance + " miles\n"
         + "Altitude =\t\t" + altitude + " feet\n"
         + "Trajectory Angle =\t" + trajectory_angle + " degrees\n"
         + "Velocity =\t\t" + velocity_fps + " feet per second\n"
         + "Elapsed Time =\t\t" + elapsed_time + " seconds\n"
         + "\nstatus_a = " + status_a + "\nstatus_b = "
         + status_b + "\nstatus_c = " + status_c;
         return results_string;
    public void start()
    if(status_a == 0 )
    strtb();
    if (status_b == 0)
    reset();
    }// end method start
    } //end class trajectory_a

    The following are copies of html and java source code files for a prior runnable version ( trajectory_b ) of this program which can enlighten some functionality intended by the program.
    (trajectory_b.html):
    <html>
    <appletcode = "trajectory_b.class" width = "800" height = "600">
    </applet>
    </html>
    (trajectory_b.java):
    // trajectory Analysis Program: trajectory_b.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class trajectory_b extends JApplet implements ActionListener {
         private JTextArea introductionArea, resultsArea;
         private JLabel spanLabel, chordLabel,
              thicknessLabel, massLabel, altitudeLabel, velocityLabel,
              trajectory_angleLabel, time_incrementLabel, rotation_factorLabel,
              calculationLabel, resultsLabel;
         private JTextField spanField, chordField, thicknessField,
              massField, altitudeField, velocityField, trajectory_angleField,
              time_incrementField, rotation_factorField;
         private JButton startButton, resetButton, contButton, termButton;
         String introduction_string, span_string, chord_string, thickness_string, mass_string,
              altitude_string, velocity_string, trajectory_angle_string,
              time_increment_string, rotation_factor_string, results_string;
         double span, chord, thickness, mass, altitude, velocity, trajectory_angle, time_increment,
              rotation_factor, distance, velocity_fps, elapsed_time;
         int status_a;
         int status_b;
         int status_c;
    /* deletion of code segment a
              span = 0;
              chord = 0;
              thickness = 0;
              mass = 0;
              altitude = 0;
              velocity = 0;
              trajectory_angle = 0;
              time_increment = 0;
              rotation_factor = 0;
              distance = 0;
              velocity_fps = 0;
              elapsed_time = 0;
              velocity_fps = 0;
              elapsed_time = 0;
         // create objects
         public void init()
              status_a = 0;
              status_b = 0;
              status_c = 0;
              // create container & panel
              Container container = getContentPane();     
              Panel panel = new Panel( new FlowLayout( FlowLayout.LEFT));
              container.add( panel );
              // set up vertical boxlayout
              Box box = Box.createVerticalBox();
              Box inputbox1 = Box.createHorizontalBox();
              Box inputbox2 = Box.createHorizontalBox();
              Box inputbox3 = Box.createHorizontalBox();
              Box buttonbox = Box.createHorizontalBox();
              introduction_string = "This is the introduction";
              // set up introduction
              introductionArea = new JTextArea( introduction_string, 10, 50 );
              introductionArea.setEditable( false );
              box.add( new JScrollPane( introductionArea ) );
              box.add( Box.createVerticalStrut (10) );
              box.add( inputbox1);
              // set up span
              spanLabel = new JLabel( "span (feet)" );
              spanField = new JTextField(5 );
              inputbox1.add( spanLabel );
              inputbox1.add( spanField );
              Dimension minSize = new Dimension(5, 15);
              Dimension prefSize = new Dimension(5, 15);
              Dimension maxSize = new Dimension(Short.MAX_VALUE, 15);
              inputbox1.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up chord
              chordLabel = new JLabel( "chord (feet)" );
              chordField = new JTextField(5 );
              inputbox1.add( chordLabel );
              inputbox1.add( chordField );
              inputbox1.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up thickness
              thicknessLabel = new JLabel( "thickness (feet)" );
              thicknessField = new JTextField(5 );
              inputbox1.add( thicknessLabel );
              inputbox1.add( thicknessField );
              inputbox1.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up mass
              massLabel = new JLabel( "mass (slugs)" );
              massField = new JTextField(5);
              inputbox1.add( massLabel );
              inputbox1.add( massField );
              box.add( Box.createVerticalStrut (10) );
              box.add( inputbox2);
              // set up altitude
              altitudeLabel = new JLabel( "altitude (feet)");
              altitudeField = new JTextField(5 );
              inputbox2.add( altitudeLabel );
              inputbox2.add( altitudeField );
              inputbox2.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up velocity
              velocityLabel = new JLabel( "velocity (Mach Number)");
              velocityField = new JTextField(5);
              inputbox2.add( velocityLabel );
              inputbox2.add( velocityField );
              inputbox2.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up trajectory_angle
              trajectory_angleLabel = new JLabel( "trajectory angle ( -90 degrees <= trajectory angle <= 90 degrees )");
              trajectory_angleField = new JTextField(5);
              inputbox2.add( trajectory_angleLabel );
              inputbox2.add( trajectory_angleField );
              box.add( Box.createVerticalStrut (10) );
              box.add( inputbox3);
              Dimension minSizeF = new Dimension(70, 15);
              Dimension prefSizeF = new Dimension(70, 15);
              Dimension maxSizeF = new Dimension(Short.MAX_VALUE, 15);
              inputbox3.add(new Box.Filler(minSizeF, prefSizeF, maxSizeF));
              // set up time_increment
              time_incrementLabel = new JLabel( "time increment (seconds)" );
              time_incrementField = new JTextField(5);
              inputbox3.add( time_incrementLabel );
              inputbox3.add( time_incrementField );
              inputbox3.add(new Box.Filler(minSizeF, prefSizeF, maxSizeF));
              // set up rotation_factor
              rotation_factorLabel = new JLabel( "rotation factor ( non-negative number)" );
              rotation_factorField = new JTextField(5);
              inputbox3.add( rotation_factorLabel );
              inputbox3.add( rotation_factorField );
              inputbox3.add(new Box.Filler(minSizeF, prefSizeF, maxSizeF));
              box.add( Box.createVerticalStrut (10) );
              box.add( buttonbox);
              // set up start
              startButton = new JButton( "START" );
              buttonbox.add( startButton );
              Dimension minSizeB = new Dimension(10, 30);
              Dimension prefSizeB = new Dimension(10, 30);
              Dimension maxSizeB = new Dimension(Short.MAX_VALUE, 30);
              buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
              // set up reset
              resetButton = new JButton( "RESET" );
              buttonbox.add( resetButton );
              buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
              // set up cont
              contButton = new JButton( "CONTINUE" );
              buttonbox.add( contButton );
              buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
              // set up term
              termButton = new JButton( "END" );
              buttonbox.add( termButton );
              box.add( Box.createVerticalStrut (10) );          
              // set up results
              resultsArea = new JTextArea( results_string, 10, 50 );
              resultsArea.setEditable( false );
              box.add( new JScrollPane( resultsArea ) );
              // add box to panel
              panel.add( box );
              // register event handlers
              Handler handler = new Handler();
              spanField.addActionListener( handler );
              chordField.addActionListener( handler );          
              thicknessField.addActionListener( handler );
              massField.addActionListener( handler );
              altitudeField.addActionListener( handler );
              velocityField.addActionListener( handler );          
              trajectory_angleField.addActionListener( handler );
              time_incrementField.addActionListener( handler );
              rotation_factorField.addActionListener( handler );
              startButton.addActionListener( handler );
              resetButton.addActionListener( handler );
              contButton.addActionListener( handler );
              termButton.addActionListener( handler );
    } // end method init
         // process handler events
         public void actionPerformed( ActionEvent event )
              // process resetButton event
              if ( event.getSource() == resetButton )
                   reset();
              // process contButton event
              if ( event.getSource() == contButton )
                   cont();
              // process endButton event
              if ( event.getSource() == termButton )
              // process span event
              if( event.getSource() == spanField ) {
                   span = Double.parseDouble( event.getActionCommand() );
                   spanField.setText( span_string );
                   status_b++;
              // process chord event
              if( event.getSource() == spanField ) {
                   span = Double.parseDouble( event.getActionCommand() );
                   spanField.setText( chord_string );
                   status_b++;     
              // process thickness event
              if( event.getSource() == thicknessField ) {
                   thickness = Double.parseDouble( event.getActionCommand() );
                   spanField.setText( thickness_string );     
                   status_b++;
              // process mass event
              if( event.getSource() == massField ) {
                   mass = Double.parseDouble( event.getActionCommand() );
                   spanField.setText( mass_string );
                   status_b++;     
              // process altitude event
              if( event.getSource() == altitudeField ) {
                   altitude = Double.parseDouble( event.getActionCommand() );
                   spanField.setText( altitude_string );     
                   status_b++;
              // process velocity event
              if( event.getSource() == velocityField ) {
                   velocity = Double.parseDouble( event.getActionCommand() );
                   spanField.setText( velocity_string );
                   status_b++;
              // process trajectory_angle event
              if( event.getSource() == trajectory_angleField ) {
                   trajectory_angle = Double.parseDouble( event.getActionCommand() );
                   spanField.setText( trajectory_angle_string );
                   status_b++;
              // process time_increment event
              if( event.getSource() == time_incrementField ) {
                   time_increment = Double.parseDouble( event.getActionCommand() );
                   spanField.setText( time_increment_string );
                   status_b++;
              // process rotation_factor event
              if( event.getSource() == rotation_factorField ) {
                   rotation_factor = Double.parseDouble( event.getActionCommand() );
                   spanField.setText( rotation_factor_string );
                   status_b++;
              // process startButton event
              if ( event.getSource() == startButton && status_b == 9 ) {
                   strtb();
         } // end method event handler
         public void strtb()
              startButton.addActionListener(
                   new ActionListener() {  // anonymous inner class
                        // set text in resultsArea
                        public void actionPerformed( ActionEvent event )
                        calculate();
                        results();
                        resultsArea.setText( results() );
                        }// end method actionPerformed1
                   } // end anonymous inner class1
              ); // end call to addActionlistener1
         } // end method strtb
         public void reset()
              resetButton.addActionListener(
                   new ActionListener() {  // anonymous inner class
                        // set text in resultsArea
                        public void actionPerformed( ActionEvent event )
                        span_string = "";
                        chord_string = "";
                        thickness_string = "";
                        mass_string = "";
                        altitude_string = "";
                        velocity_string = "";
                        trajectory_angle_string = "";
                        time_increment_string = "";
                        rotation_factor_string = "";
                        results_string = "";
                        spanField.setText( span_string );
                        chordField.setText( chord_string );
                        thicknessField.setText( thickness_string );
                        massField.setText( mass_string );
                        altitudeField.setText( altitude_string );
                        velocityField.setText( velocity_string );
                        trajectory_angleField.setText( trajectory_angle_string );
                        time_incrementField.setText( time_increment_string );
                        rotation_factorField.setText( rotation_factor_string );
    resultsArea.setEditable( true );
                        resultsArea.setText( results_string );
    resultsArea.setEditable( false );
                        span = 0;
                        chord = 0;
                        thickness = 0;
                        mass = 0;
                        altitude = 0;
                        velocity = 0;
                        trajectory_angle = 0;
                        time_increment = 0;
                        rotation_factor = 0;
                        distance = 0;
                        velocity_fps = 0;
                        elapsed_time = 0;
                        } // end method actionPerformed2
                   } // end anonymous inner class2
              ); // end call to addActionlistener2
         } // end method reset
         public void cont()
         //later
         public void calculate()
         distance = 1;
         altitude = 2;
         trajectory_angle = 3;
         velocity_fps = 4;
         elapsed_time = 5;
         public String results()
         results_string =
         "Distance =\t\t" + distance + " miles\n"
         + "Altitude =\t\t" + altitude + " feet\n"
         + "Trajectory Angle =\t" + trajectory_angle + " degrees\n"
         + "Velocity =\t\t" + velocity_fps + " feet per second\n"
         + "Elapsed Time =\t\t" + elapsed_time + " seconds\n"
         + "\nstatus_a = " + status_a + "\nstatus_b = "
         + status_b + "\nstatus_c = " + status_c;
         return results_string;
    public void start()
    if(status_a == 0 )
    strtb();
    if (status_b == 0)
    reset();
    }// end method start
    } //end class trajectory_b

  • Things Visible in Two Classes

    I'm developing a program using two classes: "Analysis.class" and "AnalysisCalc.class", each in separate files. I don't desire to import either class via package design. I'm trying to call a method from "AnalysisCalc.class" using variables visible to both classes. The intent of the program is to decrement a variable using a while loop. The intent of using "AnalysisCalc.class" is to manage my code better rather than consolidate all the code in "Analysis.class". How do I modify the following source code for these classes?
    (NOTE: Don't worry about other aspects of program such as I/O since I know how to handle that )
    // Analysis Program: Analysis.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Analysis extends JApplet implements ActionListener {
         double variableX;
         boolean variableA, variableB;
         public void init()
              variableX = 0;          
              variableA = true;
              variableB = true;
         } // end method init     
         public void strt()
              while(variableB){                    
                   rundata();
                   if( variableX < 10 )
                        variableB = false;
         }  // end method strt
         strt();
    } //end class Analysis
    // AnalysisCalc.java
    public class AnalysisCalc {  
         // AnalysisCalc constructor
         public AnalysisCalc()
              rundata( );
         public void rundata( )
              if( variableA == true)
                   variableX = 100;
                   variableA = false;
              variableX--;
    } // end class AnalysisCalc

    OK, forget the code I posted previously.
    The following code in files Trajectory.java and Calculate.java have a similar problem. I'm trying to get my method set up simple with a decrement logic because later the logic for the method will become more complex. I want to keep all this complex code out of the Trajectory.java file and manage it from the Calculate.java file. I would set up package and import design, but my ISP will not accept package design in building website since fully qualified names must be used to avoid naming conflicts.
    key code segments in file trajectory.java, being analogous to Analysis.java, include--->
    Calculate Z = new Calculate();
    while(sentinel){
    Z.rundata();
    if( altitude < 10 )
    sentinel = false;
    The file analogous to AnalysisCalc.java is Calculate.java
    // Trajectory Analysis Program: Trajectory.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Trajectory extends JApplet implements ActionListener {
         final double MAX = 90.0;
         final double MIN = -90.0;
         final double MAX_ALTITUDE = 2000000.0;
         final double MIN_ALTITUDE = 0.0;
         private JTextArea introductionArea, resultsArea;
         private JLabel spanLabel, chordLabel,
              thicknessLabel, massLabel, altitudeLabel, velocityLabel,
              trajectory_angleLabel, time_incrementLabel, rotation_factorLabel,
              calculationLabel, resultsLabel;
         private JTextField spanField, chordField, thicknessField,
              massField, altitudeField, velocityField, trajectory_angleField,
              time_incrementField, rotation_factorField;
         private JButton startButton, resetButton, contButton, abortButton;
         String introduction_string, span_string, chord_string, thickness_string, mass_string,
              altitude_string, velocity_string, trajectory_angle_string,
              time_increment_string, rotation_factor_string, results_string;
         public double span, chord, thickness, mass, altitude, velocity, trajectory_angle, time_increment,
              rotation_factor, distance, velocity_fps, elapsed_time;
         boolean value, sentinel;
         // create objects
         public void init()
              Calculate Z = new Calculate();
              span = 0;
              chord = 0;
              thickness = 0;
              mass = 0;
              altitude = 0;
              velocity = 0;
              trajectory_angle = 0;
              time_increment = 0;
              rotation_factor = 0;
              distance = 0;
              velocity_fps = 0;
              elapsed_time = 0;
              velocity_fps = 0;
              elapsed_time = 0;
              value = true;
              sentinel = true;
              introduction_string =
                   "DEBRIS TRAJECTORY PROGRAM\n" 
                   + "designed by Weldon K. Chafin, Jr.\n\n"
                   + "Inspired by the brave heroes of the Columbia Accident "
                   + "of February 1, 2003.\n\n"
                   + "This program determines trajectory for an object modeled "
                   + "as a rectangular prism having given mass falling through "
                   + "the atmosphere. The object is assumed to oscillate with same "
                   + "frequency about all six possible permutations for axis "
                   + "angular velocity vectors as the means to simulate "
                   + "equally likely random events.\n\n"
                   + "NOTE: This program is still under construction. "
                   + "I predict this program will be fully functional by October 4, 2003. "
                   + "Then it should have calculation capability comparable to the C++ program version I created "
                   + "for the Columbia Accident Investigation Board (CAIB) to predict locations of Columbia debris. "
                   + "In fact, the CAIB forwarded my program as an analytical tool to NASA "
                   + "JSE Early Sightings Assessment Team tasked with finding high interest "
                   + "Columbia debris items via radar imaging.";
              span_string = "";
              chord_string = "";
              thickness_string = "";
              mass_string = "";
              altitude_string = "";
              velocity_string = "";
              trajectory_angle_string = "";           
              time_increment_string = "";
              rotation_factor_string = "";
              results_string = "";
              // create container & panel
              Container container = getContentPane();     
              Panel panel = new Panel( new FlowLayout( FlowLayout.LEFT));
              container.add( panel );
              // set up vertical boxlayout
              Box box = Box.createVerticalBox();
              Box inputbox1 = Box.createHorizontalBox();
              Box inputbox2 = Box.createHorizontalBox();
              Box inputbox2a = Box.createHorizontalBox();
              Box inputbox2b = Box.createHorizontalBox();
              Box inputbox2c = Box.createHorizontalBox();
              Box inputbox2d = Box.createHorizontalBox();
              Box inputbox3 = Box.createHorizontalBox();
              Box buttonbox = Box.createHorizontalBox();
              // set up introduction
              introductionArea = new JTextArea( introduction_string, 10, 50 );
              introductionArea.setEditable( false );
              box.add( new JScrollPane( introductionArea ) );
              box.add( Box.createVerticalStrut (10) );
              box.add( inputbox1);
              box.add(inputbox2a);
              Dimension minSize = new Dimension(5, 15);
              Dimension prefSize = new Dimension(5, 15);
              Dimension maxSize = new Dimension(Short.MAX_VALUE, 15);
              inputbox2a.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up span
              spanLabel = new JLabel( "span (feet)" );
              spanField = new JTextField(5 );
              inputbox2a.add( spanLabel );
              inputbox2a.add( spanField );
              inputbox2a.add(new Box.Filler(minSize, prefSize, maxSize));          
              // set up chord
              chordLabel = new JLabel( "chord (feet)" );
              chordField = new JTextField(5 );
              inputbox2a.add( chordLabel );
              inputbox2a.add( chordField );
              inputbox2a.add(new Box.Filler(minSize, prefSize, maxSize));     
              // set up thickness
              thicknessLabel = new JLabel( "thickness (feet)" );
              thicknessField = new JTextField(5 );
              inputbox2a.add( thicknessLabel );
              inputbox2a.add( thicknessField );
              inputbox2a.add(new Box.Filler(minSize, prefSize, maxSize));
              box.add( Box.createVerticalStrut (10) );
              box.add(inputbox2b);
              inputbox2b.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up mass
              massLabel = new JLabel( "mass (slugs)" );
              massField = new JTextField(5);
              inputbox2b.add( massLabel );
              inputbox2b.add( massField );
              inputbox2b.add(new Box.Filler(minSize, prefSize, maxSize));     
              // set up altitude
              altitudeLabel = new JLabel( "altitude (feet)");
              altitudeField = new JTextField(5 );
              inputbox2b.add( altitudeLabel );
              inputbox2b.add( altitudeField );
              inputbox2b.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up velocity
              velocityLabel = new JLabel( "velocity (Mach Number)");
              velocityField = new JTextField(5);
              inputbox2b.add( velocityLabel );
              inputbox2b.add( velocityField );
              inputbox2b.add(new Box.Filler(minSize, prefSize, maxSize));
              box.add( Box.createVerticalStrut (10) );
              Dimension minSize2c = new Dimension(160, 15);
              Dimension prefSize2c = new Dimension(160, 15);
              Dimension maxSize2c = new Dimension(Short.MAX_VALUE, 15);
              box.add(inputbox2c);
              inputbox2c.add(new Box.Filler(minSize2c, prefSize2c, maxSize2c));
              // set up trajectory_angle
              trajectory_angleLabel = new JLabel( "trajectory angle (degrees)");
              trajectory_angleField = new JTextField(5);
              inputbox2c.add( trajectory_angleLabel );
              inputbox2c.add( trajectory_angleField );
              inputbox2c.add(new Box.Filler(minSize2c, prefSize2c, maxSize2c));
              box.add( Box.createVerticalStrut (10) );
              Dimension minSize2d = new Dimension(50, 15);
              Dimension prefSize2d = new Dimension(50, 15);
              Dimension maxSize2d = new Dimension(Short.MAX_VALUE, 15);
              box.add(inputbox2d);
              inputbox2d.add(new Box.Filler(minSize2d, prefSize2d, maxSize2d));
              // set up time_increment
              time_incrementLabel = new JLabel( "time increment (seconds)" );
              time_incrementField = new JTextField(5);
              inputbox2d.add( time_incrementLabel );
              inputbox2d.add( time_incrementField );
              inputbox2d.add(new Box.Filler(minSize2d, prefSize2d, maxSize2d));
              // set up rotation_factor
              rotation_factorLabel = new JLabel( "rotation factor (number)" );
              rotation_factorField = new JTextField(5);
              inputbox2d.add( rotation_factorLabel );
              inputbox2d.add( rotation_factorField );
              inputbox2d.add(new Box.Filler(minSize2d, prefSize2d, maxSize2d));
              box.add( Box.createVerticalStrut (10) );
              box.add( buttonbox);
              Dimension minSizeB = new Dimension(10, 30);
              Dimension prefSizeB = new Dimension(10, 30);
              Dimension maxSizeB = new Dimension(Short.MAX_VALUE, 30);
              buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
              // set up start
              startButton = new JButton( "START" );
              buttonbox.add( startButton );
              buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
              // set up reset
              resetButton = new JButton( "RESET" );
              buttonbox.add( resetButton );
              buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
              // set up cont
              contButton = new JButton( "CONTINUE" );
              buttonbox.add( contButton );
              buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
              // set up abort
              abortButton = new JButton( "ABORT" );
              buttonbox.add( abortButton );
              buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
              box.add( Box.createVerticalStrut (10) );          
              // set up results
              resultsArea = new JTextArea( results_string, 6, 50 );
              resultsArea.setEditable( false );
              box.add( new JScrollPane( resultsArea ) );
              // add box to panel
              panel.add( box );
              // register event handlers
              spanField.addActionListener( this );
              chordField.addActionListener( this );          
              thicknessField.addActionListener( this );
              massField.addActionListener( this );
              altitudeField.addActionListener( this );
              velocityField.addActionListener( this );          
              trajectory_angleField.addActionListener( this );
              time_incrementField.addActionListener( this );
              rotation_factorField.addActionListener( this );
              startButton.addActionListener( this );
              resetButton.addActionListener( this );
              contButton.addActionListener( this );
              abortButton.addActionListener( this );
              reset();
         } // end method init     
         public void t_r_a_test (double trajectory_angle) throws Tare {   
              if (trajectory_angle > MAX || trajectory_angle < MIN)
                          throw new Tare("\ntrajectory_angle "
                   + trajectory_angle + " is outside of allowable range\n\n" 
                   + "Try another value for the trajectory angle\n"
                   + "( " + MIN + " <= trajectory angle <= " + MAX + " )" );
         }  // end method t_r_a_test
         public void a_r_e_test (double altitude) throws Are {   
              if ( altitude > MAX_ALTITUDE )
                          throw new Are("\naltitude "
                   + altitude + " is outside of allowable range\n\n" 
                   + "Try value for altitude\n"
                   + "( " + MIN_ALTITUDE + " <= altitude <= "
                   + MAX_ALTITUDE + " )" );
         }  // end method a_r_e_test
         public void n_v_test (boolean value) throws Nve {   
              if ( value == false ){
                   if( span < 0 ){
                         span = 0;
                               throw new Nve("\nValue for "
                        + " span must not be negative\n\n" 
                        + "Try another value ");
                   if( chord < 0 ){
                         chord = 0;
                               throw new Nve("\nValue for "
                        + " chord must not be negative\n\n" 
                        + "Try another value ");
                   if( thickness < 0 ){
                         thickness = 0;
                               throw new Nve("\nValue for "
                        + " thickness must not be negative\n\n" 
                        + "Try another value ");
                   if( mass < 0 ){
                         mass = 0;
                               throw new Nve("\nValue for "
                        + " mass must not be negative\n\n" 
                        + "Try another value ");
                   if( altitude < 0 ){
                        altitude = 0;
                               throw new Nve("\nValue for "
                        + " altitude must not be negative\n\n" 
                        + "Try another value ");
                   if( velocity < 0 ){
                        velocity = 0;
                               throw new Nve("\nValue for "
                        + " velocity must not be negative\n\n" 
                        + "Try another value ");
                   if( time_increment < 0 ){
                        time_increment = 0;
                               throw new Nve("\nValue for "
                        + " time increment must not be negative\n\n" 
                        + "Try another value ");
                   if( rotation_factor < 0 ){
                        rotation_factor = 0;
                               throw new Nve("\nValue for "
                        + " rotation factor must not be negative\n\n" 
                        + "Try another value ");
              } //end if( value == false )
         }  // end method n_v_test
         // process events
         public void actionPerformed( ActionEvent event )
              // process spanField
              if( event.getSource() == spanField ) {
                   span_string = spanField.getText();
                   span = Double.parseDouble( span_string);
              // process chordField
              if( event.getSource() == chordField ) {
                   chord_string = chordField.getText();
                   chord = Double.parseDouble( chord_string);
              // process thicknessField
              if( event.getSource() == thicknessField ) {
                   thickness_string = thicknessField.getText();
                   thickness = Double.parseDouble( thickness_string);
              // process massField
              if( event.getSource() == massField ) {
                   mass_string = massField.getText();
                   mass = Double.parseDouble( mass_string);
              // process altitudeField
              if( event.getSource() == altitudeField ){
                   altitude_string = altitudeField.getText();
                   altitude = Double.parseDouble( altitude_string);
              // process velocityField
              if( event.getSource() == velocityField ){
                   velocity_string = velocityField.getText();
                   velocity = Double.parseDouble( velocity_string);
              // process trajectory_angleField
              if( event.getSource() == trajectory_angleField ){
                   trajectory_angle_string = trajectory_angleField.getText();
                   trajectory_angle = Double.parseDouble( trajectory_angle_string);
              // process time_incrementField
              if( event.getSource() == time_incrementField ){
                   time_increment_string = time_incrementField.getText();
                   time_increment = Double.parseDouble( time_increment_string);
              // process rotation_factorField
              if( event.getSource() == rotation_factorField ){
                   rotation_factor_string = rotation_factorField.getText();
                   rotation_factor = Double.parseDouble( rotation_factor_string);
              // process startButton event
              if ( event.getSource() == startButton )                
                   strtb();               
              // process resetButton event
              if ( event.getSource() == resetButton )
                   reset();
              // process contButton event
              if ( event.getSource() == contButton )
                   cont();
              // process abortButton event
              if ( event.getSource() == abortButton )
                   abort();
         } // end method actionPerformed
         public void strtb()
              try{          
                   span = Double.parseDouble( spanField.getText() );
                   chord = Double.parseDouble( chordField.getText() );
                   thickness = Double.parseDouble( thicknessField.getText() );
                   mass = Double.parseDouble( massField.getText() );
                   altitude = Double.parseDouble( altitudeField.getText());
                   velocity = Double.parseDouble( velocityField.getText());
                   trajectory_angle = Double.parseDouble( trajectory_angleField.getText());
                   time_increment = Double.parseDouble( time_incrementField.getText() );     
                   rotation_factor = Double.parseDouble( rotation_factorField.getText() );          
                   if( span < 0 || chord < 0 || thickness < 0 || mass < 0
                        || altitude < 0 || velocity < 0
                        || time_increment < 0 || rotation_factor < 0 )
                   value = false;
                   t_r_a_test( trajectory_angle );
                   n_v_test( value );
                   a_r_e_test( altitude );
                   while(sentinel){
                        Z.rundata();
                        if( altitude < 10 )
                             sentinel = false;
                   results();
                   resultsArea.setText( results() );
              }//end try
              // process improperly formatted input
              catch ( NumberFormatException numberFormatException ) {
                   JOptionPane.showMessageDialog( this,
                   "You must enter numbers in decimal format or integers"     ,
                   "Invalid Number Format" ,
                   JOptionPane.ERROR_MESSAGE );
              } // end catch NumberFormatException
              catch ( ArithmeticException arithmeticException ) {
                   JOptionPane.showMessageDialog( this,
                   arithmeticException.toString(), "Arithmetic Exception" ,
                   JOptionPane.ERROR_MESSAGE );
              } // end catch ArithmeticException
              catch ( Tare tare ) {
                        JOptionPane.showMessageDialog( this,
                        tare.toString(), "-90 <= range <= 90 " ,
                        JOptionPane.ERROR_MESSAGE );
              } // end catch Tare
              catch ( Nve nve ) {
                        JOptionPane.showMessageDialog( this,
                        nve.toString(), " value less than zero" ,
                        JOptionPane.ERROR_MESSAGE );
              } // end catch Nve
              catch ( Are are ) {
                        JOptionPane.showMessageDialog( this,
                        are.toString(), " value greater than maximum" ,
                        JOptionPane.ERROR_MESSAGE );
              } // end catch Are
         }  // end method strtb
         public void reset()
              span_string = "";
              chord_string = "";
              thickness_string = "";
              mass_string = "";
              altitude_string = "";
              velocity_string = "";
              trajectory_angle_string = "";
              time_increment_string = "";
              rotation_factor_string = "";
              results_string = "";
              spanField.setText( span_string );
              chordField.setText( chord_string );
              thicknessField.setText( thickness_string );
              massField.setText( mass_string );
              altitudeField.setText( altitude_string );
              velocityField.setText( velocity_string );
              trajectory_angleField.setText( trajectory_angle_string );
              time_incrementField.setText( time_increment_string );
              rotation_factorField.setText( rotation_factor_string );
              resultsArea.setEditable( true );
              resultsArea.setText( results_string );
              resultsArea.setEditable( false );
              span = 0;
              chord = 0;
              thickness = 0;
              mass = 0;
              altitude = 0;
              velocity = 0;
              trajectory_angle = 0;
              time_increment = 0;
              rotation_factor = 0;
              distance = 0;
              velocity_fps = 0;
              elapsed_time = 0;
              value = true;
         }   // end method reset
         public void cont()
         //later
         public void abort()
         //later
         public String results()
         results_string =
         "Distance =\t\t" + distance + " miles\n"
         + "Altitude =\t\t" + altitude + " feet\n"
         + "Trajectory Angle =\t" + trajectory_angle + " degrees\n"
         + "Velocity =\t\t" + velocity_fps + " feet per second\n"
         + "Elapsed Time =\t\t" + elapsed_time + " seconds\n";
         return results_string;
    } //end class Trajectory// Trajectory Analysis Program: Calculate.java
    public class Calculate {  
         Trajectory T = new Trajectory();
         // Calculate constructor
         public Calculate()
              rundata( );
         public void rundata( )
         T.altitude--;
    } // end class Calculate

  • Help with classpaths......I think

    Hi, I'm still kinda new to Java and I was trying to run through a couple of the examples in the Dietel & Dietel "Advanced Java 2 Platform How to Progam" Textbook (specifically example 4.15). Problem is when I try to run the programs I get a bunch of errors saying that certain classes (all relating to the Java3D API) don't exist or can't be found. This example required me to have the Java3D API and I think I must not have installed it right or put it in the wrong place. I was wondering if anyone could help me get the examples to run or at least help me get the directories set up properly
    I'm using the latest version of JCreator
    with JDK version 1.5
    and Java3D version 1.4
    on Windows XP
    if that helps...
    the files I'm trying to run are as follows:
    // Java3DExample.java
    // Java3DExample is an application that demonstrates Java 3D
    // and provides an interface for a user to control the
    // transformation, lighting color, and texture of a 3D scene.
    package com.deitel.advjhtp1.java3d;
    // Java core packages
    import java.awt.*;
    import java.awt.event.*;
    // Java extension packages
    import javax.swing.*;
    import javax.swing.event.*;
    public class Java3DExample extends JFrame {
       private Java3DWorld java3DWorld;  // 3D scene panel
       private JPanel controlPanel;  // 3D scene control panel  
       // initialize Java3DWorld and ControlPanel
       public Java3DExample()
          super( "Java 3D Graphics Demo" );
          java3DWorld = new Java3DWorld( "images/ajhtp.png" );
          controlPanel = new ControlPanel( java3DWorld );
          // add Components to JFrame
          getContentPane().add( java3DWorld, BorderLayout.CENTER );
          getContentPane().add( controlPanel, BorderLayout.EAST );      
       } // end Java3DExample constructor
       // start program
       public static void main( String args[] )
          Java3DExample application = new Java3DExample();
          application.setDefaultCloseOperation( EXIT_ON_CLOSE );
          application.pack();
          application.setVisible( true );
    // Java3DWorld.java
    // Java3DWorld is a Java 3D Graphics display environment
    // that creates a SimpleUniverse and provides capabilities for
    // allowing a user to control lighting, motion, and texture
    // of the 3D scene.
    package com.deitel.advjhtp1.java3d;
    // Java core packages
    import java.awt.event.*;
    import java.awt.*;
    import java.net.*;
    // Java extension packages
    import javax.swing.event.*;
    import javax.media.j3d.*;
    import javax.vecmath.*;
    // Java3D utility packages
    import com.sun.j3d.utils.universe.*;
    import com.sun.j3d.utils.image.*;
    import com.sun.j3d.utils.geometry.*;
    import com.sun.j3d.utils.behaviors.mouse.*;
    public class Java3DWorld extends Canvas3D {
       private Appearance appearance; // 3D object's appearance
       private Light ambientLight; // ambient scene lighting
       private Box shape; // 3D object to manipulate
       private Color3f lightColor; // Light color
       private Light directionalLight;
       private Material material; // 3D objects color object
       private SimpleUniverse simpleUniverse; // 3D scene environment
       private TextureLoader textureLoader; // 3D object's texture
       // holds 3D transformation information
       private TransformGroup transformGroup; 
       private String imageName; // texture image file name
       // Java3DWorld constructor
       public Java3DWorld( String imageFileName ) {
          super( SimpleUniverse.getPreferredConfiguration() );
          imageName = imageFileName;
          // create SimpleUniverse ( 3D Graphics environment )
          simpleUniverse = new SimpleUniverse( this );
          // set viewing distance for 3D scene
          ViewingPlatform viewPlatform =
             simpleUniverse.getViewingPlatform();
          viewPlatform.setNominalViewingTransform();
          // create 3D scene
          BranchGroup branchGroup = createScene();
          // attach BranchGroup to SimpleUniverse
          simpleUniverse.addBranchGraph( branchGroup );
       } // end Java3DWorld constructor   
       // create 3D scene
       public BranchGroup createScene()
          BranchGroup scene = new BranchGroup();
          // initialize TransformGroup
          transformGroup = new TransformGroup();
          // set TransformGroup's WRITE permission
          transformGroup.setCapability(
             TransformGroup.ALLOW_TRANSFORM_WRITE );
          transformGroup.setCapability(
             TransformGroup.ALLOW_TRANSFORM_READ );
          // add TransformGroup to BranchGroup
          scene.addChild( transformGroup );
          // create BoundingSphere
          BoundingSphere bounds = new BoundingSphere(
             new Point3d( 0.0f, 0.0f, 0.0f ), 100.0 );
          appearance = new Appearance(); // create object appearance
          material = new Material(); // create texture matieral
          appearance.setMaterial( material );
          String rgb = new String( "RGB" );
          // load texture for scene object
          textureLoader = new TextureLoader(
             Java3DWorld.class.getResource( imageName ), rgb, this );
          // set capability bits for enabling texture
          textureLoader.getTexture().setCapability(
             Texture.ALLOW_ENABLE_WRITE ); 
          // initial texture will not show
          textureLoader.getTexture().setEnable( false );
          // set object's texture
          appearance.setTexture( textureLoader.getTexture() );
          // create object geometry
          Box shape = new Box( 0.3f, 0.3f, 0.3f,
             Box.GENERATE_NORMALS | Box.GENERATE_TEXTURE_COORDS, 
             appearance ); 
          // add geometry to TransformGroup
          transformGroup.addChild( shape );
          // initialize Ambient lighting
          ambientLight = new AmbientLight();
          ambientLight.setInfluencingBounds( bounds );
          // initialize directionalLight
          directionalLight = new DirectionalLight();
          lightColor = new Color3f(); // initialize light color
          // set initial DirectionalLight color
          directionalLight.setColor( lightColor );
          // set capability bits to allow DirectionalLight's
          // Color and Direction to be changed
          directionalLight.setCapability(
             DirectionalLight.ALLOW_DIRECTION_WRITE );
          directionalLight.setCapability(
             DirectionalLight.ALLOW_DIRECTION_READ );
          directionalLight.setCapability(
             DirectionalLight.ALLOW_COLOR_WRITE );
          directionalLight.setCapability(
             DirectionalLight.ALLOW_COLOR_READ );
          directionalLight.setInfluencingBounds( bounds );
          // add light nodes to BranchGroup
          scene.addChild( ambientLight );
          scene.addChild( directionalLight );
          // initialize rotation behavior
          MouseRotate rotateBehavior = new MouseRotate();
          rotateBehavior.setTransformGroup( transformGroup );
          rotateBehavior.setSchedulingBounds( bounds );
          // initialize translation behavior 
          MouseTranslate translateBehavior = new MouseTranslate();
          translateBehavior.setTransformGroup( transformGroup );
          translateBehavior.setSchedulingBounds(
             new BoundingBox( new Point3d( -1.0f, -1.0f, -1.0f ),
             new Point3d( 1.0f, 1.0f, 1.0f ) ) );
          // initialize scaling behavior
          MouseZoom scaleBehavior = new MouseZoom();
          scaleBehavior.setTransformGroup( transformGroup );
          scaleBehavior.setSchedulingBounds( bounds );
          // add behaviors to BranchGroup
          scene.addChild( scaleBehavior ); 
          scene.addChild( rotateBehavior );
          scene.addChild( translateBehavior );
          scene.compile();
          return scene;
       } // end method createScene
       // change DirectionLight color
       public void changeColor( Color color )
          lightColor.set( color );
          directionalLight.setColor( lightColor );
       // change geometry surface to textured image or material color
       public void updateTexture( boolean textureValue )
          textureLoader.getTexture().setEnable( textureValue );
       // change image used for texture
       public void setImageName( String imageFileName )
          imageName = imageFileName;
       // get image file name
       public String getImageName()
          return imageName;
        // return preferred dimensions of Container
        public Dimension getPreferredSize()
           return new Dimension( 500, 500 );
        // return minimum size of Container
        public Dimension getMinimumSize()
           return getPreferredSize();
    // ControlPanel.java
    // ControlPanel is a JPanel that contains Swing controls
    // for manipulating a Java3DWorld.
    package com.deitel.advjhtp1.java3d;
    // Java core packages
    import java.awt.*;
    import java.awt.event.*;
    // Java extension packages
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    public class ControlPanel extends JPanel {
       // JSliders control lighting color
       private JSlider redSlider, greenSlider, blueSlider;
       // JCheckbox turns on texture mapping
       private JCheckBox textureCheckBox;
       // graphics display environment
       private Java3DWorld java3DWorld;
       // ControlPanel constructor
       public ControlPanel( Java3DWorld tempJ3DWorld )
          java3DWorld = tempJ3DWorld;
           // assemble instruction panel
          JPanel instructionPanel = new JPanel();
          TitledBorder titledBorder =
             new TitledBorder( "Transformation Instructions" );
          titledBorder.setTitleJustification( TitledBorder.CENTER );
          instructionPanel.setBorder( titledBorder );
          JLabel rotationInstructions =
             new JLabel( "Rotation - Left Mouse Button",
             SwingConstants.CENTER );
          JLabel translationInstructions =
             new JLabel( "Translation - Right Mouse Button",
             SwingConstants.CENTER );      
          JLabel scalingInstructions =
             new JLabel( "Scale - Alt + Left Mouse Button",
             SwingConstants.CENTER );
          // add instruction JLabels to JPanel
          instructionPanel.add( rotationInstructions );
          instructionPanel.add( translationInstructions );
          instructionPanel.add( scalingInstructions );
          // assemble texture mapping control panel
          JPanel texturePanel = new JPanel();
          TitledBorder textureBorder =
             new TitledBorder( "Texture Controls" );
          textureBorder.setTitleJustification( TitledBorder.CENTER );
          texturePanel.setBorder( textureBorder );
          textureCheckBox = new JCheckBox(
             "Apply Texture Map to Image" );
          texturePanel.add( textureCheckBox );
          // create ItemListener for JCheckBox
          textureCheckBox.addItemListener(
             new ItemListener() {
                // invoked when checkbox selected/deselected
                public void itemStateChanged( ItemEvent event )
                   if( event.getStateChange() == ItemEvent.SELECTED )
                      java3DWorld.updateTexture( true );
                   else
                      java3DWorld.updateTexture( false );
             } // end anonymous inner class
          // create JPanel with instructionPanel and texturePanel
          JPanel topPanel = new JPanel(
             new GridLayout( 2, 1, 0, 20 ) );
          topPanel.add( instructionPanel );
          topPanel.add( texturePanel );
          // assemble lighting color control panel
          JPanel colorPanel = new JPanel( 
             new FlowLayout( FlowLayout.LEFT, 15, 15 ) );
          TitledBorder colorBorder =
             new TitledBorder( "Direct Lighting Color Contols" );
          colorBorder.setTitleJustification( TitledBorder.CENTER );
          colorPanel.setBorder( colorBorder );
          JLabel redLabel = new JLabel( "R" );
          JLabel greenLabel = new JLabel( "G" );
          JLabel blueLabel = new JLabel( "B" );
          // create JSlider for adjusting red light component
          redSlider = new JSlider(
             SwingConstants.HORIZONTAL, 0, 255, 25 );
          redSlider.setMajorTickSpacing( 25 );
          redSlider.setPaintTicks( true );
          // create JSlider for adjusting green light component     
          greenSlider = new JSlider(
             SwingConstants.HORIZONTAL, 0, 255, 25 );
          greenSlider.setMajorTickSpacing( 25 );
          greenSlider.setPaintTicks( true );
          // create JSlider for adjusting blue light component
          blueSlider = new JSlider(
             SwingConstants.HORIZONTAL, 0, 255, 25 );
          blueSlider.setMajorTickSpacing( 25 );
          blueSlider.setPaintTicks( true );
          // create ChangeListener for JSliders
          ChangeListener slideListener = new ChangeListener() {
             // invoked when slider has been accessed
             public void stateChanged( ChangeEvent event )
                Color color = new Color(
                      redSlider.getValue(), greenSlider.getValue(),
                      blueSlider.getValue() );
                java3DWorld.changeColor( color );
          }; // end anonymous inner class
          // add listener to sliders
          redSlider.addChangeListener( slideListener );
          greenSlider.addChangeListener( slideListener );
          blueSlider.addChangeListener( slideListener );
          // add lighting color control components to colorPanel
          colorPanel.add( redLabel );
          colorPanel.add( redSlider );
          colorPanel.add( greenLabel );
          colorPanel.add( greenSlider );
          colorPanel.add( blueLabel );
          colorPanel.add( blueSlider );
          // set Java3DWorld object default RGB slider values
          java3DWorld.changeColor(
             new Color( redSlider.getValue(),
                greenSlider.getValue(), blueSlider.getValue() ) );
          // set GridLayout       
          setLayout( new GridLayout( 2, 1, 0, 20 ) );
          // add JPanels to ControlPanel
          add( topPanel );
          add( colorPanel );
       } // end ControlPanel constructor method
        // return preferred dimensions of container
        public Dimension getPreferredSize()
           return new Dimension( 250, 150 );
        // return minimum size of container
        public Dimension getMinimumSize()
           return getPreferredSize();
    }Thanks for any/all help
    - Joseph

    Thanks for the quick replys, I'm getting a different
    error now though.....
    Exception in thread "main"
    java.lang.IllegalArgumentException: input == null!
    at
    com.deitel.advjhtp1.java3d.Java3DWorld.createScene(Jav
    a3DWorld.java:94)
    at
    com.deitel.advjhtp1.java3d.Java3DWorld.<init>(Java3DWo
    rld.java:58)
    at
    com.deitel.advjhtp1.java3d.Java3DExample.<init>(Java3D
    Example.java:25)
    at
    com.deitel.advjhtp1.java3d.Java3DExample.main(Java3DEx
    ample.java:37)I assume those com.deitel.* thingies are about your own code, and it's showing you what lines in the source code caused the error. Obviously from the error message you're somewhere passing a null input to a method which requires a non-null argument. What do you want us to do about that?

  • When my thread starts running, at that time keylistener is not working.

    when my thread starts running, at that time keylistener is not working.
    plz reply me.

    //FrameShow.java
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import java.awt.Dimension;
    import java.awt.geom.Dimension2D;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.util.logging.Level;
    import java.awt.event.*;
    import java.util.*;
    public class FrameShow extends JFrame implements ActionListener,KeyListener
         boolean paused=false;
         JButton stop;
         JButton start;
         JButton exit;
         public IncludePanel CenterPanel;
         public FrameShow()
    CenterPanel= new IncludePanel();
              Functions fn=new Functions();
              int height=fn.getScreenHeight();
              int width=fn.getScreenWidth();
              setTitle("Game Assignment--Santanu Tripathy--MCA");
              setSize(width,height);
              setResizable(false);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              show();
              initComponents();
              DefaultColorSet();
              this.addKeyListener(this);
         this.setFocusable(true);
         public void initComponents()
              Container contentpane=getContentPane();
              //Creating Panel For Different Side
              JPanel EastPanel= new JPanel();
              JPanel WestPanel= new JPanel();
              JPanel NorthPanel= new JPanel();
              JPanel SouthPanel= new JPanel();
              //CenterPanel = new IncludePanel();
              //IncludePanel CenterPanel= new IncludePanel();
              EastPanel.setPreferredSize(new Dimension(100,10));
              WestPanel.setPreferredSize(new Dimension(100,10));
              NorthPanel.setPreferredSize(new Dimension(10,100));
              SouthPanel.setPreferredSize(new Dimension(10,100));
              //CenterPanel.setPreferredSize(new Dimension(200,200));
              //Adding Color to the Panels
              NorthPanel.setBackground(Color.green);
              SouthPanel.setBackground(Color.orange);
              CenterPanel.setBackground(Color.black);
              //Creating Border For Different Side
              Border EastBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border WestBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border NorthBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border SouthBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border CenterBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              //Creating Components For East Panel
              JLabel left= new JLabel("LEFT");
              JLabel right= new JLabel("RIGHT");
              JLabel rotate= new JLabel("ROTATE");
              left.setForeground(Color.blue);
              right.setForeground(Color.blue);
              rotate.setForeground(Color.blue);
              //Creating Components For West Panel
              ButtonGroup group = new ButtonGroup();
              JRadioButton rb1 = new JRadioButton("Pink",false);
              JRadioButton rb2 = new JRadioButton("Cyan",false);
              JRadioButton rb3 = new JRadioButton("Orange",false);
              JRadioButton _default = new JRadioButton("Black",true);
              rb1.setForeground(Color.pink);
              rb2.setForeground(Color.cyan);
              rb3.setForeground(Color.orange);
              _default.setForeground(Color.black);
              //Creating Components For North Panel
              JLabel name= new JLabel("Santanu Tripathy");
              name.setForeground(Color.blue);
              name.setFont(new Font("Serif",Font.BOLD,30));
              //Creating Components For South Panel
              start = new JButton();
              stop = new JButton();
              exit = new JButton();
              start.setToolTipText("Click this button to start the game");
              start.setFont(new java.awt.Font("Trebuchet MS", 0, 12));
              start.setText("START");
              start.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(3, 5, 3, 5), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
              start.setMaximumSize(new java.awt.Dimension(90, 35));
              start.setMinimumSize(new java.awt.Dimension(90, 35));
              start.setPreferredSize(new java.awt.Dimension(95, 35));
              if(paused)
                   stop.setToolTipText("Click this button to pause the game");
              else
                   stop.setToolTipText("Click this button to resume the game");
              stop.setFont(new java.awt.Font("Trebuchet MS", 0, 12));
              stop.setText("PAUSE");
              stop.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(3, 5, 3, 5), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
              stop.setMaximumSize(new java.awt.Dimension(90, 35));
              stop.setMinimumSize(new java.awt.Dimension(90, 35));
              stop.setPreferredSize(new java.awt.Dimension(95, 35));
              exit.setToolTipText("Click this button to exit from the game");
              exit.setFont(new java.awt.Font("Trebuchet MS", 0, 12));
              exit.setText("EXIT");
              exit.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(3, 5, 3, 5), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
              exit.setMaximumSize(new java.awt.Dimension(90, 35));
              exit.setMinimumSize(new java.awt.Dimension(90, 35));
              exit.setPreferredSize(new java.awt.Dimension(95, 35));
              //Adding some extra things to the Panels
              group.add(rb1);
              group.add(rb2);
              group.add(rb3);
              group.add(_default);
              //Adding Component into the Panels
              EastPanel.add(left);
              EastPanel.add(right);
              EastPanel.add(rotate);
              WestPanel.add(rb1);
              WestPanel.add(rb2);
              WestPanel.add(rb3);
              WestPanel.add(_default);
              NorthPanel.add(name);
              SouthPanel.add(start);
              SouthPanel.add(stop);
              SouthPanel.add(exit);
              //Adding Border Into the Panels
              EastPanel.setBorder(EastBr);
              WestPanel.setBorder(WestBr);
              NorthPanel.setBorder(NorthBr);
              SouthPanel.setBorder(SouthBr);
              CenterPanel.setBorder(CenterBr);
              //Adding Panels into the Container
              EastPanel.setLayout(new GridLayout(0,1));
              contentpane.add(EastPanel,BorderLayout.EAST);
              WestPanel.setLayout(new GridLayout(0,1));
              contentpane.add(WestPanel,BorderLayout.WEST);
              contentpane.add(NorthPanel,BorderLayout.NORTH);
              contentpane.add(SouthPanel,BorderLayout.SOUTH);
              contentpane.add(CenterPanel,BorderLayout.CENTER);
              //Adding Action Listeners
              rb1.addActionListener(this);
              rb2.addActionListener(this);
              rb3.addActionListener(this);
              _default.addActionListener(this);
              exit.addActionListener(this);
              start.addActionListener(this);
    try
              start.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent e )
                        start.setEnabled(false);
    CenterPanel.drawCircle();
    catch(Exception e)
    {System.out.println("Exception is attached with sart button exp = "+e);}
    try
              stop.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent e )
                        paused=!paused;
                        if(paused)
                             start.setToolTipText("Click this button to resume the game");
                             stop.setText("RESUME");
                        else
                             start.setToolTipText("Click this button to pause the game");
                             stop.setText("PAUSE");
    CenterPanel.pause();
    catch(Exception e)
    {System.out.println("Exception is attached with sart button exp = "+e);}
         public void DefaultColorSet()
              getContentPane().setBackground(Color.white);
         public void actionPerformed(ActionEvent AE)
              String str=(String)AE.getActionCommand();
              if(str.equalsIgnoreCase("pink"))
                   CenterPanel.setBackground(Color.pink);
              if(str.equalsIgnoreCase("cyan"))
                   CenterPanel.setBackground(Color.cyan);
              if(str.equalsIgnoreCase("orange"))
                   CenterPanel.setBackground(Color.orange);
              if(str.equalsIgnoreCase("black"))
                   CenterPanel.setBackground(Color.black);
              if(str.equalsIgnoreCase("exit"))
                   System.exit(0);
         public void keyTyped(KeyEvent kevt)
    //repaint();
    public void keyPressed(KeyEvent e)
              System.out.println("here key pressed");
              //CenterPanel.dec();
         public void keyReleased(KeyEvent ke) {}
    }//End of FrameShow.ja
    //IncludePanel.java
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.Graphics.*;
    import java.awt.Dimension;
    import java.awt.geom.Dimension2D;
    import java.util.*;
    import java.util.logging.Level;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    public class IncludePanel extends JPanel implements Runnable
    int x=0,y=0;
    int color_1=0;
    int color_2=1;
    int start=0;
    Thread th;
    Image red,blue,green,yellow;
    java.util.List image;
    static boolean PAUSE=false;
         public IncludePanel()
         red= Toolkit.getDefaultToolkit().getImage("red.png");
         blue= Toolkit.getDefaultToolkit().getImage("blue.png");
         green= Toolkit.getDefaultToolkit().getImage("green.png");
         yellow= Toolkit.getDefaultToolkit().getImage("yellow.png");
    public void paintComponent(Graphics g)
              super.paintComponent(g);
              draw(g);
    public void dec()
         System.out.println("in dec method");
         x=x+30;
    public void draw(Graphics g)
              g.setColor(Color.red);
              int xx=0,yy=0;
              for (int row=0;row<=12;row++)
                   g.drawLine(xx,yy,180,yy);
                   yy=yy+30;
              xx=0;
              yy=0;
              for (int col=0;col<=6;col++)
                   g.drawLine(xx,yy,xx,360);
                   xx=xx+30;
              if(color_1==0)
                   g.drawImage(red, x, y, this);
              else if(color_1==1)
                   g.drawImage(blue,x, y, this);
              else if(color_1==2)
                   g.drawImage(green,x,y, this);
              else if(color_1==3)
                   g.drawImage(yellow,x,y, this);
    x=x+30;
              if(color_2==0)
                   g.drawImage(red, x, y, this);
              else if(color_2==1)
                   g.drawImage(blue,x,y, this);
              else if(color_2==2)
                   g.drawImage(green,x,y, this);
              else if(color_2==3)
                   g.drawImage(yellow,x,y, this);
    x=0;
    public void drawCircle( )
         th=new Thread(this);
         th.start();
         public void pause()
              if(PAUSE)
                   th.resume();
                   PAUSE=false;
                   return;
              if(!PAUSE)
              PAUSE=true;
         public synchronized void run()
              Random rand = new Random();
              Thread ani=Thread.currentThread();
              while(ani==th)
                   if(PAUSE)
                        th.suspend();
                   if(y==330)
                        color_1 = Math.abs(rand.nextInt())%4;
                        color_2 = Math.abs(rand.nextInt())%4;
                        if(color_1==color_2)
                             color_2=(color_2+1)%4;
                        y=0;
                   else
                        y=y+30;
                   repaint();
                   try
                        Thread.sleep(700);
                   catch(Exception e)
         }//End of run
    i sent two entire program

  • Trajectory

    ee my program implementation @ the following:
    http://home.comcast.net/~weldonchafinjr/wsb/html/view.cgi-home.html-.html
    using TRAJECTORY PROGRAM link
    or
    http://home.comcast.net/wsb-cgi-bin/ssi.cgi?PWPTool=HTMLView&State=False&wsbID=257896&GroupID=228536&Owner=weldonchafinjr&SiteID=1297966
    or
    http://home.comcast.net/~weldonchafinjr/wsb/trajectory/Trajectory.html
    The program set is not allowed to have inner classes and is comprised of five classes and the html file:
    Trajectory.class :      Trajectory.java has 1135 LOC in castrated version
    SimulationPanel.class:      SimulationPanel.java has 152 LOC
    Are.class:     Are.java has 7 LOC
    Tare.class      Tare.class has 7 LOC
    Nve.class      Nve.class has 7 LOC
    Trajectory.html      Trajectory.html has 11 LOC
    Trajectory.class extends JApplet implements ActionListener
    SimulationPanel.class extends JPanel used in Trajectory.class
    Are.class., Tare.class, Nve.class each extends Exception class
    Trajectory.html is a basic html file
    Trajectory.class creates a GUI for user I/O, calculates data and creates a timer to set up an array of the data. SimulationPanel then uses array data to invoke paintComponent( Graphics g ) method and plot the data. Simulation Panel sets up a 2D real time simulation display.
    The program set works fine via appletviewer Trajectory.html command.
    However, invoking the html file directly causes a problem. When the Simulation Panel display is generated, I am unable to use its reset button to perform another 2D Simulation. The scale for the 2D Simulation is frozen and the applet seems to encounter deadlock. So I have added the information messages via showMessageDialog to warn users of this problem. I saw the Sunmicrosystems demo program "DitherTest.java" code and noticed how threads were controlled with a wipe operation via a "New Image" button and I wonder if my Simulation Panel reset button could be modified to do something similar. I do not presently have any elaborate overrides for thread control methods.
    I desire assistance in correcting this problem. The castrated version essentially is the same as what is currently used at the website except some methods and variable values have been modified for security reasons but otherwise are not relevant to the problem. I suspect that not much code modification will be necessary and I don't think modifications to Are.java, Tare.java and Nve.java are required.
    The solution could actually be relatively simple, but I don't have an IDE to troubleshoot. If the total LOC are not too much to post here, then let me know and I'll post. Otherwise, give me an Email address and I'll convey the code.

    The following code set is the castrated version. Don't get frightened by the amount of code since the majority is commenting and methods dedicated to the calculation and GUI that are not a part of the problem. Who can help me?
    Trajectory.java:
    // Trajectory Analysis Program: Trajectory.java
    //VERSION T1
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
    public class Trajectory extends JApplet implements ActionListener {
         final double MAX = 90.0;
         final double MIN = -90.0;
         final double MAX_ALTITUDE = 2000000.0;
         final double MIN_ALTITUDE = 0.0;
         final double R = 20925643.2;               // earth radius ft
         final double G_SL = 32.174;               // gravity accel: sea lvl (fps)ps
         final double DENSITY_SL = 0.002376899341;     // air dens: sea lvl slugs/cu ft
         final double TEMP_SL = 518.69;               // air temp: sea lvl Rank
         final double PRESS_SL = 2116.199414;          // air press: sea lvl psf
         final static int MAX_TIME = 6000;
         private JTextArea introductionArea, resultsArea;
         private JLabel spanLabel, chordLabel,
              thicknessLabel, massLabel, altitudeLabel, altitude_endLabel, velocityLabel,
              trajectory_angleLabel, time_incrementLabel, rotation_factorLabel,
              calculationLabel, resultsLabel;
         private JTextField spanField, chordField, thicknessField,
              massField, altitudeField, altitude_endField, velocityField,
              trajectory_angleField, time_incrementField, rotation_factorField;
         private JButton startButton, resetButton;
         public JButton two_d_sButton, calcButton, simstartButton, simresetButton;
         double max_alt, max_dis;
         String introduction_string, span_string, chord_string, thickness_string,
              mass_string, altitude_string, altitude_end_string, velocity_string,
              trajectory_angle_string, time_increment_string, rotation_factor_string,
              results_string;
         public String data_area_string;
         public JTextArea data_area;
         public double span, chord, thickness, mass, altitude, altitude_end, velocity,
              trajectory_angle, time_increment, rotation_factor, distance, velocity_fps,
              elapsed_time, temp_Rank, viscosity, density, orbit_dbl, new_distance,
              c_miles, d_min, sec, Joules, Tons_of_TNT, Pounds_of_TNT,
              KiloTons_of_TNT, Hiroshima_Bomb, angleB;
         public boolean value, sentinel, status_2, loop;
         public int orbit, min;
         public static int time_counter, m, n;
         public static double Results_Array[][] = new double[MAX_TIME][6];
         public static boolean scale_type = true;
         public static boolean animate = false;
         public static int max_screen_altitude_scale, max_screen_distance_scale;
         private CardLayout layout = new CardLayout();
         SimulationPanel mSimPanel;
         public static int resultsRIndex = 0;
         public static boolean erase = true;
         public int time_count = 0;
         public int RIndex = 0;
         Timer mAnimationTimer;
         int mCurrentPoint;
          * This main() method allows the applet to be run as a command line application.
          * Please leave it in for future debugging.
          * Use the command line: java Trajectory
         public static void main(String[] args) {
              JFrame mainFrame = new JFrame("Trajectory Simulation");
              mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Trajectory traj = new Trajectory();
              traj.init();
              mainFrame.getContentPane().add(traj, BorderLayout.CENTER);
              mainFrame.pack();
              traj.start();
              mainFrame.setVisible(true);
         // create objects
         public void init()
              span = 0;
              chord = 0;
              thickness = 0;
              mass = 0;
              altitude = 0;
              altitude_end = 0;
              velocity = 0;
              trajectory_angle = 0;
              time_increment = 0;
              rotation_factor = 0;
              distance = 0;
              velocity_fps = 0;
              elapsed_time = 0;
              temp_Rank = 0;               //     air temperature degrees R
              viscosity = 0;               //     air viscosity     
              density = 0;               //     air density
              value = true;
              sentinel = true;
              boolean status_2 = true;     //     short cut condition
              loop = true;
              orbit = 0;
              orbit_dbl = 0.0;
              new_distance = 0.0;
              c_miles = 0.0;
              d_min = 0.0;
              min = 0;
              sec = 0.0;
              Joules = 0.0;
              Tons_of_TNT= 0.0;
              Pounds_of_TNT= 0.0;           
              KiloTons_of_TNT= 0.0;
              Hiroshima_Bomb= 0.0;
              angleB = 0;
              max_dis = 0;
              max_screen_altitude_scale = 0;
              max_screen_distance_scale = 0;
              mCurrentPoint = 0;
              time_counter = 0;
              m = 0;
              n= 0;
              for( m = 0; m < MAX_TIME; m++ )
                   for( n = 0; n < 6; n++ )
                        Results_Array[m][n] = 0;
              Introduction();
              span_string = "";
              chord_string = "";
              thickness_string = "";
              mass_string = "";
              altitude_string = "";
              altitude_end_string = "";
              velocity_string = "";
              trajectory_angle_string = "";           
              time_increment_string = "";
              rotation_factor_string = "";
              results_string = "";
              // create container & panel
              this.getContentPane().setLayout(this.layout);
                       JPanel panelA = new JPanel();
              two_d_sButton = new JButton("2D Simulation");
              // register two_d_sButton event handler
              two_d_sButton.addActionListener(this);
              this.getContentPane().add(panelA, "Calculation");
              panelA.setLayout(new BorderLayout());
              // set up vertical boxlayout
              Box box = Box.createVerticalBox();
              Box inputbox1 = Box.createHorizontalBox();
              Box inputbox2 = Box.createHorizontalBox();
              Box inputbox2a = Box.createHorizontalBox();
              Box inputbox2b = Box.createHorizontalBox();
              Box inputbox2c = Box.createHorizontalBox();
              Box inputbox2d = Box.createHorizontalBox();
              Box inputbox3 = Box.createHorizontalBox();
              Box buttonbox = Box.createHorizontalBox();
              // set up introduction
              introductionArea = new JTextArea( introduction_string, 21, 50 );
              introductionArea.setEditable( false );
              box.add( new JScrollPane( introductionArea ) );
              box.add( Box.createVerticalStrut (10) );
              box.add( inputbox1);
              box.add(inputbox2a);
              Dimension minSize = new Dimension(5, 15);
              Dimension prefSize = new Dimension(5, 15);
              Dimension maxSize = new Dimension(Short.MAX_VALUE, 15);
              inputbox2a.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up span
              spanLabel = new JLabel( "span (feet)" );
              spanField = new JTextField(5 );
              inputbox2a.add( spanLabel );
              inputbox2a.add( spanField );
              inputbox2a.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up chord
              chordLabel = new JLabel( "chord (feet)" );
              chordField = new JTextField(5 );
              inputbox2a.add( chordLabel );
              inputbox2a.add( chordField );
              inputbox2a.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up thickness
              thicknessLabel = new JLabel( "thickness (feet)" );
              thicknessField = new JTextField(5 );
              inputbox2a.add( thicknessLabel );
              inputbox2a.add( thicknessField );
              inputbox2a.add(new Box.Filler(minSize, prefSize, maxSize));
              box.add( Box.createVerticalStrut (10) );
              box.add(inputbox2b);
              inputbox2b.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up mass
              massLabel = new JLabel( "mass (slugs)" );
              massField = new JTextField(5);
              inputbox2b.add( massLabel );
              inputbox2b.add( massField );
              inputbox2b.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up start altitude
              altitudeLabel = new JLabel( "start altitude (feet)");
              altitudeField = new JTextField(5 );
              inputbox2b.add( altitudeLabel );
              inputbox2b.add( altitudeField );
              inputbox2b.add(new Box.Filler(minSize, prefSize, maxSize));
              // set up end altitude
              altitude_endLabel = new JLabel( "end altitude (feet)");
              altitude_endField = new JTextField(5 );
              inputbox2b.add( altitude_endLabel );
              inputbox2b.add( altitude_endField );
              inputbox2b.add(new Box.Filler(minSize, prefSize, maxSize));
              box.add( Box.createVerticalStrut (10) );
              Dimension minSize2c = new Dimension(35, 15);
              Dimension prefSize2c = new Dimension(35, 15);
              Dimension maxSize2c = new Dimension(Short.MAX_VALUE, 15);
              box.add(inputbox2c);
              inputbox2c.add(new Box.Filler(minSize2c, prefSize2c, maxSize2c));
              // set up velocity
              velocityLabel = new JLabel( "velocity (Mach Number)");
              velocityField = new JTextField(5);
              inputbox2c.add( velocityLabel );
              inputbox2c.add( velocityField );
              inputbox2c.add(new Box.Filler(minSize2c, prefSize2c, maxSize2c));
              // set up trajectory_angle
              trajectory_angleLabel = new JLabel( "trajectory angle (degrees)");
              trajectory_angleField = new JTextField(5);
              inputbox2c.add( trajectory_angleLabel );
              inputbox2c.add( trajectory_angleField );
              inputbox2c.add(new Box.Filler(minSize2c, prefSize2c, maxSize2c));
              box.add( Box.createVerticalStrut (10) );
              Dimension minSize2d = new Dimension(50, 15);
              Dimension prefSize2d = new Dimension(50, 15);
              Dimension maxSize2d = new Dimension(Short.MAX_VALUE, 15);
              box.add(inputbox2d);
              inputbox2d.add(new Box.Filler(minSize2d, prefSize2d, maxSize2d));
              // set up time_increment
              time_incrementLabel = new JLabel( "time increment (seconds)" );
              time_incrementField = new JTextField(5);
              inputbox2d.add( time_incrementLabel );
              inputbox2d.add( time_incrementField );
              inputbox2d.add(new Box.Filler(minSize2d, prefSize2d, maxSize2d));
              // set up rotation_factor
              rotation_factorLabel = new JLabel( "rotation factor (number)" );
              rotation_factorField = new JTextField(5);
              inputbox2d.add( rotation_factorLabel );
              inputbox2d.add( rotation_factorField );
              inputbox2d.add(new Box.Filler(minSize2d, prefSize2d, maxSize2d));
              box.add( Box.createVerticalStrut (10) );
              Dimension minSizeB = new Dimension(10, 30);
              Dimension prefSizeB = new Dimension(10, 30);
              Dimension maxSizeB = new Dimension(Short.MAX_VALUE, 30);
              buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
              // set up start button
              startButton = new JButton( "START" );
              buttonbox.add( startButton );
              buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
              // set up reset button
              resetButton = new JButton( "RESET" );
              buttonbox.add( resetButton );
              buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
              // set up 2D Simulation button
              buttonbox.add(two_d_sButton);
              buttonbox.add(new Box.Filler(minSizeB, prefSizeB, maxSizeB));
              box.add( Box.createVerticalStrut (10) );
              box.add( buttonbox);
              // set up results
              resultsArea = new JTextArea( results_string, 9, 50 );
              resultsArea.setEditable( false );
              box.add( new JScrollPane( resultsArea ) );
              // add box to panelA
              panelA.add( box);
              // register event handlers
              spanField.addActionListener( this );
              chordField.addActionListener( this );          
              thicknessField.addActionListener( this );
              massField.addActionListener( this );
              altitudeField.addActionListener( this );
              altitude_endField.addActionListener( this );
              velocityField.addActionListener( this );          
              trajectory_angleField.addActionListener( this );
              time_incrementField.addActionListener( this );
              rotation_factorField.addActionListener( this );
              startButton.addActionListener( this );
              resetButton.addActionListener( this );
              reset();
         } // end method init     
         public void t_r_a_test (double trajectory_angle) throws Tare {   
              if (trajectory_angle > MAX || trajectory_angle < MIN)
                          throw new Tare("\ntrajectory_angle "
                   + trajectory_angle + " is outside of allowable range\n" 
                   + "( " + MIN + " <= trajectory angle <= " + MAX + " )\n\n"
                   + "Try different values for inputs.\n"
                   + "First consider a smaller time increment.\n"
                   + "Other considerations should include using \n"
                   + "a different altitude, trajectory angle or lesser velocity.\n"
                   + "Several types of changes in input values "
                   + "can resolve this problem.");
              if (trajectory_angle > MAX || trajectory_angle < MIN)
                   sentinel = false;
         }  // end method t_r_a_test
         public void a_r_e_test (double altitude) throws Are {   
              if ( altitude > MAX_ALTITUDE )     
                          throw new Are("\naltitude "
                   + altitude + " is outside of allowable range\n\n" 
                   + "( " + MIN_ALTITUDE + " <= altitude <= "
                   + MAX_ALTITUDE + " )\n\n"
                   + "Try different values for inputs.\n"
                   + "First consider a smaller time increment.\n"
                   + "Other considerations should include using \n"
                   + "a different altitude, trajectory angle or lesser velocity.\n"
                   + "Several types of changes in input values "
                   + "can resolve this problem.");
                   if ( altitude > MAX_ALTITUDE )     
                        sentinel = false;
         }  // end method a_r_e_test
         public void n_v_test (boolean value) throws Nve {   
              if ( value == false ){
                   if( span < 0 ){
                         span = 0;
                               throw new Nve("\nValue for "
                        + " span must not be negative\n\n" 
                        + "Try another value ");
                   if( chord < 0 ){
                         chord = 0;
                               throw new Nve("\nValue for "
                        + " chord must not be negative\n\n" 
                        + "Try another value ");
                   if( thickness < 0 ){
                         thickness = 0;
                               throw new Nve("\nValue for "
                        + " thickness must not be negative\n\n" 
                        + "Try another value ");
                   if( mass < 0 ){
                         mass = 0;
                               throw new Nve("\nValue for "
                        + " mass must not be negative\n\n" 
                        + "Try another value ");
                   if( altitude < 0 ){
                        altitude = 0;
                               throw new Nve("\nValue for "
                        + " start altitude must not be negative\n\n" 
                        + "Try another value ");
                   if( altitude_end < 0 ){
                        altitude_end = 0;
                               throw new Nve("\nValue for "
                        + " end altitude must not be negative\n\n" 
                        + "Try another value ");
                   if( velocity < 0 ){
                        velocity = 0;
                               throw new Nve("\nValue for "
                        + " velocity must not be negative\n\n" 
                        + "Try another value ");
                   if( time_increment < 0 ){
                        time_increment = 0;
                               throw new Nve("\nValue for "
                        + " time increment must not be negative\n\n" 
                        + "Try another value ");
                   if( rotation_factor < 0 ){
                        rotation_factor = 0;
                               throw new Nve("\nValue for "
                        + " rotation factor must not be negative\n\n" 
                        + "Try another value ");
              } //end if( value == false )
         }  // end method n_v_test
         // process events
         public void actionPerformed( ActionEvent event )
              // process spanField
              if( event.getSource() == spanField ) {
                   span_string = spanField.getText();
                   span = Double.parseDouble( span_string);
              // process chordField
              if( event.getSource() == chordField ) {
                   chord_string = chordField.getText();
                   chord = Double.parseDouble( chord_string);
              // process thicknessField
              if( event.getSource() == thicknessField ) {
                   thickness_string = thicknessField.getText();
                   thickness = Double.parseDouble( thickness_string);
              // process massField
              if( event.getSource() == massField ) {
                   mass_string = massField.getText();
                   mass = Double.parseDouble( mass_string);
              // process altitudeField
              if( event.getSource() == altitudeField ){
                   altitude_string = altitudeField.getText();
                   altitude = Double.parseDouble( altitude_string);
              // process altitude_endField
              if( event.getSource() == altitude_endField ){
                   altitude_end_string = altitude_endField.getText();
                   altitude_end = Double.parseDouble( altitude_end_string);
              // process trajectory_angleField
              if( event.getSource() == trajectory_angleField ){
                   trajectory_angle_string = trajectory_angleField.getText();
                   trajectory_angle = Double.parseDouble( trajectory_angle_string);
              // process time_incrementField
              if( event.getSource() == time_incrementField ){
                   time_increment_string = time_incrementField.getText();
                   time_increment = Double.parseDouble( time_increment_string);
              // process velocityField
              if( event.getSource() == velocityField ){
                   velocity_string = velocityField.getText();
                   velocity = Double.parseDouble( velocity_string);
              // process rotation_factorField
              if( event.getSource() == rotation_factorField ){
                   rotation_factor_string = rotation_factorField.getText();
                   rotation_factor = Double.parseDouble( rotation_factor_string);
              // process startButton event
              if ( event.getSource() == startButton )
                   if( altitude > MAX_ALTITUDE)
                        reset();
                   strtb();
              // process resetButton event
              if ( event.getSource() == resetButton )
                   reset();
              // process two_d_sButton
              if( event.getSource() == two_d_sButton )
                   Trajectory.this.layout.next(Trajectory.this.getContentPane());
                   String options = "After you perform a simulation you must terminate "
                             + "by using browser back button.\n"
                             + "Then, you can begin a new simulation by "
                             + "mouse clicking the Trajectory Program link again.";
                   JOptionPane.showMessageDialog( null, options);
              // process calcButton
              if( event.getSource() == calcButton )
                   Trajectory.this.layout.previous(Trajectory.this.getContentPane());
              // process simstartButton event
              if ( event.getSource() == simstartButton )
                   strtsim();
              // process simresetButton event
              if ( event.getSource() == simresetButton )
                   resetsim();
              // process a tick from the animation timer
              if (event.getSource() == mAnimationTimer) {
                   mCurrentPoint++;
                   data_area.setText( get_data() );
                   mSimPanel.repaint();
         } // end method actionPerformed
         public String get_data(){
              int index;
              index = mCurrentPoint;
              if(mCurrentPoint >=  time_counter )
                   index = time_counter;
              String time_string = "";
              String dist_string = "";
              int min = 0;
              int sec = 0;
              int fdist = 0;
              int mdist = 0;
              min = (int)Results_Array[ index ][ 0 ] / 60;
              sec = (int)Results_Array[ index ][ 0 ] - (min  * 60);
              mdist = (int)Results_Array[ index ][ 2 ];
              fdist = (int)Results_Array[ index ][ 5 ] - (mdist * 5280);
              if((int)Results_Array[ index ][ 0 ] < 60 )
                   time_string = (int)Results_Array[ index ][ 0 ]  + " sec" ;
              else
                   time_string = min +  " min + " + sec + " sec" ;
              if((int)Results_Array[ index ][ 5 ] < 5280 )
                   dist_string = (int)Results_Array[ index ][ 5 ] + " feet";
              else
                   dist_string = mdist + " miles + " + fdist + " feet";
              data_area_string = "Elapsed Time:  " + time_string
                   + "\tDistance: " + dist_string
                   + "\tAltitude: " + (int)Results_Array[ index ][ 1 ]  + " feet\n"
                   + "Velocity: " + (int)Results_Array[ index ][ 3 ]  + " fps"
                   + "\t\tTrajectory Angle: " + (int)Results_Array[ index ][ 4 ]  + " degrees";
              return data_area_string;
         }  // end method get_data
         public void strtsim(){
              time_count = getPointCount(time_counter);
              erase = true;
              animate = true;
              int delay = 1000;
              mCurrentPoint = 0;
              mAnimationTimer = new Timer(delay, this);
              mAnimationTimer.start();
         } // end method strtsim
          * Returns the current point to be displayed in any ongoing animation.
         public Point getCurrentAnimationPoint() {
              if(scale_type)
                   return new Point((int)Results_Array[mCurrentPoint][2], (int)Results_Array[mCurrentPoint][1]);
              else
                   return new Point((int)Results_Array[mCurrentPoint][5], (int)Results_Array[mCurrentPoint][1]);
         public void resetsim(){
              mAnimationTimer.stop();
              animate = false;
              data_area_string = "";
              data_area.setText( data_area_string );
              reset();
              System.gc();
              System.runFinalization();
         } // end method resetsim
         public int getPointCount(int time_counter_value){
              int point_count = 0;
              point_count = time_counter_value + 1;
              return point_count;
         public void strtb()
              try{          
                   span = Double.parseDouble( spanField.getText() );
                   chord = Double.parseDouble( chordField.getText() );
                   thickness = Double.parseDouble( thicknessField.getText() );
                   mass = Double.parseDouble( massField.getText() );
                   altitude = Double.parseDouble( altitudeField.getText());
                   altitude_end = Double.parseDouble( altitude_endField.getText());
                   velocity = Double.parseDouble( velocityField.getText());
                   trajectory_angle = Double.parseDouble( trajectory_angleField.getText());
                   time_increment = Double.parseDouble( time_incrementField.getText() );     
                   rotation_factor = Double.parseDouble( rotation_factorField.getText() );          
                   // test input
                   if( span < 0 || chord < 0 || thickness < 0 || mass < 0
                        || altitude < 0 || altitude_end < 0 || velocity < 0
                        || time_increment < 0 || rotation_factor < 0 )
                   value = false;
                   t_r_a_test( trajectory_angle );
                   n_v_test( value );
                   a_r_e_test( altitude );
                   // calculate trajectory     
                   calculate( );
                   impact_energy_calc();
                   // set up panelB
                   mSimPanel = new SimulationPanel(this, 0, max_screen_distance_scale, 0, max_screen_altitude_scale);               
                   mSimPanel.setLayout(new FlowLayout());
                   // set up sim box & simbox2
                   Box simbox = Box.createHorizontalBox();
                   Box simbox2 = Box.createHorizontalBox();
                   Dimension minSizesim = new Dimension(10, 30);
                   Dimension prefSizesim = new Dimension(10, 30);
                   Dimension maxSizesim = new Dimension(Short.MAX_VALUE, 30);
                   simbox.add(new Box.Filler(minSizesim,prefSizesim,maxSizesim) );
                   simstartButton = new JButton ( "START" );
                   simbox.add( simstartButton );
                   simbox.add(new Box.Filler(minSizesim,prefSizesim,maxSizesim) );
                   simresetButton = new JButton ( "RESET" );
                   simbox.add( simresetButton );
                   simbox.add(new Box.Filler(minSizesim,prefSizesim,maxSizesim) );
                   calcButton = new JButton("Calculation");
                   simbox.add( calcButton );
                   simbox.add(new Box.Filler(minSizesim,prefSizesim,maxSizesim) );
                   simbox.add( Box.createVerticalStrut (10) );
                   data_area = new JTextArea( data_area_string, 1, 50);
                   data_area.setEditable( false );
                   simbox2.add(data_area);
                   simbox2.add( Box.createVerticalStrut (10) );
                   // add simbox & simbox2 to panelB
                   mSimPanel.add (simbox);
                   mSimPanel.add (simbox2);
                   this.getContentPane().add(mSimPanel, "2D Simulation");
                   // register calcButton event handler
                   calcButton.addActionListener(this);
                   // register simstartButton & simresetButton
                   simstartButton.addActionListener(this);
                   simresetButton.addActionListener(this);
                   // display results for panelA
                   results();
                   resultsArea.setText( results() );
                   String work_string =
                        "The 2D Simulation is a work in progress so functionality is limited.\n"
                        + "It is best to verify the following results' values before beginning 2D Simulation: \n"
                        + "* Elapsed Time greater than 1 second\n"
                        + "* Distance greater than .001 miles\n"
                        + "Check back later for improvements in real time simulation.";
                   JOptionPane.showMessageDialog( null, work_string);
              }//end try
              // process improperly formatted input
              catch ( NumberFormatException numberFormatException ) {
                   JOptionPane.showMessageDialog( this,
                   "You must enter numbers in decimal format or integers"     ,
                   "Invalid Number Format" ,
                   JOptionPane.ERROR_MESSAGE );
              } // end catch NumberFormatException
              catch ( ArithmeticException arithmeticException ) {
                   JOptionPane.showMessageDialog( this,
                   arithmeticException.toString(), "Arithmetic Exception" ,
                   JOptionPane.ERROR_MESSAGE );
              } // end catch ArithmeticException
              catch ( Tare tare ) {
                   JOptionPane.showMessageDialog( this,
                   tare.toString(), "-90 <= range <= 90 " ,
                   JOptionPane.ERROR_MESSAGE );
              } // end catch Tare
              catch ( Nve nve ) {
                   JOptionPane.showMessageDialog( this,
                   nve.toString(), " value less than zero" ,
                   JOptionPane.ERROR_MESSAGE );
              } // end catch Nve
              catch ( Are are ) {
                   JOptionPane.showMessageDialog( this,
                   are.toString(), " value greater than maximum" ,
                   JOptionPane.ERROR_MESSAGE );                    
              } // end catch Are
         }  // end method strtb
         public void reset()
              span_string = "";
              chord_string = "";
              thickness_string = "";
              mass_string = "";
              altitude_string = "";
              altitude_end_string = "";
              velocity_string = "";
              trajectory_angle_string = "";
              time_increment_string = "";
              rotation_factor_string = "";
              results_string = "";
              spanField.setText( span_string );
              chordField.setText( chord_string );
              thicknessField.setText( thickness_string );
              massField.setText( mass_string );
              altitudeField.setText( altitude_string );
              altitude_endField.setText( altitude_end_string );
              velocityField.setText( velocity_string );
              trajectory_angleField.setText( trajectory_angle_string );
              time_incrementField.setText( time_increment_string );
              rotation_factorField.setText( rotation_factor_string );
              resultsArea.setEditable( true );
              resultsArea.setText( results_string );
              resultsArea.setEditable( false );
              span = 0;
              chord = 0;
              thickness = 0;
              mass = 0;
              altitude = 0;
              altitude_end = 0;
              velocity = 0;
              trajectory_angle = 0;
              time_increment = 0;
              rotation_factor = 0;
              distance = 0;
              velocity_fps = 0;
              elapsed_time = 0;
              value = true;
              temp_Rank = 0;
              viscosity = 0;     
              density = 0;
              status_2 = true;
              orbit = 0;
              orbit_dbl = 0.0;
              new_distance = 0.0;
              c_miles = 0.0;
              d_min = 0.0;
              min = 0;
              sec = 0.0;
              Joules = 0.0;
              Tons_of_TNT= 0.0;
              Pounds_of_TNT= 0.0;           
              KiloTons_of_TNT= 0.0;
              Hiroshima_Bomb= 0.0;
              angleB = 0;
              max_dis = 0;
              max_screen_altitude_scale = 0;
              max_screen_distance_scale = 0;
              mCurrentPoint = 0;
              time_counter = 0;
              m = 0;
              n= 0;
              for( m = 0; m < MAX_TIME; m++ )
                   for( n = 0; n < 6; n++ )
                        Results_Array[m][n] = 0;
         }   // end method reset
         public void calculate()
              double     s_x,                         //     distance in x direction
                   s_y,                         //     distance in y direction
                   s_x_old,                    //     distance in x direction(old)
                   g_accel,                    //     local acceleration due to gravity     
                   press,                         //     air pressure          
                   x_velocity,                    //     velocity in x direction
                   y_velocity,                    //     velocity in y direction
                   ratio_R,                    //     term variable gravity               
                   rot_time,                    //     time to next rotation
                   temp_dim_1,                    //     swap variable rotation
                   temp_dim_2,                    //     swap variable rotation
                   temp_dim_3,                    //     swap variable
                   c,                         //       local speed of sound
                   Reynolds,                    //     Reynolds Number
                   Reynolds_old,                    //     Reynolds Number(old)
                   force_drag,                    //     drag force
                   force_drag_x,                    //      drag force in x direction
                   force_drag_y,                    //       drag force in y direction
                   area_normal_to_flow,               //     area_normal_to_flow
                   characteristic_dimension,          //     characteristic_dimension
                   Cd,                         //     drag coefficient               
                   M;                         //     Mach Number
              int count;                         //       counter
              int prior_time;                     //     time_counter - 1
              char test;                         //     character test condition
              boolean set_velocity;                    //     velocity set condition
              boolean change;                         //     rotation change condition
              boolean status_1;                    //     short cut condition     
              boolean status_3;                    //     short cut condition
              String short_cut;                    //     short cut message
              String input;                         //     short cut input
              String altitude_end_error_string;          
              // initialize applicable variables
              s_x = 0;
              s_x_old = 0;
              press = 0;
              x_velocity = 0;
              y_velocity = 0;     
              c = 0;     
              M = 0;
              Reynolds_old = 1;
              Reynolds = 1;
              ratio_R = 1;
              force_drag = 0;
              force_drag_x = 0.0;
              force_drag_y = 0.0;
              change = true;
              set_velocity = true;
              status_1 = true;
              status_3 = true;
              s_y = altitude;
              test = 'Y';
              rot_time = elapsed_time + time_increment * rotation_factor;
              short_cut = "";
              input = "";
              altitude_end_error_string =
                   "Results have a probable error.\n"
                   + "The end altitude value could be too high.\n"
                   + "Reset and try some other values for inputs.";
              count = 0;
              temp_dim_1 = span;
              temp_dim_2 = chord;
              temp_dim_3 = thickness;
              if( altitude < altitude_end && trajectory_angle > 0 )
                   status_2 = false;
              while(s_y > 0.0 && status_2 && sentinel)     
                   // calculate local acceleration due to gravity
                   ratio_R = R /( R + s_y );
                   g_accel = G_SL * Math.pow( ratio_R, 2);
                   // calculate air conditions
                   Calc_Air( s_y );
                   // kinematic reference:
                   // x direction means a direction perpendicular to the
                   // acceleration due to gravity with progression toward
                   // a position at a later time
                   // y direction means a direction having the same direction as
                   // acceleration due to gravity
                   // calculate velocity_fps from initial velocity(Mach Number)
                   // & Reynolds
                   if( set_velocity)
                        c = 49.0 * Math.sqrt(temp_Rank);
                        velocity_fps = velocity * c * 5280/3600;
                        if( trajectory_angle < 0 )
                             velocity_fps = 0 - Math.abs(velocity_fps);
                        // set velocity precision
                        if( trajectory_angle < 0.0000000001 && trajectory_angle > -0.0000000009 )
                             x_velocity = Math.abs(velocity_fps);
                             y_velocity = 0.0;
                        else if( trajectory_angle >= 89.99000000 && trajectory_angle <= 90.0000000)
                             x_velocity = 0.0;
                             y_velocity = Math.abs(velocity_fps);
                        else if( trajectory_angle <= -89.99000000 && trajectory_angle >= -90.0000000)
                             x_velocity = 0.0;
                             y_velocity = 0 - Math.abs(velocity_fps);
                        else
                             if( trajectory_angle >= 0 )
                                  x_velocity = Math.abs(velocity_fps) * Math.cos(Math.abs(trajectory_angle) * Math.PI / 180);
                                  y_velocity = Math.abs(velocity_fps) * Math.sin(Math.abs(trajectory_angle) * Math.PI / 180);
                             else
                                  x_velocity = Math.abs(velocity_fps) * Math.cos(Math.abs(trajectory_angle) * Math.PI / 180);
                                  y_velocity = 0 - Math.abs(velocity_fps) * Math.sin(Math.abs(trajectory_angle) * Math.PI / 180);
                        // calculate Reynolds number
                        Reynolds = Math.abs( density * Math.abs(velocity_fps) * chord / viscosity );
                        set_velocity = false;
                        // add first results to applicable variables for plotting
                        if( elapsed_time == 0)
                             Results_Array[ time_counter ][ 0 ] = (double)time_counter;
                             Results_Array[ time_counter ][ 1 ] = altitude;
                             Results_Array[ time_counter ][ 2 ] = distance /5280;
                             Results_Array[ time_counter ][ 3 ] = velocity_fps;
                             Results_Array[ time_counter ][ 4 ] = trajectory_angle;
                             Results_Array[ time_counter ][ 5 ] = distance;
                             // determine initial maximum altitude for scale plot
                             if(time_counter == 0)
                                  max_screen_altitude_scale = (int)Results_Array[ time_counter ][ 1 ];
                             // determine initial maximum distance for scale plot
                             if(time_counter == 0)
                                  if(scale_type)
                                       max_screen_distance_scale = (int)Res                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Rotate a JLabel

    Hello again!
    I am trying to rotate an image on a JLabel and I feel I am almost there! However the size does not seem to adjust so when I put it on my label it is far too small. The code I am using is below:
      protected ImageIcon poleImage = new ImageIcon("ai/Images/pole.jpg");
      protected Image img = Toolkit.getDefaultToolkit().getImage("ai/Images/pole.jpg");
    public JLabel rotatePole(JLabel lbl)
       Image image;
       ImageIcon icon;
       image = img;
       icon = poleImage;
       int h = image.getHeight(lbl);
       int w = image.getWidth(lbl);
       rad = rad + toRad(30);
       BufferedImage bim = new BufferedImage(h, w, BufferedImage.TYPE_INT_RGB);
       Graphics2D g2d = (Graphics2D)(bim.createGraphics());
       g2d.translate(h, 0);
       g2d.rotate(rad);
       g2d.drawImage(image, 0, 0, w, h, lbl);
       icon = new ImageIcon(bim);
       lbl.setIcon(icon);
       image = bim;
       return(lbl);
    public double toRad(double deg)
         double radians;
         radians = deg * 0.0174532925;
         return(radians);
    }//end toRad()I am defining rad to be zero in the constructor and it sould be increasing by 30 degrees each time I hit the left arrow key. Also the returned lbl goes to the JLabel I use in my JPanel ( poleLbl = pole.rotatePole(poleLbl); )
    What I am seeing is my full size image is replaced by a tiny square. Any help would be appreciated.
    Thanks

    OK. From the code provided by 74philip and the recommended link from camickr I put this together. I get no error messages of any kind.
    I am calling the routine via:
    private void processRKey()
      int offsetR;
      int newXcart;
      int newXpole;
    //The line below is where I am calling the rotation methods
      poleLbl = pole.getLabel();
      poleLblSz = poleLbl.getPreferredSize();
    //I threw this  in to try to re-establish the pole binding but alas no luck
    // buildbindings();
      offsetR = 20;
      newXcart = cart.getXPos()+ offsetR;
      newXpole = pole.getXPos() + offsetR;
      positionLbls(newXcart, cart.getYPos(), newXpole, pole.getYPos());
      cart.setXPos(newXcart);
      pole.setXPos(newXpole);
      System.out.println("R: " + cart.getXPos() + " " + cart.getYPos());
    }//end processRKey() What is happening is that my pole no longer moves in any direction nor does it rotate. My cart is still key-bound and does move left and right in response to arrow key strikes. What follows is my rotation routine.
    public void Rotation()
       ClassLoader cl = Pole.class.getClassLoader();
       try
          bi = ImageIO.read(cl.getResourceAsStream(path));
          image = bi;
       catch(IOException ioE)
          JOptionPane.showMessageDialog(null, "Bufferd Image Load Failure\n");
       //getValue();
    private BufferedImage getImage(double theta)
         double cos = Math.abs(Math.cos(theta));
         double sin = Math.abs(Math.sin(theta));
         double width  = image.getWidth();
         double height = image.getHeight();
         int w = (int)(width * cos + height * sin);
         int h = (int)(width * sin + height * cos);
         BufferedImage out = new BufferedImage(w, h, image.getType());
         Graphics2D g2 = out.createGraphics();
         g2.setPaint(UIManager.getColor("Panel.background"));
         g2.fillRect(0,0,w,h);
         double x = w/2;
         double y = h/2;
         AffineTransform at = AffineTransform.getRotateInstance(theta, x, y);
         x = (w - width)/2;
         y = (h - height)/2;
         at.translate(x, y);
         g2.drawRenderedImage(image, at);
         g2.dispose();
         return out;
    public JLabel getLabel()
         Rotation();
         rad = rad + toRad(30);
         BufferedImage bi = getImage(rad);
         image = bi;
         //tempLbl.setIcon(new ImageIcon(bi));
         ImageIcon icon = new ImageIcon(image);
         tempLbl = new JLabel(icon);
         tempLbl.setHorizontalAlignment(JLabel.CENTER);
         return tempLbl;
    /*private void getValue()
       rad = rad + toRad(30);
       BufferedImage bi = getImage(rad);
       tempLbl.setIcon(new ImageIcon(bi));
    public double toRad(double deg)
         double radians;
         radians = deg * 0.0174532925;
         return(radians);
    }//end toRad()I think it is just something obvious that I am too inexperienced to recognize.
    Thanks for the help earlier, by the way!

  • How can i rotate a PNG photo and keep the transparent background?

    current i use this method to rotate a photo, but the transparent background is lost.
    what can I do ?
    public CreateRotationPhoto(String photofile,String filetype,int rotation_value,String desfile){
                 File fileIn = new File(photofile);
               if (!fileIn.exists()) {
                   System.out.println(" file not exists!");
                   return;
               try {
                       InputStream input = new FileInputStream(fileIn);
                       JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(input);
                       BufferedImage imageSrc = decoder.decodeAsBufferedImage();
                       int width = imageSrc.getWidth();
                       int height = imageSrc.getHeight();
                       BufferedImage src = ImageIO.read(input);
                       int width = src.getWidth(); //????? 
                            int height = src.getHeight(); //????? 
                       Image img = src.getScaledInstance(width, height,
                               Image.SCALE_FAST);
                       BufferedImage bi;
                       int fill_width=0;
                       int fill_height=0;
                       if (rotation_value==1||rotation_value==3){
                            bi = new BufferedImage(height, width,BufferedImage.TYPE_INT_RGB);
                            fill_width=height;
                            fill_height=width;
                       else{
                            bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
                            fill_height=height;
                            fill_width=width;
                            //BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                       input.close();
                       System.out.println(photofile);
                       File fileOut = new File(desfile);
                       //File fileOut = new File("c:/Host1.PNG");
                       OutputStream output = new FileOutputStream(fileOut);
                       JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
                       JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
                       param.setQuality(0.90f, false);
                       encoder.setJPEGEncodeParam(param);
                       Graphics2D biContext =bi.createGraphics();
                      biContext.setColor(Color.white);
                       biContext.fillRect(0,0,fill_width,fill_height);
                       int frame_width,frame_height;
                     if (rotation_value==1||rotation_value==3){
                            frame_width=height;
                            frame_height=width;
                       }else{
                            frame_width=width;
                            frame_height=height;
                       int x=0,y=0;
                       if (rotation_value==2){
                            x=frame_width;
                            y=frame_height;
                       if (rotation_value==0){
                             x=frame_width;
                             y=frame_height;
                       if (rotation_value==1){
                                x=frame_height;
                                 y=frame_height;
                       if (rotation_value==3){
                                    x=frame_width;
                                 y=frame_width;
                       double rotate=0;
                       if (rotation_value==0){
                             rotate=Math.PI *2;
                       if (rotation_value==1){
                            rotate=Math.PI / 2;
                       if (rotation_value==2){
                            rotate=Math.PI;
                       if (rotation_value==3){
                            rotate=Math.PI*1.5;
                       int x=0,y=0;
                       if (rotation_value==2){
                            x=width;
                            y=height;
                       if (rotation_value==1){
                                x=height;
                                 y=height;
                       if (rotation_value==3){
                                    x=width;
                                 y=width;
                       double rotate=0;
                       if (rotation_value==1){
                            rotate=Math.PI / 2;
                       if (rotation_value==2){
                            rotate=Math.PI;
                       if (rotation_value==3){
                            rotate=Math.PI*1.5;
                       System.out.println(Integer.toString(x)+"|x|"+Integer.toString(y)+"|y|"+Double.toString(rotate));
                       biContext.rotate(rotate, x / 2, y / 2);
                       biContext.drawImage(src, 0, 0, null);
                       biContext.dispose();
                       System.out.println("123123123123");
                       try{
                               ImageIO.write(bi, filetype, output);
                               //ImageIO.write(bi, filetype, "c:/Host.PNG");
                               output.close();
                          }catch (IOException e) {
                              System.err.println(e);
                      // encoder.encode(bi);
                       //output.close();
                } catch (Exception e) {
                         e.printStackTrace();
          }

    Using this BufferedImage.TYPE_INT_RGB for the type will eliminate any transparency in
    your image. Try BufferedImage.TYPE_INT_ARGB.
    Image file: Bird.gif
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Rotate implements ChangeListener
        BufferedImage image;
        JLabel label;
        JSlider slider;
        public Rotate(BufferedImage orig)
            // make transparent background
            Color toErase = new Color(248, 248, 248, 255);
            image = eraseColor(convertImage(orig), toErase);
        public void stateChanged(ChangeEvent e)
            int value = slider.getValue();
            double theta = Math.toRadians(value);
            BufferedImage rotated = getImage(theta);
            label.setIcon(new ImageIcon(rotated));
        private BufferedImage getImage(double theta)
            double cos = Math.cos(theta);
            double sin = Math.sin(theta);
            int w = image.getWidth();
            int h = image.getHeight();
            int width  = (int)(Math.abs(w * cos) + Math.abs(h * sin));
            int height = (int)(Math.abs(w * sin) + Math.abs(h * cos));
            BufferedImage bi = new BufferedImage(width, height, image.getType());
            Graphics2D g2 = bi.createGraphics();
            g2.setPaint(new Color(0,0,0,0));
            g2.fillRect(0,0,width,height);
            AffineTransform at = AffineTransform.getRotateInstance(theta, width/2, height/2);
            double x = (width - w)/2;
            double y = (height - h)/2;
            at.translate(x, y);
            g2.drawRenderedImage(image, at);
            g2.dispose();
            return bi;
        private BufferedImage convertImage(BufferedImage in)
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gd = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gd.getDefaultConfiguration();
            BufferedImage out = gc.createCompatibleImage(in.getWidth(), in.getHeight(),
                                                         Transparency.TRANSLUCENT);
            Graphics2D g2 = out.createGraphics();
            g2.drawImage(in, 0, 0, null);
            g2.dispose();
            return out;
        private BufferedImage eraseColor(BufferedImage source, Color color)
            int w = source.getWidth();
            int h = source.getHeight();
            int type = BufferedImage.TYPE_INT_ARGB;
            BufferedImage out = new BufferedImage(w, h, type);
            Graphics2D g2 = out.createGraphics();
            g2.setPaint(new Color(0,0,0,0));
            g2.fillRect(0,0,w,h);
            int target = color.getRGB();
            for(int j = 0; j < w*h; j++)
                int x = j % w;
                int y = j / w;
                if(source.getRGB(x, y) == target)
                    source.setRGB(x, y, 0);
            g2.drawImage(source, 0, 0, null);
            g2.dispose();
            return out;
        private JLabel getLabel()
            label = new JLabel(new ImageIcon(image));
            return label;
        private JSlider getSlider()
            slider = new JSlider(JSlider.HORIZONTAL, 0, 360, 0);
            slider.addChangeListener(this);
            return slider;
        public static void main(String[] args) throws IOException
            String path = "images/Bird.gif";
            ClassLoader cl = Rotate.class.getClassLoader();
            InputStream is = cl.getResourceAsStream(path);
            Rotate rotate = new Rotate(ImageIO.read(is));
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().setBackground(Color.pink);
            f.getContentPane().add(rotate.getLabel());
            f.getContentPane().add(rotate.getSlider(), "South");
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Which is better for drawing JPGs on JLabel: ImageIcon or directly?

    I'm currently using this everywhere.
    BufferedImage bi;
    Jlabel jLabel;
    ImageIcon img = new ImageIcon( bi );
    jLabel.setIcon(imgIcon);but now I've discovered I can write images directly to the component from paintComponent( Graphics g )
    (from a subclass of JLabel)
    public void paintComponent( Graphics g ) {
      super.paintComponent( g );
      Graphics2D g2 = (Graphics2D)g;
      BufferedImage bi=getBufImg();
      g2.drawImage(bi, 0, 0, this.getWidth(), this.getHeight(), null );Is this more efficient or better form? Should I update my code everywhere?
    Also, the latter method seems to work the first time I call it, but I can't seem to change the image on an event like mouseEnter using code like this:
    public void mouseEntered(MouseEvent e) {
      Graphics g = this.getGraphics();
      Graphics2D g2 = (Graphics2D)g;
      BufferedImage bi=getBufImg();
      g2.drawImage(bi, 0, 0, this.getWidth(), this.getHeight(), null );
    }what's wrong?

    Is this more efficient or better form?
    No.
    Should I update my code everywhere?
    It depends on what you want to do. If you want to show an image then ImageIcon is an easy way. Override paintComponent when you want to do something other than simply display the image, eg, write text on top of the image or alter the image with things like rotation and scaling.
    Also, the latter method seems to work the first time I call it, but I can't seem to change the image on an event like mouseEnter using code like this
    Don't put painting code inside event code. Painting/drawing code belongs in an appropriate painting method. Use member variables in the enclosing class for state, manipulate these from your event code and set up your painting method to be able to accurately render this state at any time.
    stephensk8s is correct about the mouseEntered method. It works for components. So using a simple JLabel with ImageIcon is a carefree way to achieve rollover affects.
    Creating this kind of thing for custom graphics and images takes a little more effort. It all depends on what you are trying to do.
    Is there a good place to go to get a better understanding of this, or just ask on this forum?
    Ask when you need help.
    Resources that may be helpful to get started:
    Lesson: Writing Event Listeners
    Lesson: Performing Custom Painting
    How to Use Icons
    Lesson: Working with Images
    Core Java Technologies Tech Tips.

  • Problem in rotating and moving image at the same time

    the problem is that im making a car game(2D) in which u have upper view of car.
    i have make the car rotate bt problem is that i canot move it forward or backward correctly
    .wen i move it forward or backward i goes wrong...
    nd another problem is that i cannot both rotate and move the car at same time
    example if i press both up nd right arrow keys i doesnt move nd rotate..
    nd also plz tell me the accelerate nd reverse method so i can speedup my car like other car games
    here is the code
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.geom.*;
    import java.applet.*;
    import java.net.URL;
    public class RaceGame extends JComponent
    static int x=560;
    static int y=410;
    static int currentAngle=0;
    static double hspeed,vspeed;
    static int carspeed=1;
    Image car;
    //int angle=car.getAngle();
    Image getImage(String filename)
    URL url = getClass().getResource(filename);
    ImageIcon icon = new ImageIcon(url);
    return icon.getImage();
    //Rectangle2D.Float rect=new Rectangle2D.Float(x,y,30,30);
    //Rectangle rect=new Rectangle(x,y,30,30);
    public RaceGame()
    car=getImage("car1.jpeg");
    public void CreateBase()
    JFrame frame=new JFrame("Dare2Race");
    frame.setBounds(70,30,650,500);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container c=frame.getContentPane();
    c.add(new RaceGame());
    frame.addKeyListener(new adapter());
    c.setBackground(Color.BLACK);
    //JLabel finish=new JLabel("FINISH");
    //c.add(finish);
    public void rotate()
    currentAngle+=1;
    if(currentAngle>=360)
    currentAngle=0;
    repaint();
    public void paint(Graphics g)
    super.paint(g);
    Graphics2D g2d=(Graphics2D)g;
    AffineTransform origXform=g2d.getTransform();
    AffineTransform newXform=(AffineTransform)(origXform.clone());
    newXform.rotate(Math.toRadians(currentAngle),x,y);
    g2d.setTransform(newXform);
    g2d.drawImage(car,x,y,this);
    g2d.setTransform(origXform);
    g.setColor(Color.WHITE);
    g.drawLine(640,380,420,380);
    g.drawLine(640,460,320,460);
    g.drawLine(420,380,420,300);
    g.drawLine(320,460,320,380);
    g.drawLine(420,300,125,300);
    g.drawLine(320,380,230,380);
    g.drawLine(230,380,230,460);
    g.drawLine(230,460,2,460);
    g.drawLine(125,300,125,370);
    g.drawLine(125,370,105,370);
    g.drawLine(2,460,2,180);
    g.drawLine(105,370,105,300);
    g.drawLine(2,180,450,180);
    g.drawLine(105,300,105,250);
    g.drawLine(105,250,550,250);
    g.drawLine(550,250,550,20);
    g.drawLine(550,20,275,20);
    g.drawLine(450,180,450,100);
    g.drawLine(450,100,360,100);
    g.drawLine(360,100,360,160);
    g.drawLine(360,160,10,160);
    g.drawLine(10,160,10,30);
    g.drawLine(275,20,275,90);
    g.drawLine(275,90,110,90);
    g.drawLine(110,90,110,30);
    repaint();
    class adapter extends KeyAdapter
    public void keyPressed(KeyEvent e)
    switch(e.getKeyCode())
    case KeyEvent.VK_LEFT:
    currentAngle--;
    repaint();
    break;
    case KeyEvent.VK_RIGHT:
    currentAngle++;
    repaint();
    break;
    case KeyEvent.VK_UP:
    carspeed++;
    hspeed=((double)carspeed)*Math.cos(currentAngle);
    vspeed=((double)carspeed)*Math.sin(currentAngle);
    x = x - (int) hspeed;
    y = y - (int) vspeed;
    repaint();
    break;
    case KeyEvent.VK_DOWN:
    carspeed--;
    hspeed=((double)carspeed)*Math.cos(currentAngle);
    vspeed=((double)carspeed)*Math.sin(currentAngle);
    x = x + (int)hspeed;
    y = y + (int)vspeed;
    repaint();
    break;
    public static void main(String[]args)
    RaceGame race=new RaceGame();
    race.CreateBase();
    //race.setDoubleBuffered(true);
    }

    the problem is that im making a car game(2D) in which u have upper view of car.
    i have make the car rotate bt problem is that i canot move it forward or backward correctly
    .wen i move it forward or backward i goes wrong...
    nd another problem is that i cannot both rotate and move the car at same time
    example if i press both up nd right arrow keys i doesnt move nd rotate..
    nd also plz tell me the accelerate nd reverse method so i can speedup my car like other car games
    plz help me
    here is the code
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.geom.*;
    import java.applet.*;
    import java.net.URL;
    public class RaceGame extends JComponent
    static int x=560;
    static int  y=410;
    static int currentAngle=0;
    static double hspeed,vspeed;
    static  int carspeed=1;
    Image car;
    //int angle=car.getAngle();
    Image getImage(String filename)
    URL url = getClass().getResource(filename);
    ImageIcon  icon = new ImageIcon(url);   
    return icon.getImage();
    //Rectangle2D.Float rect=new Rectangle2D.Float(x,y,30,30);
    //Rectangle rect=new Rectangle(x,y,30,30);
    public RaceGame()
    car=getImage("car1.jpeg");
    public void CreateBase()
    JFrame frame=new JFrame("Dare2Race");
    frame.setBounds(70,30,650,500);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container c=frame.getContentPane();
    c.add(new RaceGame());
    frame.addKeyListener(new adapter());
    c.setBackground(Color.BLACK);
    //JLabel finish=new JLabel("FINISH");
    //c.add(finish);
    public void rotate()
    currentAngle+=1;
    if(currentAngle>=360)
    currentAngle=0;
    repaint();
    public void paint(Graphics g)
    super.paint(g);
    Graphics2D g2d=(Graphics2D)g;
    AffineTransform origXform=g2d.getTransform();
    AffineTransform newXform=(AffineTransform)(origXform.clone());
    newXform.rotate(Math.toRadians(currentAngle),x,y);
    g2d.setTransform(newXform);
    g2d.drawImage(car,x,y,this);
    g2d.setTransform(origXform);
    g.setColor(Color.WHITE);
    g.drawLine(640,380,420,380);
    g.drawLine(640,460,320,460);
    g.drawLine(420,380,420,300);
    g.drawLine(320,460,320,380);
    g.drawLine(420,300,125,300);
    g.drawLine(320,380,230,380);
    g.drawLine(230,380,230,460);
    g.drawLine(230,460,2,460);
    g.drawLine(125,300,125,370);
    g.drawLine(125,370,105,370);
    g.drawLine(2,460,2,180);
    g.drawLine(105,370,105,300);
    g.drawLine(2,180,450,180);
    g.drawLine(105,300,105,250);
    g.drawLine(105,250,550,250);
    g.drawLine(550,250,550,20);
    g.drawLine(550,20,275,20);
    g.drawLine(450,180,450,100);
    g.drawLine(450,100,360,100);
    g.drawLine(360,100,360,160);
    g.drawLine(360,160,10,160);
    g.drawLine(10,160,10,30);
    g.drawLine(275,20,275,90);
    g.drawLine(275,90,110,90);
    g.drawLine(110,90,110,30);
    repaint();
    class adapter extends KeyAdapter
    public void keyPressed(KeyEvent e)
      switch(e.getKeyCode())
        case KeyEvent.VK_LEFT:
        currentAngle--;
        repaint();
        break;
        case KeyEvent.VK_RIGHT:
        currentAngle++;
        repaint();
        break;
        case KeyEvent.VK_UP:
        carspeed++;
        hspeed=((double)carspeed)*Math.cos(currentAngle);
        vspeed=((double)carspeed)*Math.sin(currentAngle);
        x = x - (int) hspeed;
        y = y - (int) vspeed;
        repaint();
        break;
        case KeyEvent.VK_DOWN:
        carspeed--;
        hspeed=((double)carspeed)*Math.cos(currentAngle);
        vspeed=((double)carspeed)*Math.sin(currentAngle);
        x = x + (int)hspeed;
        y = y + (int)vspeed;
        repaint();
        break;
    public static void main(String[]args)
    RaceGame race=new RaceGame();
    race.CreateBase();
    //race.setDoubleBuffered(true);
    }and there is no compile time error in this code
    the only error that occurs when u write java RaceGame is because of the car image which compiler doesnt found and throughs exception if u place any image in ur bin folder adn name it car.jpg it wont generate error

  • Rotate Operator leaves black color around destination image

    Hi Everyone,
    I am creating a JPeg image which has two layers. First one is the background image layer. Second one is the photo which i want to put on the center on the back ground image. I am using overlay operator for this purpose.I have already done this thing.. BUT when i try to rotate the photo then a black color appears (in the area where part of un-rotated image was). I want the background image to be there instead of that black colour..
    I have searched a lot but did not find the solution.. Please help.
    Thanks & Best Regards,
    Masood Ahmad

    Hi,
    It works perfect.. i am doing the same thing using rotate operator in JAI... why that is not working... I am pasting both Rotate programs here.. One is in Java2D and 2nd in JAI.. Java2D is working but JAI rotate is leaving black area after rotation.
    Please tell where i am wrong in JAI or is it bug in JAI?
    Program in JAI
    import java.io.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.net.URL;
    import java.net.MalformedURLException;
    import java.awt.*;
    import java.awt.color.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.awt.image.renderable.*;
    import java.util.*;
    import javax.media.jai.*;
    import javax.media.jai.operator.*;
    import javax.media.jai.widget.*;
    import com.sun.media.jai.codec.*;
    public class RotateTestJAI extends JPanel
    PlanarImage src1 = null;
    PlanarImage src2 = null;
    ImageDisplay ic1 = null;
    public static void main(String any[]) throws Exception{
    JFrame frame = new JFrame();
    frame.add(new RotateTestJAI(any[0],any[1]));
    frame.setSize(800,600);     
    frame.setVisible(true);     
    public RotateTestJAI(String im1, String im2) throws Exception{
    super(true);
    setLayout(new BorderLayout());
         try
                   //scale first image
                   FileSeekableStream stream = new FileSeekableStream(im1);
                   RenderedOp imscaled = JAI.create("stream",stream);
                   Interpolation interp = Interpolation.getInstance(Interpolation.INTERP_BILINEAR);
                   System.out.println("height : "+imscaled.getHeight()+" Width : "+imscaled.getWidth());
                   ParameterBlock params = new ParameterBlock();
                   params.addSource(imscaled);
                   params.add((float)1388/imscaled.getWidth());
                   params.add((float)1641/imscaled.getHeight());
                   params.add(0.00F);
                   params.add(0.00F);
                   params.add(interp);
                   src1 = JAI.create("scale", params );
                   //scale second image
                   stream = new FileSeekableStream(im2);
                   imscaled = JAI.create("stream",stream);
                   interp = Interpolation.getInstance(Interpolation.INTERP_BILINEAR);
                   params = new ParameterBlock();
                   params.addSource(imscaled);
                   params.add((float)400/imscaled.getWidth());
                   params.add((float)300/imscaled.getHeight());
                   params.add(0.00F);
                   params.add(0.00F);
                   params.add(interp);
                   src2 = JAI.create("scale", params );
                   float x = (float)(src1.getHeight()/2)-src2.getHeight();
                   float y = (float)(src1.getWidth()/2)-src2.getWidth();
                   int value = 10;
                   float angle = (float)(value * (Math.PI/180.0F));
                   //Rotate second image          
                   params = new ParameterBlock();
                   params.addSource(src2); // The source image
                   params.add(x); // The x origin
                   params.add(y); // The y origin
                   params.add(angle); // The rotation angle
                   params.add(Interpolation.getInstance(Interpolation.INTERP_BILINEAR)); // The interpolation
                   // Create the rotate operation
                   src2 = JAI.create("Rotate", params, null);
                   //translate 2nd image to bring it in center               
                   params = new ParameterBlock();
                   params.addSource(src2); // The source image
                   params.add((float)Math.max(x, 0)); // The x translation
                   params.add((float)Math.max(y, 0)); // The y translation
                   params.add(Interpolation.getInstance(Interpolation.INTERP_BILINEAR)); // The interpolation
                   // Create the translate operation
                   src2 = JAI.create("translate", params, null);
                   //overlay second image on first image
                   params = new ParameterBlock();     
                   params.addSource(src1);
                   params.addSource(src2);     
              RenderedOp tmp = JAI.create("overlay", params);
                   //put the image on display     
                   ic1=new ImageDisplay(tmp);
              this.add(ic1,BorderLayout.CENTER);
         catch ( MalformedURLException e)
              return;
    Program in Java2D:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class RotationTest implements ActionListener
    BufferedImage bg;
    BufferedImage fg;
    JLabel label;
    double theta;
    double thetaInc;
    public RotationTest(BufferedImage bg, BufferedImage fg)
    this.bg = bg;
    this.fg = fg;
    theta = 0.0;
    thetaInc = Math.PI/6;
    public void actionPerformed(ActionEvent e)
    theta += thetaInc;
    label.setIcon(new ImageIcon(getImage()));
    private BufferedImage getImage()
    int w = bg.getWidth();
    int h = bg.getHeight();
    BufferedImage out = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = out.createGraphics();
    g2.drawRenderedImage(bg, null);
    double width = fg.getWidth();
    double height = fg.getHeight();
    double x = (w - width)/2;
    double y = (h - height)/2;
    AffineTransform at = AffineTransform.getTranslateInstance(x, y);
    at.rotate(theta, width/2, height/2);
    g2.drawRenderedImage(fg, at);
    g2.dispose();
    return out;
    private JLabel getLabel()
    ImageIcon icon = new ImageIcon(getImage());
    label = new JLabel(icon);
    label.setHorizontalAlignment(JLabel.CENTER);
    return label;
    private JPanel getUIPanel()
    JButton rotate = new JButton("rotate");
    rotate.addActionListener(this);
    JPanel panel = new JPanel();
    panel.add(rotate);
    return panel;
    public static void main(String[] args) throws IOException
    ClassLoader cl = RotationTest.class.getClassLoader();
    String path = "images/cougar.jpg";
    BufferedImage one = ImageIO.read(cl.getResourceAsStream(path));
    path = "images/Bird.gif";
    BufferedImage two = ImageIO.read(cl.getResourceAsStream(path));
    RotationTest test = new RotationTest(one, two);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(test.getLabel());
    f.getContentPane().add(test.getUIPanel(), "South");
    f.setSize(400,400);
    f.setLocation(200,200);
    f.setVisible(true);
    }

  • Borderlayout east west rotate

    I'm a beginner, and i would like to ask if there is a way to rotate the view of a hand with cards.
    I want a hand on the north, on the south, on the west (i want to show this vertical) and the east (vertical too)
    Who can help me with this?
    this is my code so far.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    * This is the BlackjackGUI window. The user can play a game of blackjack
    * through this window. The BlackjackGUI creates the players and starts the game.
    * @author Tony Sintes
    public class BlackjackGUI extends JFrame {
    public static void main( String [] args ) {
    JFrame frame = new BlackjackGUI();
    frame.getContentPane().setBackground( FOREST_GREEN );
    frame.setSize( 1024, 860 );
    frame.show();
    private BlackjackDealer dealer;
    private GUIPlayer human;
    private JPanel players = new JPanel( new BorderLayout() );
    private static final Color FOREST_GREEN = new Color( 35, 142, 35 );
    public BlackjackGUI() {
    setUp();
    WindowAdapter wa = new WindowAdapter() {
    public void windowClosing( WindowEvent e ) {
    System.exit( 0 );
    addWindowListener( wa );
    // needs to be protected if subclassed
    private PlayerView getPlayerView( Player p ) {
    PlayerView v = new PlayerView( p );
    v.setBackground( FOREST_GREEN );
    return v;
    // needs to be protected if subclassed
    private void setUp() {
    BlackjackDealer dealer = getDealer();
    PlayerView v1 = getPlayerView( dealer );
    GUIPlayer human = getHuman();
    PlayerView v2 = getPlayerView( human );
    Player safe = getSafePlayer();
    PlayerView v3 = getPlayerView(safe);
    Player onehit = getOneHitPlayer();
    PlayerView v4 = getPlayerView(onehit);
    PlayerView [] views = { v1, v2, v3, v4 };
    // addPlayers( views );
    dealer.addPlayer( human);
    dealer.addPlayer(safe);
    dealer.addPlayer(onehit);
    addOptionView( human, dealer );
    getContentPane().add(players);
    players.setBackground( FOREST_GREEN );
    players.add(v1, BorderLayout.NORTH);
    players.add(v2, BorderLayout.EAST);
    players.add(v3, BorderLayout.WEST);
    players.add(v4, BorderLayout.SOUTH);
    // needs to be protected if subclassed
    // private void addPlayers( PlayerView [] p ) {
    // players.setBackground( FOREST_GREEN );
    // for( int i = 0; i < p.length; i ++ ) {
    // players.add( p );
    // getContentPane().add( players, BorderLayout.CENTER );
    private void addOptionView( GUIPlayer human, BlackjackDealer dealer ) {
    OptionView ov = new OptionView( human, dealer );
    ov.setBackground( FOREST_GREEN );
    getContentPane().add( ov, BorderLayout.SOUTH );
    private BlackjackDealer getDealer() {
    if( dealer == null ) {
    Hand dealer_hand = new Hand();
    Deckpile cards = getCards();
    dealer = new BlackjackDealer( "Dealer", dealer_hand, cards );
    return dealer;
    private GUIPlayer getHuman() {
    if( human == null ) {
    Hand human_hand = new Hand();
    Bank bank = new Bank( 1000 );
    human = new GUIPlayer( "Human", human_hand, bank );
    return human;
    private Player getSafePlayer() {
    // lever zoveel als nodig
    Hand safe_hand = new Hand();
    Bank safe_bank = new Bank (1000);
    return new SafePlayer("Safe", safe_hand, safe_bank);
    private Player getOneHitPlayer() {
    // lever zoveel als nodig
    Hand onehit_hand = new Hand();
    Bank onehit_bank = new Bank (1000);
    return new OneHitPlayer("OneHit", onehit_hand, onehit_bank);
    private Deckpile getCards() {
    Deckpile cards = new Deckpile();
    for( int i = 0; i < 4; i ++ ) {
    cards.shuffle();
    Deck deck = new VDeck();
    deck.addToStack( cards );
    cards.shuffle();
    return cards;
    }

    This requires the font playing cards which you can find on this page.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    public class HandRotation
        Cards cards;
        JPanel table;
        JPanel hand1, hand2, hand3, hand4;
        JPanel[] hands;
        JLabel[] ids;
        int handIndex;   // index into hands for hand in north section
        public HandRotation()
            cards = new Cards();
            table = new JPanel();
            initTable();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(getUIPanel(), "North");
            f.getContentPane().add(new JScrollPane(table));
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
        private JPanel getUIPanel()
            final JButton
                deal   = new JButton("deal"),
                rotate = new JButton("rotate"),
                clear  = new JButton("clear"),
                show   = new JButton("show deck");
            ActionListener l = new ActionListener()
                public void actionPerformed(ActionEvent e)
                    JButton button = (JButton)e.getSource();
                    if(button == deal)
                        dealHand();
                    if(button == rotate)
                        rotateView();
                    if(button == clear)
                        clear();
                    if(button == show)
                        cards.showDeck();
            deal.addActionListener(l);
            rotate.addActionListener(l);
            clear.addActionListener(l);
            show.addActionListener(l);
            JPanel panel = new JPanel();
            panel.add(deal);
            panel.add(rotate);
            panel.add(clear);
            panel.add(show);
            return panel;
        private void initTable()
            // clockwise starting at north position
            hand1 = new JPanel(new GridLayout(1,0));
            hand2 = new JPanel(new GridLayout(0,1));
            hand3 = new JPanel(new GridLayout(1,0));
            hand4 = new JPanel(new GridLayout(0,1));
            hands = new JPanel[] { hand1, hand2, hand3, hand4 };
            handIndex = 0;
            JPanel idPanel = initIDPanel();
            table.setLayout(new BorderLayout());
            // add clockwise
            table.add(hand1, "North");
            table.add(hand2, "East");
            table.add(hand3, "South");
            table.add(hand4, "West");
            table.add(idPanel);
            cards.shuffle();
        private JPanel initIDPanel()
            JPanel panel = new JPanel(new BorderLayout());
            String[] quadrants = { "North", "East", "South", "West" };
            String[] idNames = { "hand 1", "hand 2", "hand 3", "hand 4" };
            ids = new JLabel[idNames.length];
            for(int j = 0; j < ids.length; j++)
                ids[j] = new JLabel(idNames[j]);
                ids[j].setHorizontalAlignment(JLabel.CENTER);
                panel.add(ids[j], quadrants[j]);
                hands[j].setName(idNames[j]);
            return panel;
        private void dealHand()
            for(int j = 0; j < hands.length; j++)
                hands[j].add(cards.deal());
            table.revalidate();
            table.repaint();
        private void rotateView()
            // shift each hand anti-clockwise one position
            //     hands all appear to rotate anti-clockwise with each call
            // remove each hand from table and change the rows/cols in its
            //     GridLayout from (0,1) to (1,0), or from (1,0) to (0,1)
            //     before adding the hand to the next anti-clockwise position
            for(int j = 0; j < hands.length; j++)
                table.remove(hands[j]);
                GridLayout layout = (GridLayout)hands[j].getLayout();
                int rows = layout.getRows();
                int cols = layout.getColumns();
                // to avoid IllegalArgumentException:
                //         "rows and cols cannot both be zero"
                if(rows == 0)
                    layout.setRows(cols);
                    layout.setColumns(rows);
                else
                    layout.setColumns(rows);
                    layout.setRows(cols);
            // next (clockwise) hand goes into north section
            handIndex++;
            if(handIndex > hands.length - 1)
                handIndex = 0;
            // add hands back into new positions in table
            //    and update the ids with names of new hands
            String[] directions = { "North", "East", "South", "West" };
            for(int j = 0; j < hands.length; j++)
                int index = (handIndex + j) % hands.length;
                table.add(hands[index], directions[j]);
                ids[j].setText(hands[index].getName());
            table.revalidate();
            table.repaint();
        private void clear()
            for(int j = 0; j < hands.length; j++)
                hands[j].removeAll();
            table.repaint();
            cards.shuffle();
        public static void main(String[] args)
            new HandRotation();
    class Cards
        List deck;
        Font font;
        int lastCardIndex;
        public Cards()
            font = new Font("playing cards", Font.PLAIN, 72);
            createDeck();
            lastCardIndex = 0;
        public Card deal()
            if(lastCardIndex > deck.size() - 1)
                shuffle();
            return (Card)deck.get(lastCardIndex++);
        public void shuffle()
            Collections.shuffle(deck);
            lastCardIndex = 0;
        public void showDeck()
            JPanel panel = new JPanel(new GridLayout(0,13));
            Font f = font.deriveFont(36f);
            Card card;
            JLabel label;
            for(int j = 0; j < deck.size(); j++)
                card = (Card)deck.get(j);
                label = new JLabel(card.getText());
                label.setForeground(card.getForeground());
                label.setFont(f);
                panel.add(label);
            JOptionPane.showMessageDialog(null, panel);
        private void createDeck()
            deck = new ArrayList();
            String s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            String next;
            Color
                color = Color.black,
                red = new Color(204,0,0);
            for(int j = 0; j < 52; j++)
                if(j == s.length() - 1)
                    next = s.substring(j);
                else
                    next = s.substring(j, j + 1);
                if(j == 26)
                    color = red;
                deck.add(new Card(next, color));
        public class Card extends JLabel
            public Card(String s, Color color)
                super(s);
                setFont(font);
                setForeground(color);
                setHorizontalAlignment(JLabel.CENTER);
    }

  • Flashing & Rotate image problem!

    1) how can i make an image flashing ( appear & disappear ) in JLabel?.
    2)how can i make it rotate?.
    plz need help!

    both questions easily answered by searching the forums - numerous examples

  • Rotate a bob image

    hi,
    I need to rotate a blob image and place it on a JLabel. can anyone help me to do that. it is really urgent
    thx in advance

    Don't multi post! One thread is enough! Locked. I'll delete this later.

Maybe you are looking for