Rotations in applets
how can rotate a picture clockwise or counter-clockwise using applets-URGENT
/* <applet code="RotatingAnImage" width="400" height="400"></applet>
* use: >appletviewer RotatingAnImage.java
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class RotatingAnImage extends JApplet
ImageManager manager;
RotatingImagePanel imagePanel;
public void init()
manager = new ImageManager();
imagePanel = new RotatingImagePanel(manager.getImage());
getContentPane().setLayout(new BorderLayout());
getContentPane().add(getUIPanel(), "North");
getContentPane().add(new JScrollPane(imagePanel));
private JPanel getUIPanel()
final JButton
ccw = new JButton("ccw"),
cw = new JButton("cw"),
save = new JButton("save");
ActionListener l = new ActionListener()
public void actionPerformed(ActionEvent e)
JButton button = (JButton)e.getSource();
if(button == ccw)
imagePanel.rotate(-1);
if(button == cw)
imagePanel.rotate(1);
if(button == save)
manager.save(imagePanel, imagePanel.theta);
ccw.addActionListener(l);
cw.addActionListener(l);
save.addActionListener(l);
JPanel panel = new JPanel();
panel.add(ccw);
panel.add(cw);
panel.add(save);
return panel;
public static void main(String[] args)
JApplet applet = new RotatingAnImage();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(applet);
f.setSize(400,400);
f.setLocation(200,200);
applet.init();
f.setVisible(true);
class RotatingImagePanel extends JPanel
BufferedImage image;
double theta, thetaInc;
public RotatingImagePanel(BufferedImage image)
this.image = image;
theta = 0;
thetaInc = Math.PI/6; // 30 degrees
protected void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
int w = getWidth();
int h = getHeight();
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
int x = (w - imageWidth)/2;
int y = (h - imageHeight)/2;
AffineTransform at = AffineTransform.getTranslateInstance(x, y);
at.rotate(theta, w/2 - x, h/2 - y);
g2.drawRenderedImage(image, at);
public Dimension getPreferredSize()
double cos = Math.abs(Math.cos(theta));
double sin = Math.abs(Math.sin(theta));
int w = (int)(image.getWidth() * cos + image.getHeight() * sin);
int h = (int)(image.getWidth() * sin + image.getHeight() * cos);
return new Dimension(w, h);
public void rotate(int direction)
theta += thetaInc * direction;
revalidate();
repaint();
class ImageManager
BufferedImage image;
public ImageManager()
loadImage();
private void loadImage()
String fileName = "images/redfox.jpg";
try
URL url = getClass().getResource(fileName);
image = ImageIO.read(url);
catch(MalformedURLException mue)
System.err.println("url: " + mue.getMessage());
catch(IOException ioe)
System.err.println("read: " + ioe.getMessage());
public void save(Component c, double theta)
double cos = Math.abs(Math.cos(theta));
double sin = Math.abs(Math.sin(theta));
int w = (int)(image.getWidth() * cos + image.getHeight() * sin);
int h = (int)(image.getWidth() * sin + image.getHeight() * cos);
BufferedImage bi = new BufferedImage(w, h, image.getType());
Graphics2D g2 = bi.createGraphics();
int x = (c.getWidth() - w)/2;
int y = (c.getHeight() - h)/2;
g2.translate(-x, -y);
c.paint(g2);
g2.dispose();
try
ImageIO.write(bi, "png", new File("rotatingAnImage.png"));
catch(IOException ioe)
System.err.println("write: " + ioe.getMessage());
public BufferedImage getImage()
return image;
}
Similar Messages
-
Hi all,,,
I was wondering how i rotate an image. As it stands now, i have the image reference in a variable and i need to know what the proper way is to reference that image with the Graphics2D class. I've tried a few things, but whenever i try to use the rotate method in Graphics2D, it gives me an error.
Perhaps just a short snippet to give me a push in the right direction?
Thanks
KyleThis is my code:
Graphics2D g2;
int rotateD = 90;
int w = paddleImage.getWidth(null) / 2;
int h = paddleImage.getHeight(null) / 2;
g2.rotate(Math.toRadians(rotateD),w,h);
g2.drawImage(paddleImage);and this is my error:
C:\java\projects\SuperPong>javac Paddle.java
Paddle.java:61: cannot resolve symbol
symbol : method drawImage (java.awt.Image)
location: class java.awt.Graphics2D
g2.drawImage(paddleImage);
^any idea what is wrong with the drawImage?
thanks,
Kyle -
hi,
I am doing my project in java.My project is " Online Image Processing ".
I did some processing like gray Scale, Invert , Contrast and rotate 90 degree.
can any one help me for
1. I vant to rotate Image to 1 degree...
2. How to get Blure and Sharpen image?
3. Can i append frames inside applet?
plz Help me ..I did not read the content of the links (To lazy) just found them for you.
You say that the examples use frames:
this should not be a problem as the required code is the same.
Tip:
How whould you display a image in a frame?
How whould you display a image in a applet?
Concentrate on the above 2 and simply change the code accordingly.
This should be easy also try asking google. -
iOS Version: 7.1.2
Browser: Safari
I have a sample log-in page with two input fields and a submit button. When I focus on any of the input fields in landscape mode and rotate my phone and come to the portrait mode I see a weird black space towards the right of my page. Screenshots attached below:
My page code below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />
<title>IOS Test</title>
<style type="text/css">
a, abbr, acronym, address, applet, article, aside, audio, b, blockquote, big, body, center, canvas, caption, cite, code, command, datalist, dd, del, details, dfn, dl, div, dt, em, embed, fieldset, figcaption, figure, font, footer, form, h1, h2, h3, h4, h5, h6, header, hgroup, html, i, iframe, img, ins, kbd, keygen, label, legend, li, meter, nav, object, ol, output, p, pre, progress, q, s, samp, section, small, span, source, strike, strong, sub, sup, table, tbody, tfoot, thead, th, tr, tdvideo, tt, u, ul, var
background: transparent;
border: 0 none;
font-size: 100%;
margin: 0;
padding: 0;
border: 0;
outline: 0;
vertical-align: top;
ol, ul
list-style: none;
blockquote, q
quotes: none;
table, table td
padding: 0;
border: none;
border-collapse: collapse;
img
vertical-align: top;
embed
vertical-align: top;
article, aside, audio, canvas, command, datalist, details, embed, figcaption, figure, footer, header, hgroup, keygen, meter, nav, output, progress, section, source, video, div
display: block;
mark, rp, rt, ruby, summary, time
display: inline;
input, textarea
border: 0;
padding: 0;
margin: 0;
outline: 0;
iframe
border: 0;
margin: 0;
padding: 0;
input, textarea, select
margin: 0;
padding: 0;
body
font-family: Arial, Myriad Pro, Trebuchet MS, sans-serif;
font-size: 100%;
background: #F5F5F5;
a
text-decoration: none;
a:hover
text-decoration: none;
img, object, embed, video
max-width: 100% !important;
.clear
display: block !important;
width: 100% !important;
clear: both !important;
.body
position: fixed;
width: 100%;
top: 0;
left: 0;
overflow-y: scroll;
-ms-overflow-style: -ms-autohiding-scrollbar;
-webkit-overflow-scrolling: touch;
-ms-touch-action: pan-y;
-ms-user-select: none;
z-index: 0;
.body > *
-webkit-transform: translateZ(0px);
.header
background: #fff;
text-align: center;
border-bottom: #45A116 solid 8px;
padding: 5% 10%;
.content
width: 70%;
position: relative;
margin: 20% auto 10% auto;
text-align: center;
.content input
display: block;
background: #E6E6E6;
border-radius: 15px;
border-bottom: #A8A8A8 solid 3px;
margin-bottom: 5%;
width: 96%;
padding: 4% 2%;
text-align: center;
color: #595959;
.content a
display: inline-block;
padding: 2% 10%;
color: #fff;
background: #45A116;
margin-top: 5%;
border-radius: 5px;
border-bottom: #2C690E solid 3px;
-webkit-transition: all 0.1s linear;
-moz-transition: all 0.1s linear;
-ms-transition: all 0.1s linear;
-o-transition: all 0.1s linear;
.content a:active
background:#368011;
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function adjustBody() {
var wh = $(window).height();
$(".body").css({
"height": wh + "px"
$(document).ready(function () {
adjustBody();
$(window).resize(function () {
adjustBody();
</script>
</head>
<body>
<div class="body">
<div class="header">
<img src="sampleImage.png" alt="Sample Logo" />
</div>
<form action="" method="get" id="sampleForm">
<div class="content">
<input type="email" value="User Name" onblur="if($(this)[0].value == ''){$(this)[0].value = 'User Name';}"
onfocus="if($(this)[0].value != '' && $(this)[0].value == 'User Name'){$(this)[0].value = ''};" />
<input type="password" value="Password" onblur="if($(this)[0].value == ''){$(this)[0].value = 'Password';}"
onfocus="if($(this)[0].value != '' && $(this)[0].value == 'Password'){$(this)[0].value = ''};" />
<a href="javascript:void(0);" onclick="$('#sampleForm').submit();">Login</a>
</div>
</form>
</div>
</body>
</html>
Does anyone have any solutions to this problem?
Regards,
Mayank TripathiALWAYS SAVE YOUR idevice USING ICLOUD !!!! IT SAVES ... ALL !! (includings apps data, but the apps themselves ! USE IT ! i done this...)
-
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_aThe 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 -
i'm looking into putting 3d content on the web.
i was thinking of using the 3d api to create an applet which showed a 3d product object which the user could then rotate and which i could load .wml objects (or some3d format) into the applet.
i know this is possible.
but i've read somewhere that in order for the user to use it they must have jre 1.2 and the java 3d extension installed. because java 3d needs java 1.2 VM to run (which i'mled to believe most browsers dont support).
my understanding is that most browsers at most support 1.1 vm which means that if i went ahead i would disenfranchise a large part of my audience (which i am not prepared to do)
the whole reason i decided to go through the java route was because i wanted 3d content on the web without having to have the user download a player in order to view it.
so my question is, assuming what i believe to be true is correct. is it possible to write the sort of 3d applet i want without using the 3d api, and thereby keeping my applet to 1.1 spec and therefore keep my audience?
i'm basically looking for a workaround. i want 3d content, i dont want the user to have to use a player.
any means of doing this i will do
java is'nt really my background i'm just having a bash to solve a problem. so excuse my ignorance if i've written crap
any help would be gratefully received
cheers
if you wish you can email me direct at [email protected]The JRE 1.1 is very common because M$ uses this ancient version. But browserls like Opera and Netscape come together with newer versions of the JRE, at least 1.2 is used here.
I think there is no way to use J3D together with the JRE 1.1 - and it is not recommended to use this much too old java version generally. -
Java Applet not loading in Firefox preview
I am playing around with the classic Java applet "intel
rotating 3d photo cube" and for some reason the applet won't load
when I preview with Firefox. It works fine previewing in Safari and
Opera and even works fine when I open the html file directly
through the finder with Firefox. What could it be? Thanks.
JoshI have exactly the same problem.
(my config is
windows Xp Profesional
jre 1.4.1 03
ie6)
I'm also using zonealarm as a firewall.
any Ideas? -
Rotate Image Created with createImage() ?
I've been looking around online for a way to do this, but so far the only things I have found are 50+ lines of code. Surely there is a simple way to rotate an image created with the createImage() function?
Here's some example code with all the tedious stuff already written. Can someone show me a simple way to rotate my image?
import java.net.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import javax.swing.*;
public class RotImg extends JApplet implements MouseListener {
URL base;
MediaTracker mt;
Image myimg;
public void init() {
try{ mt = new MediaTracker(this);
base = getCodeBase(); }
catch(Exception ex){}
myimg = getImage(base, "myimg.gif");
mt.addImage(myimg, 1);
try{ mt.waitForAll(); }
catch(Exception ex){}
this.addMouseListener(this);
public void paint(Graphics g){
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(myimg, 20, 20, this);
public void mouseClicked(MouseEvent e){
//***** SOME CODE HERE *****//
// Rotate myimg by 5 degrees
//******** END CODE ********//
repaint();
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
}Thanks very much for your help!
null// <applet code="RotationApplet" width="400" height="400"></applet>
// use: >appletviewer RotationApplet.java
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class RotationApplet extends JApplet {
RotationAppletPanel rotationPanel;
public void init() {
Image image = loadImage();
rotationPanel = new RotationAppletPanel(image);
setLayout(new BorderLayout());
getContentPane().add(rotationPanel);
private Image loadImage() {
String path = "images/cougar.jpg";
Image image = getImage(getCodeBase(), path);
MediaTracker mt = new MediaTracker(this);
mt.addImage(image, 0);
try {
mt.waitForID(0);
} catch(InterruptedException e) {
System.out.println("loading interrupted");
return image;
class RotationAppletPanel extends JPanel {
BufferedImage image;
double theta = 0;
final double thetaInc = Math.toRadians(5.0);
public RotationAppletPanel(Image img) {
image = convert(img);
addMouseListener(ml);
public void rotate() {
theta += thetaInc;
repaint();
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
double x = (getWidth() - image.getWidth())/2;
double y = (getHeight() - image.getHeight())/2;
AffineTransform at = AffineTransform.getTranslateInstance(x,y);
at.rotate(theta, image.getWidth()/2, image.getHeight()/2);
g2.drawRenderedImage(image, at);
private BufferedImage convert(Image src) {
int w = src.getWidth(this);
int h = src.getHeight(this);
int type = BufferedImage.TYPE_INT_RGB; // options
BufferedImage dest = new BufferedImage(w,h,type);
Graphics2D g2 = dest.createGraphics();
g2.drawImage(src,0,0,this);
g2.dispose();
return dest;
private MouseListener ml = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
rotate();
} -
So im just starting java, about 12 weeks in.
So in my class we are getting started with objects. What i want to do is create a class called car, and have it create a new car and draw images loaded, and then have the tires rotate, there are 2 images,
the car base and the tires.
I know how to display images in applets, but i dont know how to define the images in the objects class and then draw them from the class.I get errors with this code from my car class
import java.applet.*;
public class car extends Applet{
* @param args
private String model;
private int passangers;
private double gas,speed;
private Image tire;
private MediaTracker tr;
tr = new MediaTracker(this);
tire = getImage(getCodeBase(), "tire.png");
tr.addImage(tire,0);
public car(String id, int pass, double tank)
model=id;
passangers=pass;
gas=tank;
public car()
model="";
passangers=0;
gas=0;
}I get errors on these lines
private Image tire;
private MediaTracker tr;
tr = new MediaTracker(this);
tire = getImage(getCodeBase(), "tire.png");
tr.addImage(tire,0);errors
Severity and Description Path Resource Location Creation Time Id
Image cannot be resolved to a type Car Game car.java line 13 1197077768237 1745
MediaTracker cannot be resolved to a type Car Game car.java line 14 1197077768238 1746
Return type for the method is missing Car Game car.java line 16 1197077768239 1750
Syntax error on token ";", { expected after this token Car Game car.java line 14 1197077768238 1747
Syntax error on token "(", delete this token Car Game car.java line 17 1197077768239 1752
Syntax error on token "0", invalid FormalParameter Car Game car.java line 17 1197077768239 1753
Syntax error on token(s), misplaced construct(s) Car Game car.java line 15 1197077768238 1748
Syntax error on token(s), misplaced construct(s) Car Game car.java line 16 1197077768239 1749
Syntax error on tokens, delete these tokens Car Game car.java line 16 1197077768239 1751
The serializable class car does not declare a static final serialVersionUID field of type long Car Game car.java line 4 1197077768237 1744
The serializable class main does not declare a static final serialVersionUID field of type long Applet main.java line 5 1196990860997 1682
The serializable class main does not declare a static final serialVersionUID field of type long Car Game main.java line 5 1197077768196 1743
The serializable class ShowImage does not declare a static final serialVersionUID field of type long Display JPEG/src ShowImage.java line 4 1196488911896 1393Edited by: jasonpeinko on Dec 7, 2007 5:42 PM -
Applet Won't Receive Focus...Help!
Hello, I am trying to program a Tetris applet, but for some reason I can't move the piece. The arrow keys move and rotate the piece and the space bar drops the piece. The code is too large to fit in a post, but I am including links so that you can see what I'm working with. The actual applet is at http://www.danielbakerdesigns.com/tetris/tetris.htm. There are five Java classes at http://www.danielbakerdesigns.com/tetris/Area.java, http://www.danielbakerdesigns.com/tetris/Board.java, http://www.danielbakerdesigns.com/tetris/Piece.java, http://www.danielbakerdesigns.com/tetris/Tetris.java, and http://www.danielbakerdesigns.com/tetris/Unit.java. Only the Area and Tetris classes are relevant to receiving key events (at least that I'm aware of).
Could somebody please tell me why I can't move my pieces? I've tried everything I can think of (which probably means I am just majorly brain-farting someplace), but nothing seems to work.
Thank you so much for your help!You dont have the error because there may be such class in your local class path.
To solve this, you have to store the class file in correct directories.
In the directory of storing tetris.htm, please create a directory com
You should create directory like this
com/sun/j3d/utils/timercom contain directory called sun. sun contain a directory called utils...
Store J3DTimer in the directory of timer -
How to embed an applet in a JPanel
Hi All,
I am in need of serious help as I have not been able to figure this out for days!!!
All I want to do is to display a runnable applet in a JPanel.
The applet is shown below. Its a ball bouncing around. All I need to do is to embed this in a Jpanel with buttons which will control the movement of the ball in the applet which should be on a Panel. For the life of me I havent figured it out!
Can someone help a brother out!
import java.awt.*;
import javax.swing.*;
import java.applet.Applet;
import java.awt.*;
import javax.swing.JOptionPane;
import javax.swing.*;
import java.awt.event.*;
//Animation Class
class Animation extends Thread {
private Applet appl;
private Color color;
private int increment, vincrement;
private int which;
private int position = 0;
private int vposition = 0;
public int xCenter, yCenter;
private int pause;
private int width, height, speed;
private double distance;
private Dimension[] rotations;
private int currentRotation ;
Animation(Applet a, Color c, int p, int wid, int hei ,int theSpeed, int Start) {
color = c;
appl = a;
pause = p;
width = wid;
height = hei;
speed = theSpeed;
rotations = new Dimension[8];
rotations[0] = new Dimension(1,0);
rotations[1] = new Dimension(1,-1);
rotations[2] = new Dimension(0,-1);
rotations[3] = new Dimension(-1 , -1);
rotations[4] = new Dimension(-1,0);
rotations[5] = new Dimension(-1,1);
rotations[6] = new Dimension(1,0);
rotations[7] = new Dimension(1,1);
currentRotation = Start;
increment = (int)rotations[Start].getWidth();
vincrement = (int)rotations[Start].getHeight();
setSpeed();
public void setSpeed()
{ increment = increment*speed;
vincrement = vincrement * speed;
public void changeRotation(int run, int rise){
increment = run;
vincrement = rise;
setSpeed();
public void rotate(){
currentRotation++;
if (currentRotation == 8)
currentRotation = 0;
changeRotation((int)rotations[currentRotation].getWidth(), (int)rotations[currentRotation].getHeight() );
public void bounce(){
increment = -increment;
public void vBounce(){
vincrement = -vincrement;
public void setColor(Color n)
color = n;
public void run() {
while (true) {
try {
Thread.sleep(pause);
} catch (InterruptedException e) {}
position += increment;
if (position > width - 30 || position <= 0)
{ increment = -increment;
vposition += vincrement;
if (vposition > height - 30 || vposition <= 0)
{ vincrement= -vincrement;
appl.repaint();
public void draw(Graphics g) {
g.setColor(color);
g.fillOval(0 + position, 0 + vposition,30, 30);
setCentre();
public void setCentre(){
xCenter = position - 30/2;
yCenter = vposition -30/2;
public boolean didCollide(Animation x){
distance = Math.sqrt( Math.pow( (xCenter- x.xCenter) ,2) + Math.pow((yCenter-x.yCenter) , 2) );
if (distance <= 31){
return true;
}else return false;
}I took the liberty to make few changes:
the applet:
import java.awt.*;
public class AnimA extends java.applet.Applet
Animation anim;
int p = 70;
int wid = 400;
int hei = 300;
int theSpeed = 2;
int start = 7;
public void init()
setLayout(new BorderLayout());
anim = new Animation(Color.green,p,wid,hei,theSpeed,start);
add("Center",anim);
Panel panel = new Panel();
panel.setBackground(Color.lightGray);
panel.add(new Button("Button 1"));
panel.add(new Button("Button 1"));
add("South",panel);
Thread th = new Thread(anim);
th.start();
the animation
import java.awt.*;
import java.awt.event.*;
//Animation Class
class Animation extends Panel implements Runnable
// private Applet appl;
private Color color;
private int increment, vincrement;
private int which;
private int position = 0;
private int vposition = 0;
public int xCenter, yCenter;
private int pause;
private int width, height, speed;
private double distance;
private Dimension[] rotations;
private int currentRotation ;
Animation(Color c, int p, int wid, int hei ,int theSpeed, int Start)
color = c;
// appl = a;
pause = p;
width = wid;
height = hei;
speed = theSpeed;
rotations = new Dimension[8];
rotations[0] = new Dimension(1,0);
rotations[1] = new Dimension(1,-1);
rotations[2] = new Dimension(0,-1);
rotations[3] = new Dimension(-1 , -1);
rotations[4] = new Dimension(-1,0);
rotations[5] = new Dimension(-1,1);
rotations[6] = new Dimension(1,0);
rotations[7] = new Dimension(1,1);
currentRotation = Start;
increment = (int)rotations[Start].getWidth();
vincrement = (int)rotations[Start].getHeight();
setSpeed();
public void setSpeed()
increment = increment * speed;
vincrement = vincrement * speed;
public void changeRotation(int run, int rise){
increment = run;
vincrement = rise;
setSpeed();
public void rotate()
currentRotation++;
if (currentRotation == 8) currentRotation = 0;
changeRotation((int)rotations[currentRotation].getWidth(), (int)rotations[currentRotation].getHeight() );
public void bounce()
increment = -increment;
public void vBounce()
vincrement = -vincrement;
public void setColor(Color n)
color = n;
public void run()
while (true)
try
Thread.sleep(pause);
catch (InterruptedException e) {}
repaint(position,vposition,31,31);
position += increment;
if (position > width - 30 || position <= 0) bounce();
vposition += vincrement;
if (vposition >= height - 30 || vposition <= 0) vBounce();
repaint(position,vposition,31,31);
public void update(Graphics g)
this.paint(g);
public void paint(Graphics g)
width = getWidth();
height = getHeight()-4;
Rectangle cl = g.getClipBounds();
g.setColor(Color.pink);
g.fillRect(cl.x,cl.y,cl.width,cl.height);
g.setColor(color);
g.fillOval(position,vposition,30,30);
setCentre();
public void setCentre()
xCenter = position - 30/2;
yCenter = vposition -30/2;
public boolean didCollide(Animation x)
distance = Math.sqrt( Math.pow( (xCenter- x.xCenter) ,2) + Math.pow((yCenter-x.yCenter) , 2) );
if (distance <= 31) return true;
else return false;
} Noah -
How to add two objects on scene and how to rotate them?
I am beginer on 3d. I am trying do write applet where are 3x3x3 rubic.
My plans are to have 27 litle cubes. There are 6 flats (9 cubes in a flat) so i have six objects groups. My problem at this moment is that i cant find out how to make two objets. Each of this two objects consists from couple more litle objects. Some of litle objects can be in first and second big object. For example it can be two flats of rubic (corner).
Is anybody have some examples or somehow to hepl me to find out.
Thanks a lotI have code :
import java.applet.Applet;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import com.sun.j3d.utils.applet.MainFrame;
import com.sun.j3d.utils.behaviors.mouse.*;
import com.sun.j3d.utils.universe.SimpleUniverse;
import javax.media.j3d.*;
import javax.vecmath.AxisAngle4f;
import javax.vecmath.Color3f;
import javax.vecmath.Vector3f;
public class RubicApplet extends Applet implements MouseListener
TransformGroup objRotate = null;
public BranchGroup createSceneGraph(SimpleUniverse su,Canvas3D canvas)
// Create the root of the branch graph
BranchGroup objRoot = new BranchGroup();
objRoot.setCapability(BranchGroup.ALLOW_DETACH);
Transform3D transform = new Transform3D();
transform.setRotation(new AxisAngle4f(.5f,1f,1f,.5f));
BoundingSphere behaveBounds = new BoundingSphere();
// create Cube and RotateBehavior objects
objRotate = new TransformGroup(transform);
objRotate.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
objRotate.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
objRotate.setCapability(TransformGroup.ENABLE_PICK_REPORTING);
// Colors
Color3f gray = new Color3f(0.2f,0.2f,0.2f);
Color3f red = new Color3f(1.0f,0.0f,0.0f);
Color3f white = new Color3f(1.0f,1.0f,1.0f);
Color3f yellow = new Color3f(1.0f,1.0f,0.0f);
Color3f green = new Color3f(0.0f,1.0f,0.0f);
Color3f blue = new Color3f(0.0f,0.0f,1.0f);
Color3f purple = new Color3f(1.0f,0.0f,1.0f);
// Object possition
float x=-0.5f;
float y=-0.5f;
float z=-0.5f;
objRoot.addChild(objRotate);
// colors for: back, front, right, left, bottom, top
Color3f[] myColors0 = {white,gray,gray,red,blue,gray};
RCube cube1 = new RCube(myColors0,new Vector3f(x-1,y-1,z-1));
// colors for: back, front, right, left, bottom, top
Color3f[] myColors1 = {gray,gray,gray,red,blue,gray};
RCube cube2 = new RCube(myColors1,new Vector3f(x-1,y-1,z+1));
// colors for: back, front, right, left, bottom, top
Color3f[] myColors2 = {gray,yellow,gray,red,blue,gray};
RCube cube3 = new RCube(myColors2,new Vector3f(x-1,y-1,z+3));
// colors for: back, front, right, left, bottom, top
Color3f[] myColors3 = {white,gray,gray,red,gray,gray};
RCube cube4 = new RCube(myColors3,new Vector3f(x-1,y+1,z-1));
objRotate.addChild(cube1);
objRotate.addChild(cube2);
objRotate.addChild(cube3);
objRotate.addChild(cube4);
MouseRotate myMouseRotate = new MouseRotate();
myMouseRotate.setTransformGroup(objRotate);
myMouseRotate.setSchedulingBounds(new BoundingSphere());
objRoot.addChild(myMouseRotate);
MouseTranslate myMouseTranslate = new MouseTranslate();
myMouseTranslate.setTransformGroup(objRotate);
myMouseTranslate.setSchedulingBounds(new BoundingSphere());
objRoot.addChild(myMouseTranslate);
MouseZoom myMouseZoom = new MouseZoom();
myMouseZoom.setTransformGroup(objRotate);
myMouseZoom.setSchedulingBounds(new BoundingSphere());
objRoot.addChild(myMouseZoom);
// Let Java 3D perform optimizations on this scene graph.
objRoot.compile();
return objRoot;
public RubicApplet()
setLayout(new BorderLayout());
GraphicsConfiguration config =SimpleUniverse.getPreferredConfiguration();
Canvas3D canvas3D = new Canvas3D(config);
canvas3D.addMouseListener(this);
add("Center", canvas3D);
SimpleUniverse simpleU = new SimpleUniverse(canvas3D);
BranchGroup scene = createSceneGraph(simpleU,canvas3D);
simpleU.getViewingPlatform().setNominalViewingTransform();
simpleU.addBranchGraph(scene);
public static void main(String[] args)
Frame frame = new MainFrame(new RubicApplet(), 600, 600);
public void mouseClicked(MouseEvent e)
public void mouseEntered(MouseEvent e)
public void mouseExited(MouseEvent e)
public void mousePressed(MouseEvent e)
public void mouseReleased(MouseEvent e)
I need to rotate with some event two cubes and with some other event rotate three cubes -
I'm new to java 3D and want to create an app that runs both as applet and application. When I load the html I just get the grey background in the browser and a brand new window that runs the program as as application.
When trying to run as an application, I get an empty window followed by another smaller window that runs the app.
import java.applet.Applet;
import java.net.*;
import java.awt.*;
import javax.media.j3d.*;
import javax.vecmath.*;
import com.sun.j3d.utils.geometry.*;
import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.image.TextureLoader;
import com.sun.j3d.utils.applet.MainFrame;
public class ThreeDReels extends Applet {
private BoundingSphere bounds = new BoundingSphere( new Point3d( 0.0,0.0,0.0 ), 200.0 );
public ThreeDReels() {
setLayout(new BorderLayout());
Canvas3D c3d = new Canvas3D(null);
add("Center", c3d);
SimpleUniverse u = new SimpleUniverse( );
BranchGroup bgroot = new BranchGroup( );
TransformGroup tgr1 = setBehaviour(bgroot, 500);
tgr1.addChild(createReel(new Vector3f(0.3f, 0.0f, 0.0f), 0.4f, 0.2f));
TransformGroup tgr2 = setBehaviour(bgroot, 500);
tgr2.addChild(createReel(new Vector3f(0.0f, 0.0f, 0.0f), 0.4f, 0.2f));
TransformGroup tgr3 = setBehaviour(bgroot, 500);
tgr3.addChild(createReel(new Vector3f(-0.3f, 0.0f, 0.0f), 0.4f, 0.2f));
u.getViewingPlatform( ).setNominalViewingTransform( );
addLights( bgroot );
u.addBranchGraph( bgroot );
public BranchGroup createReel(Vector3f position, float diameter, float height)
BranchGroup bg = new BranchGroup( );
Appearance app = new Appearance();
TextureLoader texLoader = new TextureLoader("c:\\javaclasses\\3dreels\\reel1.gif", this);
app.setTexture(texLoader.getTexture());
Transform3D translate = new Transform3D();
Transform3D rotate = new Transform3D();
translate.set(position);
TransformGroup ReelTGT = new TransformGroup(translate);
rotate.rotZ(Math.PI/2.0d);
TransformGroup ReelTGR = new TransformGroup(rotate);
Cylinder reel = new Cylinder(diameter, height, Primitive.GENERATE_TEXTURE_COORDS, app );
ReelTGR.addChild( reel );
ReelTGT.addChild(ReelTGR);
bg.addChild(ReelTGT);
bg.compile();
return bg;
public TransformGroup setBehaviour( BranchGroup bg, int speed )
TransformGroup objTrans = new TransformGroup( );
objTrans.setCapability( TransformGroup.ALLOW_TRANSFORM_WRITE );
Transform3D xAxis = new Transform3D( );
xAxis.rotZ(Math.PI*1.5f); // set axis of rotation
Alpha xAlpha = new Alpha(-1, speed);
RotationInterpolator rotator = new RotationInterpolator(xAlpha, objTrans, xAxis, 0.0f, (float)Math.PI*2.0f);
rotator.setSchedulingBounds(bounds);
objTrans.addChild(rotator);
bg.addChild( objTrans );
return objTrans;
public void addLights( BranchGroup bg )
Color3f color = new Color3f( 1.0f,1.0f,1.0f );
Vector3f direction = new Vector3f( -1.0f,-1.0f,1.0f );
DirectionalLight light = new DirectionalLight( color, direction );
light.setInfluencingBounds(bounds);
bg.addChild( light );
public BranchGroup createBackground( )
BranchGroup backgroundGroup = new BranchGroup( );
Background back = new Background( );
back.setApplicationBounds( bounds );
BranchGroup bgGeometry = new BranchGroup( );
Appearance app = new Appearance( );
Sphere sphere = new Sphere( 1.0f, Primitive.GENERATE_NORMALS_INWARD, app );
bgGeometry.addChild( sphere );
back.setGeometry( bgGeometry );
backgroundGroup.addChild( back );
return backgroundGroup;
public static void main( String[] args )
new MainFrame(new ThreeDReels(), 400, 300);
}replace
SimpleUniverse u = new SimpleUniverse( );
by
SimpleUniverse u = new SimpleUniverse(c3d ); -
Hi I have a simple question,
Is the startup screen of a Java Applet replacable by a custom image or somethimng like that?
I mean the screen you get when the Applet is busy loading. The one with the Java logo in the center with a 'gray-rotating' 18-pointed star behind it.
Kind regards,
KlaasAs part of the applet/object tag, no, I don't think you can.
You could use DHTML to place a different image over the loading applet, and have the applet call back to the webpage, informing it to remove the load image.
Or you can have the base loader very simple (just show image, and use a URLClassLoader to kick start the real applet).
i think you can already get premade versions of this off the net -
Properly (?) Double Buffered Applet is really Choppy
Hi all. I looked around here for the proper way to double buffer an applet, and I think I've got it, but it's realllly choppy when it runs. (It's a little 2d jump 'n run game with not much in it yet). If you have any idea why, please tell =) Thanks!
public class Game extends JApplet implements KeyListener, Runnable
//doublebuffer stuff
Graphics bufferGraphics;
Image offscreenImage;
Dimension dim;
//constants
int SCREEN_WIDTH = 800;
int SCREEN_HEIGHT = 600;
int SPRITE_SIZE = 64;
Color BGColor = Color.white;
int PLAYER_SPEED_X = 10;
int PLAYER_JUMP_SPEED = 20;
int GRAVITY_ACCEL = 1;
//directional constants
int LEFT = -1;
int RIGHT = 1;
int STOPPED = 0;
int UP = -1;
int DOWN = 1;
//images
Image playerImage;
//movement
boolean freeFall = true;
int playerDirX = STOPPED;
int playerVelY = 0;
int playerPosX = 0;
int playerPosY = 0;
//game control variables
boolean gameIsRunning = false;
Thread t;
int i = 0;
public void init()
addKeyListener(this);
gameIsRunning = true;
//prepare offscreen image for double buffering
setSize(800,600);
dim = getSize();
offscreenImage = createImage(dim.width,dim.height);
bufferGraphics = offscreenImage.getGraphics();
playerImage = getImage(getDocumentBase(),"images/playerRight.gif");
t = new Thread(this);
t.start();
public void run()
while(gameIsRunning)
try
t.sleep(33);
catch (InterruptedException e) {}
playerPosX += playerDirX*PLAYER_SPEED_X;
playerPosY -= playerVelY;
if(freeFall)
playerVelY -= GRAVITY_ACCEL;
//wraparound
if(playerPosX < 0)
playerPosX = 0;
if(playerPosX > SCREEN_WIDTH - SPRITE_SIZE)
playerPosX = SCREEN_WIDTH - SPRITE_SIZE;
//stop at the floor
if(playerPosY > SCREEN_HEIGHT - SPRITE_SIZE)
freeFall = false;
playerVelY = 0;
playerPosY = SCREEN_HEIGHT - SPRITE_SIZE;
repaint();
public void keyPressed(KeyEvent e)
//move right
if(e.getKeyCode() == KeyEvent.VK_RIGHT ||
e.getKeyCode() == KeyEvent.VK_D)
playerImage = getImage(getDocumentBase(),"images/playerRight.gif");
playerDirX = RIGHT;
//move left
if(e.getKeyCode() == KeyEvent.VK_LEFT ||
e.getKeyCode() == KeyEvent.VK_A)
playerImage = getImage(getDocumentBase(),"images/playerLeft.gif");
playerDirX = LEFT;
//jump
if(e.getKeyCode() == KeyEvent.VK_SPACE ||
e.getKeyCode() == KeyEvent.VK_W ||
e.getKeyCode() == KeyEvent.VK_UP)
//allow jumping if we're standing on a surface
if(playerPosY == SCREEN_HEIGHT - SPRITE_SIZE ||
playerPosX == 0 ||
playerPosX == SCREEN_WIDTH - SPRITE_SIZE)
if(playerPosX == 0)
playerDirX = RIGHT;
playerImage =
getImage(getDocumentBase(),"images/playerRight.gif");
if(playerPosX == SCREEN_WIDTH - SPRITE_SIZE)
playerDirX = LEFT;
playerImage =
getImage(getDocumentBase(),"images/playerLeft.gif");
freeFall = true;
playerVelY = PLAYER_JUMP_SPEED;
public void keyReleased(KeyEvent e)
//stop moving right
if(e.getKeyCode() == KeyEvent.VK_RIGHT ||
e.getKeyCode() == KeyEvent.VK_D)
if(playerDirX == RIGHT)
playerDirX = STOPPED;
//stop moving left
if(e.getKeyCode() == KeyEvent.VK_LEFT ||
e.getKeyCode() == KeyEvent.VK_A)
if(playerDirX == LEFT)
playerDirX = STOPPED;
public void keyTyped(KeyEvent e)
public void paint(Graphics g)
//clear screen
bufferGraphics.setColor(Color.white);
bufferGraphics.fillRect(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
//draw the player
bufferGraphics.drawImage(playerImage,playerPosX,playerPosY,this);
g.drawImage(offscreenImage,0,0,this);
public void stop()
t.stop();
public void update(Graphics g)
paint(g);
}It looks fine to me, but don't reload the player images every time. If you need a different image you should read up on AffineTransform and do some rotations etc, or at least have the 4 images in an array or something.
P.S. stop is deprecated for threads. If you are done with the thread null it. That being said, if you are making this as an applet, make sure you can restart or reload it properly by testing it with the appletvier.
Good luck in your work.
Maybe you are looking for
-
10.6.2 Server Xsan 2.2.1 and SNFS 3.1.2 MDC
I'm trying to connect an Xserve running 10.6.2 and Xsan 2.2.1 to a Linux MDC running StorNext 3.1.2, but Xsan can't connect to the fsmpm. I receive the following entries in system.log: Feb 25 17:52:49 engOSX106Svr xsand[1186]: Synchronizing with fsmp
-
Dear All I am doing a scenario where I am receiving an asynchronous message in BPM and sending it Synchronously to the external system A. When I get a response from the external system I have to check a condition in BPM and based on that either have
-
How can I prevent finder from popping up when switching spaces
When you switch between spaces with control + arrow keys the finder window in that space becomes the active window. I'd like the order of my windows to remain the same so that I can use several spaces for different sets of apps without the finder win
-
Chart colors in VC 7.20 SP3
Hi, I want to change the chart colors to custom hex-values, not to calender-brown etc. I changed the colors in portal theme of the complex elements table and calendar but the colors in my vc charts did not change. Othe portal theme colors like button
-
Regarding ALV using OOPS Concept
Hi Experts, Can abody explain to me how can i disable some settings in the tool bar of ALV Grid using oops concept??