Juggling Duke Applet
I'm trying to implement a juggling duke program in an applet, but i keep recieveing the following error:
java.lang.NoClassDefFoundError: Juggler (wrong name: sunw/demo/juggler/Juggler)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at sun.applet.AppletClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.applet.AppletClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.applet.AppletClassLoader.loadCode(Unknown Source)
at sun.applet.AppletPanel.createApplet(Unknown Source)
at sun.plugin.AppletViewer.createApplet(Unknown Source)
at sun.applet.AppletPanel.runLoader(Unknown Source)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)Could someone help? Thanx.
I'm trying to implement a juggling duke program in an applet, but i keep recieveing the following error:
java.lang.NoClassDefFoundError: Juggler (wrong name: sunw/demo/juggler/Juggler)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at sun.applet.AppletClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.applet.AppletClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.applet.AppletClassLoader.loadCode(Unknown Source)
at sun.applet.AppletPanel.createApplet(Unknown Source)
at sun.plugin.AppletViewer.createApplet(Unknown Source)
at sun.applet.AppletPanel.runLoader(Unknown Source)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)Could someone help? Thanx.
Similar Messages
-
How to move multiple images in applet
Hi,how to move multiple images in applet or random images in applet .
Means moving images.gif around the applet with different starting point ,help me to create that move method ..why don't you check the tumbling duke applet as provided free in this site? :-)
-
Where are all the .java files????
I placed a few of Oracle's demo JAR and fmb/fmx files on my server to test a couple of things, and they are working fine. (I moved them over to the server by copying the JAR file off my local machine and pasting then into the forms90/java folder on my server. Then I copy and pasted the fmx and fmb files over and created a [this_demo] profile for each one I was using. I also added the .jar to the formsweb.cfg)
Anyways.....
I would like to look at the actual code for one of these demos, but can't find the .java file anywhere. It's not in the JAR file. All that is in the JAR file is META-INF and oracle/forms/demos/enhancedItems2/.class(es) files.
I also downloaded sun's juggling duke JAR file(s) -juggler.jar and methodtracer.jar. I created a test form and got Duke to juggle just fine, but I would like to take a look at the .java code. Where should that be???
Thanks in advanceAn error occured when trying to open the file for reading. Filename: ".\jad\tmp\MOLine.java"
Current Working Directory: C:\Program Files\Cavaj Java Decompiler\
System error message: The system cannot find the file specified.
C++ exception: ios: failbit setDo you get the same error if you use a directory name which has no space in name?
Question is, when I am trying to decompile MOLine.class to produce MOLine.java, why is it looking for MOLine.java?Most probably because you cannot decompile the class file (I believe if it was possible, Oracle would have provided the java file).
Thanks,
Hussein -
Applet not opening in browser Help needed
Hi experts,
I have Java installed in my machine in the path C:\Program Files\Java
While trying to open the link http://www.radinks.com/upload/applet.php in browser, I am being asked to install the missing plugin and that plugin is java.
I do not know why this happens and I am stuck with this problem for sometime.
Any help in this regard will be well appreciated with dukes.
Thanks in advance,
Kind Regards,
Aneesfaheemhameed wrote:
I have the same issue. But this is on Internet Explorer 8. Firefox is fine.Given the [web page does not validate|http://validator.w3.org/check?uri=http%3A%2F%2Fwww.radinks.com%2Fupload%2Fapplet.php&charset=(detect+automatically)&doctype=Inline&group=0] *(<- link),* I am not surprised it fails in some browsers while working in others. Checking the source of the page itself, I notice the applet is embedded in the page using an OBJECT element only, and that possibly also explains why it works in some browsers but not others.
The best bet of the author of the web page is to defer writing the applet element to the [deployJava.js|http://java.sun.com/javase/6/docs/technotes/guides/jweb/deployment_advice.html#deplToolkit] *(<- link)* that is provided by Sun.
Unfortunately there is little that you can do about it, unless you want to attempt creating a page to load off your hard disk, that is valid and workable for IE. I cannot guarantee it will work, but try this variant..
The altered web page, which can be tested at [http://pscode.org/test/radinks/applet.html].
<html>
<body>
<applet
code="com.radinks.dnd.DNDAppletPlus"
archive="dndplus.jar"
codebase="http://www.radinks.com/upload/"
width= "290"
height= "290"
alt="Java is recognised, but disabled!">
<param name="url" value = "http://67.131.250.110/upload.php">
<param name="message" value="http://www.radinks.com/upload/init.html">
<param name="name" value="Rad Upload Plus">
<param name="max_upload" value="10000">
<param name="encode_path" value="yes">
<param name="translate_path" value="yes">
<param name="full_path" value="yes">
This browser does not recognise the Java APPLET element. Get Java from www.java.com.
</applet>
</body>
</html> -
Socket communication failure between Java applet and C++ application
I have a java applet that connects to a C++ application via Java's ServerSocket and Socket objects. THe C++ application is using the Winsock 2 API. The applet and application are running on an NT workstation (SP 6) and using IE (5.5) For a very simple C++ test applications the communictions work fine. Once more code gets added to the C++ application the portion of the socket that C++ listens to seems to close. Upon performing a recv call the return value is a zero. Microsoft insists this is a sign the Java side has shut down the socket. The Java applet can still receive messages from the C++ app but C++ cannot receive responses from the Java side. Java throws no exceptions and an explicit check of the socket shows no errors. Again, what puzzles me is that it works for simple C++ applications. Are there any known conflicts between Java and C++ in this regard?
I have inlcuded the basic java code segments below.
/ run Method.
* This method is called by the Thread.start() method. This
* method is required for the implementation of the Runnable interface
* This method sets up the server side socket communication and
* contiuously loops looking for requests from a external
* socket.
* @author Chris Duke
public void run(){
// create socket connections
boolean success = false;
try {
cServerSocket = new ServerSocket(cPortID);
System.out.println("Waiting for client to connect...");
cClientSocket = cServerSocket.accept();
System.out.println("Client connected");
// Create a stream to read from the client
cInStream = new BufferedReader(new InputStreamReader(
cClientSocket.getInputStream()));
// Create a stream to write to the client
cOutStream = new PrintWriter(
cClientSocket.getOutputStream(), true);
success = true;
}catch (IOException e) {
System.out.println("CommSocket:Run - Socket Exception(1) " + e);
success = false;
// if the socket was successfully created, keep the thread running
while (success){
try{
// check socket to see if it is still available for reading
if (cInStream != null && cInStream.ready()){
// check for an incoming message
String message = ReceiveMessage();
// Send message to listeners
Event(message);
if (cInStream == null){
success = false;
System.out.println("CommSocket:Run - shutdown");
}catch (IOException e){
System.out.println("CommSocket:Run - Socket not ready exception");
break;
// SendMessage method -
* Sends a text message to a connected listener through port specified by portID
* @author Chris Duke
* @param String message - This will be the message sent out through the server
* socket's port specified by portID.
public void SendMessage(String message){
cOutStream.println(message);
if (cOutStream.checkError() == true)
System.out.println("SendMessage : Flush = Error");
else{
System.out.println("SendMessage : Flush - No Error");
}a very simple C++ test applications the communictions work fine. Once more code gets added to the C++ application the portion of the socket that C++ listens to seems to close.
This quite strongly implicates the extra code in the C++ App. The firstly thing I would try would be telnet. Try connecting to both versions of the C++ Application and manually reproducing a proper exchange.
a recv call the return value is a zero. Microsoft insists this is a sign the Java side has shut down the socket.
A correct implementation of recv should return the number of bytes received, or -1 for an error. A zero return indicates no bytes received not a socket closed/error. This sounds like FUD to me.
Are there any known conflicts between Java and C++ in this regard?
I can see no obvious faults, though the code is incomplete, I don't think it's an sockets implementation issue, at either end, it sounds more likely to be a protocol/handshaking bug in the C++ App. -
How can I change oval shape applet to (plot)
Hi this is not my code so, the orignal code is freeware to www.neuralsemantics.com and is Copyright 1989 by Rich Gopstein and Harris Corporation.
The site allows permission to play with the code or ammend it.
how could I modify the applet to display (plot) several cycles of the audio signal instead of the elliptical shape. The amplitude and period of the waveform should change in accordance with the moving sliders
Here is the code from www.neuralsemantics.com /applets/jazz.html
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class JazzMachine extends Applet
implements Runnable, AdjustmentListener, MouseListener {
// program name
final static String TITLE = "The jazz machine";
// Line separator char
final static String LSEP = System.getProperty("line.separator");
// Value range
final static int MIN_FREQ = 1; // min value for barFreq
final static int MAX_FREQ = 200; // max value for barFreq
final static int MIN_AMPL = 0; // min value for barVolume
final static int MAX_AMPL = 100; // max value for barVolume
// Sun's mu-law audio rate = 8KHz
private double rate = 8000d;
private boolean audioOn = false; // state of audio switch (on/off)
private boolean changed = true; // change flag
private int freqValue = 1; // def value of frequency scrollbar
private int amplValue = 70; // def value of volume scrollbar
private int amplMultiplier = 100; // volume multiplier coeff
private int frequency, amplitude; // the requested values
private int soundFrequency; // the actual output frequency
// the mu-law encoded sound samples
private byte[] mu;
// the audio stream
private java.io.InputStream soundStream;
// graphic components
private Scrollbar barVolume, barFreq;
private Label labelValueFreq;
private Canvas canvas;
// flag for frequency value display
private boolean showFreq = true;
// width and height of canvas area
private int cw, ch;
// offscreen Image and Graphics objects
private Image img;
private Graphics graph;
// dimensions of the graphic ball
private int ovalX, ovalY, ovalW, ovalH;
// color of the graphic ball
private Color ovalColor;
// default font size
private int fontSize = 12;
// hyperlink objects
private Panel linkPanel;
private Label labelNS;
private Color inactiveLinkColor = Color.yellow;
private Color activeLinkColor = Color.white;
private Font inactiveLinkFont = new Font("Dialog", Font.PLAIN, fontSize);
private Font activeLinkFont = new Font("Dialog", Font.ITALIC, fontSize);
// standard font for the labels
private Font ctrlFont;
// standard foreground color for the labels
private Color fgColor = Color.white;
// standard background color for the control area
private Color ctrlColor = Color.darkGray;
// standard background color for the graphic ball area
private Color bgColor = Color.black;
// start value for the time counter
private long startTime;
// maximum life time for an unchanged sound (10 seconds)
private long fixedTime = 10000;
// animation thread
Thread runner;
// Constructors
public JazzMachine() {
// Methods
public void init() {
// read applet <PARAM> tags
setAppletParams();
// font for the labels
ctrlFont = new Font("Dialog", Font.PLAIN, fontSize);
// convert scrollbar values to real values (see below for details)
amplitude = (MAX_AMPL - amplValue) * amplMultiplier;
frequency = (int)Math.pow(1.2d, (double)(freqValue + 250) / 10.0);
setLayout(new BorderLayout());
setBackground(ctrlColor);
setForeground(fgColor);
Label labelVolume = new Label(" Volume ");
labelVolume.setForeground(fgColor);
labelVolume.setAlignment(Label.CENTER);
labelVolume.setFont(ctrlFont);
barVolume = new Scrollbar(Scrollbar.VERTICAL, amplValue, 1,
MIN_AMPL, MAX_AMPL + 1);
barVolume.addAdjustmentListener(this);
// assign fixed size to the scrollbar
Panel pVolume = new Panel();
pVolume.setLayout(null);
pVolume.add(barVolume);
barVolume.setSize(16, 90);
pVolume.setSize(16, 90);
Label labelFreq = new Label("Frequency");
labelFreq.setForeground(fgColor);
labelFreq.setAlignment(Label.RIGHT);
labelFreq.setFont(ctrlFont);
barFreq = new Scrollbar(Scrollbar.HORIZONTAL, freqValue, 1,
MIN_FREQ, MAX_FREQ);
barFreq.addAdjustmentListener(this);
// assign fixed size to the scrollbar
Panel pFreq = new Panel();
pFreq.setLayout(null);
pFreq.add(barFreq);
barFreq.setSize(140, 18);
pFreq.setSize(140, 18);
// show initial frequency value
labelValueFreq = new Label();
if (showFreq) {
labelValueFreq.setText("0000000 Hz");
labelValueFreq.setForeground(fgColor);
labelValueFreq.setAlignment(Label.LEFT);
labelValueFreq.setFont(ctrlFont);
Panel east = new Panel();
east.setLayout(new BorderLayout(10, 10));
east.add("North", labelVolume);
Panel pEast = new Panel();
pEast.add(pVolume);
east.add("Center", pEast);
Panel south = new Panel();
Panel pSouth = new Panel();
pSouth.setLayout(new FlowLayout(FlowLayout.CENTER));
pSouth.add(labelFreq);
pSouth.add(pFreq);
pSouth.add(labelValueFreq);
south.add("South", pSouth);
linkPanel = new Panel();
this.composeLink();
Panel west = new Panel();
// dummy label to enlarge the panel
west.add(new Label(" "));
add("North", linkPanel);
add("South", south);
add("East", east);
add("West", west);
add("Center", canvas = new Canvas());
private void composeLink() {
linkPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 5));
linkPanel.setFont(inactiveLinkFont);
linkPanel.setForeground(Color.yellow);
Label labelName = new Label(TITLE + " \u00a9");
labelName.setForeground(inactiveLinkColor);
labelName.setAlignment(Label.RIGHT);
labelNS = new Label(" Neural Semantics ");
labelNS.setForeground(inactiveLinkColor);
labelNS.setFont(inactiveLinkFont);
labelNS.setAlignment(Label.LEFT);
linkPanel.add(labelName);
linkPanel.add(labelNS);
// link to Neural Semantics website
String h = getDocumentBase().getHost();
if ((h.length() > 4) && (h.substring(0, 4).equals("www.")))
h = h.substring(4);
if ((h != null) && (! h.startsWith("neuralsemantics.com"))) {
// create a hand cursor for the hyperlink area
Cursor linkCursor = new Cursor(Cursor.HAND_CURSOR);
linkPanel.setCursor(linkCursor);
labelName.addMouseListener(this);
labelNS.addMouseListener(this);
private void switchAudio(boolean b) {
// switch audio to ON if b=true and audio is OFF
if ((b) && (! audioOn)) {
try {
sun.audio.AudioPlayer.player.start(soundStream);
catch(Exception e) { }
audioOn = true;
// switch audio to OFF if b=false and audio is ON
if ((! b) && (audioOn)) {
try {
sun.audio.AudioPlayer.player.stop(soundStream);
catch(Exception e) { }
audioOn = false;
private void getChanges() {
// create new sound wave
mu = getWave(frequency, amplitude);
// show new frequency value
if (showFreq)
labelValueFreq.setText((new Integer(soundFrequency)).toString() + " Hz");
// shut up !
switchAudio(false);
// switch audio stream to new sound sample
try {
soundStream = new sun.audio.ContinuousAudioDataStream(new
sun.audio.AudioData(mu));
catch(Exception e) { }
// listen
switchAudio(true);
// Adapt animation settings
double prop = (double)freqValue / (double)MAX_FREQ;
ovalW = (int)(prop * cw);
ovalH = (int)(prop * ch);
ovalX = (int)((cw - ovalW) / 2);
ovalY = (int)((ch - ovalH) / 2);
int r = (int)(255 * prop);
int b = (int)(255 * (1.0 - prop));
int g = (int)(511 * (.5d - Math.abs(.5d - prop)));
ovalColor = new Color(r, g, b);
// start the timer
startTime = System.currentTimeMillis();
// things are fixed
changed = false;
// Thread
public void start() {
// create thread
if (runner == null) {
runner = new Thread(this);
runner.start();
public void run() {
// infinite loop
while (true) {
// Volume or Frequency has changed ?
if (changed)
this.getChanges();
// a touch of hallucination
repaint();
// let the children sleep. Shut up if inactive during more
// than the fixed time.
if (System.currentTimeMillis() - startTime > fixedTime)
switchAudio(false);
// let the computer breath
try { Thread.sleep(100); }
catch (InterruptedException e) { }
public void stop() {
this.cleanup();
public void destroy() {
this.cleanup();
private synchronized void cleanup() {
// shut up !
switchAudio(false);
// kill the runner thread
if (runner != null) {
try {
runner.stop();
runner.join();
runner = null;
catch(Exception e) { }
// AdjustmentListener Interface
public void adjustmentValueChanged(AdjustmentEvent e) {
Object source = e.getSource();
// Volume range : 0 - 10000
// ! Scrollbar value range is inverted.
// ! 100 = multiplier coefficient.
if (source == barVolume) {
amplitude = (MAX_AMPL - barVolume.getValue()) * amplMultiplier;
changed = true;
// Frequency range : 97 - 3591 Hz
// ! Scrollbar value range represents a logarithmic function.
// The purpose is to assign more room for low frequency values.
else if (source == barFreq) {
freqValue = barFreq.getValue();
frequency = (int)Math.pow(1.2d, (double)(freqValue + 250) / 10.0);
changed = true;
// MouseListener Interface
public void mouseClicked(MouseEvent e) {
public void mouseEntered(MouseEvent e) {
// text color rollover
labelNS.setForeground(activeLinkColor);
labelNS.setFont(activeLinkFont);
showStatus("Visit Neural Semantics");
public void mouseExited(MouseEvent e) {
// text color rollover
labelNS.setForeground(inactiveLinkColor);
labelNS.setFont(inactiveLinkFont);
showStatus("");
public void mousePressed(MouseEvent e) {
try {
java.net.URL url = new java.net.URL("http://www.neuralsemantics.com/");
AppletContext ac = getAppletContext();
if (ac != null)
ac.showDocument(url);
catch(Exception ex){ }
public void mouseReleased(MouseEvent e) {
// Painting
public void update(Graphics g) {
Graphics canvasGraph = canvas.getGraphics();
if (img == null) {
// get canvas dimensions
cw = canvas.getSize().width;
ch = canvas.getSize().height;
// initialize offscreen image
img = createImage(cw, ch);
graph = img.getGraphics();
// offscreen painting
graph.setColor(bgColor);
graph.fillRect(0, 0, cw, ch);
graph.setColor(ovalColor);
graph.fillOval(ovalX, ovalY, ovalW, ovalH);
// canvas painting
if (canvasGraph != null) {
canvasGraph.drawImage(img, 0, 0, canvas);
canvasGraph.dispose();
// Sound processing
// Creates a sound wave from scratch, using predefined frequency
// and amplitude.
private byte[] getWave(int freq, int ampl) {
int lin;
// calculate the number of samples in one sinewave period
// !! change this to multiple periods if you need more precision !!
int nSample = (int)(rate / freq);
// calculate output wave frequency
soundFrequency = (int)(rate / nSample);
// create array of samples
byte[] wave = new byte[nSample];
// pre-calculate time interval & constant stuff
double timebase = 2.0 * Math.PI * freq / rate;
// Calculate samples for a single period of the sinewave.
// Using a single period is no big precision, but enough
// for this applet anyway !
for (int i=0; i<nSample; i++) {
// calculate PCM sample value
lin = (int)(Math.sin(timebase * i) * ampl);
// convert it to mu-law
wave[i] = linToMu(lin);
return wave;
private static byte linToMu(int lin) {
int mask;
if (lin < 0) {
lin = -lin;
mask = 0x7F;
else {
mask = 0xFF;
if (lin < 32)
lin = 0xF0 | 15 - (lin / 2);
else if (lin < 96)
lin = 0xE0 | 15 - (lin-32) / 4;
else if (lin < 224)
lin = 0xD0 | 15 - (lin-96) / 8;
else if (lin < 480)
lin = 0xC0 | 15 - (lin-224) / 16;
else if (lin < 992)
lin = 0xB0 | 15 - (lin-480) / 32;
else if (lin < 2016)
lin = 0xA0 | 15 - (lin-992) / 64;
else if (lin < 4064)
lin = 0x90 | 15 - (lin-2016) / 128;
else if (lin < 8160)
lin = 0x80 | 15 - (lin-4064) / 256;
else
lin = 0x80;
return (byte)(mask & lin);
// Applet info
public String getAppletInfo() {
String s = "The jazz machine" + LSEP + LSEP +
"A music synthetizer applet" + LSEP +
"Copyright (c) Neural Semantics, 2000-2002" + LSEP + LSEP +
"Home page : http://www.neuralsemantics.com/";
return s;
private void setAppletParams() {
// read the HTML showfreq parameter
String param = getParameter("showfreq");
if (param != null)
if (param.toUpperCase().equals("OFF"))
showFreq = false;
// read the HTML backcolor parameter
bgColor = changeColor(bgColor, getParameter("backcolor"));
// read the HTML controlcolor parameter
ctrlColor = changeColor(ctrlColor, getParameter("controlcolor"));
// read the HTML textcolor parameter
fgColor = changeColor(fgColor, getParameter("textcolor"));
// read the HTML fontsize parameter
param = getParameter("fontsize");
if (param != null) {
try {
fontSize = Integer.valueOf(param).intValue();
catch (NumberFormatException e) { }
private Color changeColor(Color c, String s) {
if (s != null) {
try {
if (s.charAt(0) == '#')
c = new Color(Integer.valueOf(s.substring(1), 16).intValue());
else
c = new Color(Integer.valueOf(s).intValue());
catch (NumberFormatException e) { e.printStackTrace(); }
return c;
}thanks LIZ
PS If you can help how do I Give the Duke dollers to youhttp://www.google.ca/search?q=java+oval+shape+to+plot&hl=en&lr=&ie=UTF-8&oe=UTF-8&start=10&sa=N
Ask the guy who made it for more help -
How do I convert my GUI java app to be an applet or display it on a webpage
I have created a loan calculator program in netbeans, I got the application to run fine but now I want to add it into a html page.
I'm just looking for a place to start, I just don't know where to go from here, I want to know if I can actually convert my app with a few changes to an applet or if any one can point me to a forum of similar interest or tutorials that explain what I'm looking for.
I don't even know what i'm looking for except i want this program to run on a webpage.
Or is there a way to run my .jar file on a webpage??
My teacher has not taught us anything on this matter except the below code suggestions on converting and my program is more extensive than her examples for converting. This is what she briefly described on this subject.
1.To convert an application to an applet the main differences are: import java.awt.Graphics; import javax.swing.JApplet; import javax.swing.JOptionPane;
Extend JApplet Replace main with public void init() method
Output with public void paint( Graphics g ) method
2. Remove calls to setSize, setTitle, pack, and any window listener calls, e.g., setDefaultCloseOperation. Compile the program---if something doesn't compile just comment it out for now.
3. Create a simple web page with the following body.
<applet CODE="__________.class" WIDTH="300" HEIGHT="300"
archive="http://www.cs.duke.edu/courses/fall01/cps108/resources/joggle.jar">
Your browser does not support applets </applet>
I understand those steps for a simple program like hello world but not my current app
Heres my code on the 2 extend off my first GUI of the Loan Application
public class AnalysisGUI extends GUI {
/** Creates new form AnalysisGUI */
public AnalysisGUI(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}//end constructor
private DecimalFormat currency = new DecimalFormat("0.00");
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
analysisjButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
writejTextArea = new javax.swing.JTextArea();
clearTextAreajButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
analysisjButton.setText("Analysis");
analysisjButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
analysisjButtonActionPerformed(evt);
writejTextArea.setColumns(20);
writejTextArea.setRows(5);
jScrollPane1.setViewportView(writejTextArea);
clearTextAreajButton.setText("Clear Analysis Output");
clearTextAreajButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearTextAreajButtonActionPerformed(evt);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(analysisjButton)
.addComponent(clearTextAreajButton))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 433, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(86, 86, 86))
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(306, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(analysisjButton)
.addGap(84, 84, 84)
.addComponent(clearTextAreajButton)
.addGap(113, 113, 113))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 263, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(22, 22, 22))))
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-700)/2, (screenSize.height-627)/2, 700, 627);
}// </editor-fold>
private void analysisjButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//importing values for FOR loop of 13 pyaments a years
ir13 = super.rate;
balance13 = super.balance;
time13 = super.time;
payment13 = MortgageCalculator.CalculatePayment(ir13, balance13, time13, PayperYear13);
interest13 = round((balance13 * (ir13/PayperYear13)));
principle13 = round(payment13 - interest13);
//set up for 12 pyaments a year
balance = super.balance;
ir = super.rate;
time = super.time;
payment = super.payment;
interest = round((balance * (ir/PayperYear12)));
principle = round(payment - interest);
//set up for 24 payments a year
balance24 = super.balance;
ir24 = super.rate;
time24 = super.time;
payment24 = super.payment/2;
interest24 = round((balance24 * (ir/PayperYear24)));
principle24 = round(payment24 - interest24);
//set up for 26 payemnts a years
ir26 = super.rate;
balance26 = super.balance;
time26 = super.time;
payment26 = MortgageCalculator.CalculatePayment(ir26, balance26, time26, PayperYear26);
interest26 = round((balance26 * (ir26/PayperYear26)));
principle26 = round(payment26 - interest26);
double totalPrinciple = 0; //set to zero
double totalInterest = 0; //set to zero
for( int n = 0; n < time; n++) //check Year of Loan
totalPrinciple = 0; //reset to zero for totaling Year n totals
totalInterest = 0; //reset to zero for totaling Year n totals
writejTextArea.append("-----Based on 12 Payments Per Year-----\n");
writejTextArea.append(" "+" "+"Principle" + " " +
"Interest"+ " "+
"Balance"+"\n");
//loops through the monthly payments
for(int i = 1; i <= PayperYear12; i++ )
//Calculate applied amounts for chart to be printed
interest = round((balance * ir)/PayperYear12);
principle = round(payment - interest);
balance = round(balance - principle);
//total year end amounts
totalPrinciple = totalPrinciple + principle;
totalInterest = totalInterest + interest;
writejTextArea.append("Payment " + i + " $" + currency.format(principle) + " " +
currency.format(interest) + " $" +
currency.format(balance)+"\n");
}//end for 12 payments per year
//print 12 payments Totals
int yr = n + 1;
writejTextArea.append("\n---Year " + yr + " Totals Based on 12 Payments Per Year---");
writejTextArea.append("\nYear Total Principle: $" + currency.format(totalPrinciple));
writejTextArea.append("\nYear Total Interest: $" + currency.format(totalInterest));
writejTextArea.append("\nRemaining Balance: $" + currency.format(balance)+"\n");
writejTextArea.append("\n-------------------------------------------------------\n");
//Start 13 PAYMENTS A YEAR TABLE
double totalPrinciple13 = 0; //reset to zero for totaling Year n totals
double totalInterest13 = 0; //reset to zero for totaling Year n totals
writejTextArea.append("-----Based on 13 Payments Per Year-----\n");
writejTextArea.append(" "+" "+"Principle" + " " +
"Interest"+ " "+
"Balance"+"\n");
//loops through the monthly 13 payments
for(int j = 1; j <= PayperYear13; j++ )
//Calculate applied amounts for chart to be printed
interest13 = round((balance13 * ir13)/PayperYear13);
principle13 = round(payment13 - interest13);
balance13 = round(balance13 - principle13);
//total year end amounts
totalPrinciple13 = totalPrinciple13 + principle13;
totalInterest13 = totalInterest13 + interest13;
//System.out.printf("\n%-10s %-10s %-10s %-10s %-10s", n + 1 , i + 1,Principle, Interest, Balance);
//System.out.printf("\n%-10s %-10s %-10.2f %-10.2f %-10.2f", n + 1 , i + 1,round(principle), round(interest), balance);
writejTextArea.append("Payment " + j + " $" + currency.format(principle13) + " " +
currency.format(interest13) + " $" +
currency.format(balance13)+"\n");
}//end for 13 payments per year
//Print totals for 13 payments a year
yr = n + 1;
writejTextArea.append("\n---Year " + yr + " Totals Based on 13 Payments Per Year---");
writejTextArea.append("\nYear Total Principle: $" + currency.format(totalPrinciple13));
writejTextArea.append("\nYear Total Interest: $" + currency.format(totalInterest13));
writejTextArea.append("\nRemaining Balance: $" + currency.format(balance13)+"\n");
writejTextArea.append("\n-------------------------------------------------------\n");
//Start 24 PAYMENTS A YEAR TABLE
double totalPrinciple24 = 0; //reset to zero for totaling Year n totals
double totalInterest24 = 0; //reset to zero for totaling Year n totals
writejTextArea.append("-----Based on 24 Payments Per Year-----\n");
writejTextArea.append(" "+" "+"Principle" + " " +
"Interest"+ " "+
"Balance"+"\n");
//loops through the monthly payments
for(int i = 1; i <= PayperYear24; i++ )
//Calculate applied amounts for chart to be printed
interest24 = round((balance24 * ir24)/PayperYear24);
principle24 = round(payment24 - interest24);
balance24 = round(balance24 - principle24);
//total year end amounts
totalPrinciple = totalPrinciple + principle24;
totalInterest = totalInterest + interest24;
writejTextArea.append("Payment " + i + " $" + currency.format(principle24) + " " +
currency.format(interest24) + " $" +
currency.format(balance24)+"\n");
}//end for 24 payments per year
//print 24 payments Totals
yr = n +1;
writejTextArea.append("\n---Year " + yr + " Totals Based on 24 Payments Per Year---");
writejTextArea.append("\nYear Total Principle: $" + currency.format(totalPrinciple24));
writejTextArea.append("\nYear Total Interest: $" + currency.format(totalInterest24));
writejTextArea.append("\nRemaining Balance: $" + currency.format(balance24)+"\n");
writejTextArea.append("\n-------------------------------------------------------\n");
//Start 26 PAYMENTS A YEAR TABLE
double totalPrinciple26 = 0;//reset to zero for totaling Year n totals
double totalInterest26 = 0; //reset to zero for totaling Year n totals
writejTextArea.append("------Based on 26 Payments Per Year-----\n");
writejTextArea.append(" "+" "+"Principle" + " " +
"Interest"+ " "+
"Balance"+"\n");
//loops through the monthly payments 26 times
for(int i = 1; i <= PayperYear26; i++ )
//Calculate applied amounts for chart to be printed
interest26 = round((balance26 * ir24)/PayperYear26);
principle26 = round(payment26 - interest26);
balance26 = round(balance26 - principle26);
totalPrinciple = totalPrinciple + principle26;
totalInterest = totalInterest + interest26;
writejTextArea.append("Payment " + i + " $" + currency.format(principle26) + " " +
currency.format(interest26) + " $" +
currency.format(balance26)+"\n");
}//end for 26 payments per year
yr = n + 1;
//prints 26 payments yearly totals
writejTextArea.append("\n---Year " + yr + " Totals Based on 26 Payments Per Year---");
writejTextArea.append("\nYear Total Principle: $" + currency.format(totalPrinciple26));
writejTextArea.append("\nYear Total Interest: $" + currency.format(totalInterest26));
writejTextArea.append("\nRemaining Balance: $" + currency.format(balance26)+"\n");
writejTextArea.append("\n-------------------------------------------------------\n");
}//end for years of the loan
private void clearTextAreajButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//clear analysis field
writejTextArea.setText("");
public static double round(double r)//round to cents method
return Math.ceil(r*100)/100;
}//end round
/**HI micha what a long progam
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
AnalysisGUI dialog = new AnalysisGUI(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
dialog.setVisible(true);
});//end announymous
}//end main mehtod
//12 year declared varialbes
//private double balance;
private double principle;
private double ir;
private double interest;
private double PayperYear12 = 12;
//Variables for 13 payments a years
private int PayperYear13 = 13;
private double balance13;
private double principle13;
private double ir13;
private double interest13;
private double payment13;
private double time13;
//Varialbes for 24 payments a year
private int PayperYear24 = 24;
private double balance24;
private double principle24;
private double ir24;
private double interest24;
private double payment24;
private double time24;
//Varialbes for 24 payments a year
private int PayperYear26 = 26;
private double balance26;
private double principle26;
private double ir26;
private double interest26;
private double payment26;
private double time26;
// Variables declaration - do not modify
private javax.swing.JButton analysisjButton;
private javax.swing.JButton clearTextAreajButton;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea writejTextArea;Your original program extends "GUI" which appears to extend JFrame (correct me if I'm wrong). If so, the first thing you should do would be to re-write this so that it extends JPanel which shouldn't be that hard to do (at least it's not hard to do if you know a little Swing -- but I worry about someone coming into this from the netbeans-generated code world). Purists will tell you to not even extend this, to have your main GUI class hold an instance of JPanel instead, and this would work fine too, as long as one way or another, the main GUI program can produce your application displayed on a JPanel on demand.
If you've done this correctly, then using your JPanel in a JFrame is trivial: in a main method create a JFrame, and then simply add your JPanel to the JFrame's contentPane and display it. Likewise using your JPanel in a JApplet is just as trivial as you'd do essentially the same thing: add your JPanel to the JApplet's contentPane, but this time do it in the JApplet's init method. -
Jbutton in applet not appearing when embedded in webpage(jre1.6.0_02)
Hi,
I am accessing a webcam from an applet embedded in a webpage using JMF 2.1. I am using JButtons using Image Icons. When i view the applet using applet viewer both the player and buttons appear fine. However when the applet is embedded in a jsp page the image JButtons don't appear at all. I am using jre1.6.0_02.
Following is the code( The capture and cancel JButtons dont appear when viewed in webpage):
import java.awt.*;
import java.io.*;
//import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.*;
import java.net.URL;
import java.net.URLConnection;
import javax.media.format.*;
import javax.media.control.*;
import javax.media.util.*;
import javax.media.*;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class WebCamUnit extends JApplet implements ActionListener
static final long serialVersionUID = -116069779446114664L;
private static final String FILENAME_HEADER = "fileName";
private static final String FILELASTMOD_HEADER = "fileLastMod";
public static Player player = null;
public CaptureDeviceInfo captureDeviceInfo = null;
public MediaLocator ml = null;
public JButton captureButton, cancelButton = null;
public Buffer buf = null;
public Image img = null;
public VideoFormat vf = null;
public BufferToImage btoi = null;
public Component comp;
public static boolean isTrue = true;
public JPanel buttonPanel, playerPanel;
public static String localDirectoryName = null;
public static String serverDirectoryName = null;
public static String servletURL = null;
public static String localImageName = null;
public static String serverImageName = null;
String webCamDriverName = null;
String middleButtonFilename = "TakePicture.JPG";
String frontButtonFilename = "Cancel.JPG";
public void init()
localImageName = getParameter("LOCAL_IMAGE_NAME");
serverImageName = getParameter("SERVER_IMAGE_NAME");
localDirectoryName = getParameter("LOCAL_DIRECTORY_NAME");
serverDirectoryName = getParameter("SERVER_DIRECTORY_NAME");
servletURL = getParameter("SERVLET_URL");
webCamDriverName = getParameter("WEBCAM_DRIVER_NAME");
setLayout(new BorderLayout());
setSize(320, 340);
ImageIcon middleButtonIcon = new ImageIcon(middleButtonFilename);
ImageIcon frontButtonIcon = new ImageIcon(frontButtonFilename);
captureButton = new JButton(middleButtonIcon);
cancelButton = new JButton(frontButtonIcon);
captureButton.setBackground(Color.WHITE);
captureButton.setContentAreaFilled(false);
captureButton.setBorderPainted(false);
captureButton.setFocusPainted(false);
captureButton.addActionListener(this);
captureButton.setEnabled(true);
cancelButton.setBackground(Color.WHITE);
cancelButton.setContentAreaFilled(false);
cancelButton.setBorderPainted(false);
cancelButton.setFocusPainted(false);
cancelButton.addActionListener(this);
cancelButton.setEnabled(true);
buttonPanel = new JPanel();
buttonPanel.add(captureButton);
buttonPanel.add(cancelButton);
buttonPanel.setBackground(Color.WHITE);
getContentPane().add(buttonPanel, BorderLayout.CENTER);
if(null==webCamDriverName)
webCamDriverName = "vfw:Microsoft WDM Image Capture (Win32):2";
captureDeviceInfo = CaptureDeviceManager.getDevice(webCamDriverName);
ml = captureDeviceInfo.getLocator();
try
player = Manager.createRealizedPlayer(ml);
catch (Exception e)
try
player.start();
catch (Exception e)
public void destroy()
player.close();
public void start()
try
if ((comp = player.getVisualComponent()) != null)
playerPanel = new JPanel();
comp.setBounds(0, 0, 320, 240);
playerPanel.add(comp);
getContentPane().add(playerPanel, BorderLayout.NORTH);
player.start();
catch (Exception e)
setVisible(true);
invalidate();
repaint();
public boolean action(Event e, Object o)
return true;
public void paint(Graphics g)
super.paint(g);
public static void playerclose()
player.close();
player.deallocate();
public void actionPerformed(ActionEvent e)
JComponent c = (JComponent) e.getSource();
if (c == captureButton)
player.stop();
FrameGrabbingControl fgc = (FrameGrabbingControl) player
.getControl("javax.media.control.FrameGrabbingControl");
buf = fgc.grabFrame();
btoi = new BufferToImage((VideoFormat) buf.getFormat());
img = btoi.createImage(buf);
String newDir = localDirectoryName;
boolean success = (new File(newDir)).mkdirs();
String imageServername = localDirectoryName + localImageName;
saveJPG(img, imageServername);
isTrue = false;
else
if ((comp = player.getVisualComponent()) != null)
getContentPane().add(comp, BorderLayout.NORTH);
player.start();
isTrue = true;
public void stop()
player.stop();
player.deallocate();
getContentPane().removeAll();
public static void saveJPG(Image img, String s)
img = img.getScaledInstance(160, 120, 1);
BufferedImage bi = new BufferedImage(img.getWidth(null), img
.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bi.createGraphics();
g2.drawImage(img, 0, 0, null, null);
FileOutputStream out = null;
try
out = new FileOutputStream(s);
catch (java.io.FileNotFoundException io)
String message = "File Not Found";
JOptionPane pane = new JOptionPane(message);
JDialog dialog = pane.createDialog(new JFrame(), "Dilaog");
dialog.show();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
param.setQuality(0.50f, false);
encoder.setJPEGEncodeParam(param);
try
encoder.encode(bi);
out.close();
try
transferFile(localDirectoryName+localImageName,serverImageName,"",-1);
catch (Exception e1)
String message = "Error occurred while transferring image to server!!";
JOptionPane pane = new JOptionPane(message);
JDialog dialog = pane.createDialog(new JFrame(), "Dilaog");
dialog.show();
String message = "Image saved successfully!!";
JOptionPane pane = new JOptionPane(message);
JDialog dialog = pane.createDialog(new JFrame(), "Dilaog");
dialog.show();
catch (java.io.IOException io)
String message = "Error occurred while saving image!!";
JOptionPane pane = new JOptionPane(message);
JDialog dialog = pane.createDialog(new JFrame(), "Dilaog");
dialog.show();
catch (Exception e)
// this method transfers the prescribed file to the server.
// if the destination directory is "", it transfers the file to "d:\\".
//11-21-02 Changes : This method now has a new parameter that references the item
//that is being transferred in the import list.
public static String transferFile(String srcFileName, String
destFileName,
String destDir, int itemID)
if (destDir.equals(""))
destDir = serverDirectoryName;
// get the fully qualified filename and the mere filename.
String fqfn = srcFileName;
String fname = fqfn.substring(fqfn.lastIndexOf(File.separator)+1);
try
//importTable importer = jbInit.getImportTable();
// create the file to be uploaded and a connection to servlet.
File fileToUpload = new File(fqfn);
long fileSize = fileToUpload.length();
// get last mod of this file.
// The last mod is sent to the servlet as a header.
long lastMod = fileToUpload.lastModified();
String strLastMod = String.valueOf(lastMod);
URL serverURL = new URL(servletURL);
URLConnection serverCon = serverURL.openConnection();
// a bunch of connection setup related things.
serverCon.setDoInput(true);
serverCon.setDoOutput(true);
// Don't use a cached version of URL connection.
serverCon.setUseCaches (false);
serverCon.setDefaultUseCaches (false);
// set headers and their values.
serverCon.setRequestProperty("Content-Type",
"application/octet-stream");
serverCon.setRequestProperty("Content-Length",
Long.toString(fileToUpload.length()));
serverCon.setRequestProperty(FILENAME_HEADER, destDir + destFileName);
serverCon.setRequestProperty(FILELASTMOD_HEADER, strLastMod);
// if (webadminApplet.DEBUG) System.out.println("Connection with FTP server established");
// create file stream and write stream to write file data.
FileInputStream fis = new FileInputStream(fileToUpload);
OutputStream os = serverCon.getOutputStream();
try
// transfer the file in 4K chunks.
byte[] buffer = new byte[4096];
long byteCnt = 0;
//long percent = 0;
int newPercent = 0;
int oldPercent = 0;
while (true)
int bytes = fis.read(buffer);
byteCnt += bytes;
//11-21-02 :
//If itemID is greater than -1 this is an import file transfer
//otherwise this is a header graphic file transfer.
if (bytes < 0) break;
os.write(buffer, 0, bytes);
os.flush();
//if (webadminApplet.DEBUG) System.out.println("No of bytes sent: " + byteCnt);
finally
// close related streams.
os.close();
fis.close();
// if (webadminApplet.DEBUG) System.out.println("File Transmission complete");
// find out what the servlet has got to say in response.
BufferedReader reader = new BufferedReader(
new
InputStreamReader(serverCon.getInputStream()));
try
String line;
while ((line = reader.readLine()) != null)
// if (webadminApplet.DEBUG) System.out.println(line);
finally
// close the reader stream from servlet.
reader.close();
} // end of the big try block.
catch (Exception e)
System.out.println("Exception during file transfer:\n" + e);
e.printStackTrace();
return("FTP failed. See Java Console for Errors.");
} // end of catch block.
return("File: " + fname + " successfully transferred.");
} // end of method transferFile().
}>
I am accessing a webcam from an applet embedded in a webpage using JMF 2.1. I am using JButtons using Image Icons. When i view the applet using applet viewer both the player and buttons appear fine. However when the applet is embedded in a jsp page the image JButtons don't appear at all. >That is probably because of security. Add 10 Dukes to the thread to indicate you are serious about resolving this, and I might expand on that answer. -
Finding and retrieving an XML file from an application and an applet
I have a problem.
I have data stored in an XML file. I want to be able to call that file and store it into a document object from an application standing alone on a computer as weel as from an applet that would be running over the web.
I don't know how to do this.
When I use a relative path name for the application it attaches the path of the folder that contains java.exe. I could do something with the class path but this wouldn't help the end user of the application on a different computer. For similar reasons I don't want to hard code because I don't know where the final applet will be stored.
I have a table that holds, sorts and filters the data so I want the table to collect the data, I don't want to dictate the path from the applet or the application, I want a method that is consistant with both scenarios.
Can anyone offer some advice?I've just finished trying it out, here is what I did:
String xmlDocName="filename.xml";
java.net.URL fileURL=this.getClass().getResource(xmlDocName);
private final String fileName = fileURL.toString().substring(6);
The substring removes the "file:/" from the URL.
This works fine in the IDE, I have even stored the xml file in a lower folder e.g. package_folder/xml_folder/filename.xml and replaced the xmlDocName with "xml_folder/filename.xml" and it worked fine.
I haven't tried it in an applet because I'm running IE and as you are well aware there are problems with swing and IE applets. But you answer deserves the Duke Dollars, thank you very much. -
hi there,
I am a student at the University of Portsmouth in the UK in my third and last year. I am doing my dissertation as a game using applets for a client at the university of which there consits four prototypes. One of the main specification points is that it should work on an apple mac, therefore I am using Swing applets. however with my first prototype it works fine on windows in windows Explorer, firefox and Netscape but i cant get it to work on Mac os 9 or X even with the latest version of java installed on the machine. Can anyone tell me why this is so, I would be very gratefull.
As I cant post the whole applet here as a file download I will just put some code snippets of the main program classes.
Applet ------------------------------
* Class JugglingBalls - A sub class of JApplet that combines the GameInterface and GamePanel into a single application
* @author (Liam Morren)
* @version (v1.0)
import java.awt.*;
import javax.swing.*;
public class JugglingBalls extends JApplet
// instance variables -----------------------------------------------------------------------------------------------------------------------------------
private GamePanel gamePanel; // The game panel including game and render loop
private GameInterface gameInterface; // The swing interface to modify the game scene components
// JApplet methods -------------------------------------------------------------------------------------------------------------------------------------
* Called by the browser or applet viewer to inform this JApplet that it
* has been loaded into the system. It is always called before the first
* time that the start method is called.
public void init()
gamePanel = new GamePanel();
gameInterface = new GameInterface(gamePanel.getGameScene());
Container content = getContentPane(); // The container for components in the applet
setLayout(new BoxLayout(content, BoxLayout.X_AXIS));
content.add(gamePanel);
content.add(gameInterface);
* Returns information about this applet.
* An applet should override this method to return a String containing
* information about the author, version, and copyright of the JApplet.
* @return a String representation of information about this JApplet
public String getAppletInfo()
// provide information about the applet
return "Title: JugglingBalls \nAuthor: Liam Morren \nA simple application showing balls juggling in the air.";
Interface -------------------------------------
* Class GameInterface - Lets you manipulate the game components using swing components
* @author (Liam Morren)
* @version (v1.0)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class GameInterface extends JPanel
// instance variables -------------------------------------------------------------------------------------------------------------------------------------
private GameScene gameScene; // Reference to the game scene
private JTabbedPane gameTabs; // Tabs for Game, Balls and Background
// Scene panel
JButton pause, start, reset; // Buttons
// Balls panel
JRadioButton redBall, greenBall, blueBall, archBall, figureOfEightBall; // Radio buttons
JCheckBox canSplit; // Check box
JComboBox setAllPaths, setAllTypes, newBall, selectBall; // Drop down boxes
JButton deleteBall; // Button
Ball currentBall; // Current ball being changed
// Background panel
JRadioButton black, white, red, green, blue, hide, show, stop, move, arch, figureOfEight; // Radio buttons
// Constructors -------------------------------------------------------------------------------------------------------------------------------------------
* Constructor for objects of class GameInterface
public GameInterface(GameScene gameSceneIn)
gameScene = gameSceneIn; // Reference to the game scene
gameTabs = new JTabbedPane(); // JTabbedPane to hold different toolbars
gameTabs.setPreferredSize(new Dimension(200, 494)); // Set the preffered size for the tabbed pane
currentBall = gameScene.getBall(0); // First ball
// Add the panels to the tabbed pane
gameTabs.addTab("Scene", makeScenePanel());
gameTabs.addTab("Balls", makeBallsPanel());
gameTabs.addTab("Background", makeBackgroundPanel());
add(gameTabs); // Add the tab to the game interface panel
setPreferredSize(new Dimension(200, 200));
// Other methods ------------------------------------------------------------------------------------------------------------------------------------------
* makeScenePanel
* @return JPanel - The scene panel with buttons added
private JPanel makeScenePanel()
// Make scene panel
JPanel scenePanel = new JPanel();
scenePanel.setLayout(new BoxLayout(scenePanel, BoxLayout.Y_AXIS)); // Change layout
pause = new JButton("Pause"); // Make buttons
start = new JButton("Start");
reset = new JButton("Reset");
// Add button actions
pause.addActionListener(new ActionListener() // Add button listener to pause button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
gameScene.setPaused(true); // Pause game
start.addActionListener(new ActionListener() // Add button listener to start button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
gameScene.setPaused(false); // Unpause game
reset.addActionListener(new ActionListener() // Add button listener to reset button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
gameScene.reset(); // Reset game
updateSelectBallComboBox();
changeSelectedBall(0);
scenePanel.add(pause); // Add buttons to scene panel
scenePanel.add(start);
scenePanel.add(reset);
return scenePanel;
* makeBackgroundPanel
* @return JPanel - The background panel with buttons added
private JPanel makeBackgroundPanel()
// Make scene panel
JPanel backgroundPanel = new JPanel();
backgroundPanel.setLayout(new GridLayout(5, 1, 2, 2)); // Change layout
// Make buttons
// background colour buttons
JPanel backgroundcolour = new JPanel(); // Change backgroundcolour panel
backgroundcolour.setBorder(BorderFactory.createLineBorder(Color.black));
black = new JRadioButton("Black"); // Radio buttons to change colour
white = new JRadioButton("white");
black.setSelected(true); // Set black as already selected
ButtonGroup backColourGroup = new ButtonGroup(); // Group buttons so only one can be pressed at a time
backColourGroup.add(black); // Add buttons to group
backColourGroup.add(white);
backgroundcolour.setLayout(new GridLayout(2, 2, 0, 0)); // Change layout
backgroundcolour.add(new JLabel("Background colour")); // Add label
backgroundcolour.add(black); // Add buttons to colours panel
backgroundcolour.add(white);
// Add radio button actions
black.addActionListener(new ActionListener() // Add button listener to black button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
gameScene.setBackgroundColour(false); // Background colour = black
white.addActionListener(new ActionListener() // Add button listener to white button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
gameScene.setBackgroundColour(true); // Background colour = white
// colour buttons
JPanel colours = new JPanel(); // Change colours panel
colours.setBorder(BorderFactory.createLineBorder(Color.black));
red = new JRadioButton("Red"); // Radio buttons to change colour
green = new JRadioButton("Green");
green.setSelected(true); // Set green as already selected
blue = new JRadioButton("Blue");
ButtonGroup colourGroup = new ButtonGroup(); // Group buttons so only one can be pressed at a time
colourGroup.add(red); // Add buttons to group
colourGroup.add(green);
colourGroup.add(blue);
colours.setLayout(new GridLayout(2, 2, 0, 0)); // Change layout
colours.add(new JLabel("Change colours")); // Add label
colours.add(red); // Add buttons to colours panel
colours.add(green);
colours.add(blue);
// Add radio button actions
red.addActionListener(new ActionListener() // Add button listener to red button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
if (gameScene.getBackgroundEffect().getColour() != 0)
gameScene.getBackgroundEffect().setColour(0); // Background effect colour = red
green.addActionListener(new ActionListener() // Add button listener to green button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
if (gameScene.getBackgroundEffect().getColour() != 1)
gameScene.getBackgroundEffect().setColour(1); // Background effect colour = green
blue.addActionListener(new ActionListener() // Add button listener to blue button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
if (gameScene.getBackgroundEffect().getColour() != 2)
gameScene.getBackgroundEffect().setColour(2); // Background effect colour = blue
// hide buttons
JPanel hideShow = new JPanel(); // Change hideShow panel
hideShow.setBorder(BorderFactory.createLineBorder(Color.black));
hide = new JRadioButton("Hide"); // Radio buttons to hide show
show = new JRadioButton("Show");
show.setSelected(true); // Set show as already selected
ButtonGroup hideShowGroup = new ButtonGroup(); // Group buttons so only one can be pressed at a time
hideShowGroup.add(hide); // Add buttons to group
hideShowGroup.add(show);
hideShow.setLayout(new GridLayout(2, 2, 0, 0)); // Change layout
hideShow.add(new JLabel("Hide / Show")); // Add label
hideShow.add(hide); // Add buttons to hideShow panel
hideShow.add(show);
// Add radio button actions
hide.addActionListener(new ActionListener() // Add button listener to hide button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
gameScene.getBackgroundEffect().hide(); // Hide
show.addActionListener(new ActionListener() // Add button listener to show button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
gameScene.getBackgroundEffect().unHide(); // Unhide
// stopMove buttons
JPanel stopMove = new JPanel(); // Change StopMove panel
stopMove.setBorder(BorderFactory.createLineBorder(Color.black));
stop = new JRadioButton("Stop"); // Radio buttons to stop move
move = new JRadioButton("Move");
stop.setSelected(true); // Set stop as already selected
ButtonGroup stopMoveGroup = new ButtonGroup(); // Group buttons so only one can be pressed at a time
stopMoveGroup.add(stop); // Add buttons to group
stopMoveGroup.add(move);
stopMove.setLayout(new GridLayout(2, 2, 0, 0)); // Change layout
stopMove.add(new JLabel("Stop / Move")); // Add label
stopMove.add(stop); // Add buttons to stopMove panel
stopMove.add(move);
// Add radio button actions
stop.addActionListener(new ActionListener() // Add button listener to stop button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
gameScene.getBackgroundEffect().setMove(false); // stop
move.addActionListener(new ActionListener() // Add button listener to move button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
gameScene.getBackgroundEffect().setMove(true); // move
// changePath buttons
JPanel changePath = new JPanel(); // Change changePath panel
changePath.setBorder(BorderFactory.createLineBorder(Color.black));
arch = new JRadioButton("Arch"); // Radio buttons to change path
figureOfEight = new JRadioButton("Figure of eight");
arch.setSelected(true); // Set stop as already selected
ButtonGroup changePathGroup = new ButtonGroup(); // Group buttons so only one can be pressed at a time
changePathGroup.add(arch); // Add buttons to group
changePathGroup.add(figureOfEight);
changePath.setLayout(new GridLayout(2, 2, 0, 0)); // Change layout
changePath.add(new JLabel("Change Path")); // Add label
changePath.add(arch); // Add buttons to changePath panel
changePath.add(figureOfEight);
// Add radio button actions
arch.addActionListener(new ActionListener() // Add button listener to arch button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
gameScene.getBackgroundEffect().setPath(new Arch()); // Arch
figureOfEight.addActionListener(new ActionListener() // Add button listener to figureOfEight button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
gameScene.getBackgroundEffect().setPath(new FigureOfEight()); // Figure of eight
// Add components to background panel
backgroundPanel.add(backgroundcolour);
backgroundPanel.add(colours);
backgroundPanel.add(hideShow);
backgroundPanel.add(stopMove);
backgroundPanel.add(changePath);
return backgroundPanel;
* makeBallsPanel
* @return JPanel - The ball panel with buttons added
private JPanel makeBallsPanel()
// Make balls panel
JPanel ballsPanel = new JPanel();
ballsPanel.setLayout(new BoxLayout(ballsPanel, BoxLayout.Y_AXIS)); // Change layout
// Make buttons
// set all drop down boxes
JPanel setAll = new JPanel(); // Set all panel
setAll.setBorder(BorderFactory.createLineBorder(Color.black));
String[] setAllPathsChoices = {"Arch", "Figure of eight"}; // Selections for set all paths
setAllPaths = new JComboBox(setAllPathsChoices); // Add selections to combo box
String[] setAllTypesChoices = {"Primary ball", "Pastel ball", "3D ball", "Image ball"}; // Selections for set all types
setAllTypes = new JComboBox(setAllTypesChoices); // Add selections to combo box
setAll.add(new JLabel("Set all paths")); // Add combo boxes to set all panel
setAll.add(setAllPaths);
setAll.add(new JLabel("Set all types"));
setAll.add(setAllTypes);
// Add combo box actions
setAllPaths.addActionListener(new ActionListener() // Add selection listener to set all paths combo box
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
if (setAllPaths.getSelectedItem() == "Arch")
gameScene.setAllPathsArch();
else
gameScene.setAllPathsFigureOfEight();
setAllTypes.addActionListener(new ActionListener() // Add selection listener to set all types combo box
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
if (setAllTypes.getSelectedItem() == "Primary ball")
gameScene.setAllTypesPrimaryBall();
else if (setAllTypes.getSelectedItem() == "Pastel ball")
gameScene.setAllTypesPastelBall();
else if (setAllTypes.getSelectedItem() == "Image ball")
gameScene.setAllTypesImageBall();
else
gameScene.setAllTypesBall3D();
// new ball drop down box
JPanel newBallPanel = new JPanel(); // new ball panel
newBallPanel.setBorder(BorderFactory.createLineBorder(Color.black));
String[] newType = {"Primary ball", "Pastel ball", "3D ball", "Image ball"}; // Selections for new ball
newBall = new JComboBox(newType); // Add selections to combo box
newBallPanel.add(new JLabel("New ball")); // Add combo boxes to new ball panel
newBallPanel.add(newBall);
// Add combo box actions
newBall.addActionListener(new ActionListener() // Add selection listener to newBall combo box
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
String ballType = (String) newBall.getSelectedItem();
if (ballType == "Primary ball")
gameScene.addBall(new PrimaryBall(gameScene));
else if (ballType == "Pastel ball")
gameScene.addBall(new PastelBall(gameScene));
else if (ballType == "Image ball")
gameScene.addBall(new ImageBall(gameScene));
else
gameScene.addBall(new Ball3D(gameScene));
updateSelectBallComboBox();
changeSelectedBall(gameScene.getBalls().size() - 1); // Update interface to show new ball
// selected ball panel
JPanel selectedBallPanel = new JPanel(); // selected ball panel
selectedBallPanel.setBorder(BorderFactory.createLineBorder(Color.black));
// Select ball
selectBall = new JComboBox(gameScene.getBallList()); // Add ball list to the select drop down box
deleteBall = new JButton("DeleteBall"); // Delete button
// Ball colour
redBall = new JRadioButton("Red"); // Red choice
redBall.setSelected(true); // Start as selected
greenBall = new JRadioButton("Green"); // Green choice
blueBall = new JRadioButton("Blue"); // Blue choice
ButtonGroup ballColour = new ButtonGroup(); // So only one colour can be selected at a tim
ballColour.add(redBall);
ballColour.add(greenBall);
ballColour.add(blueBall);
// Path
archBall = new JRadioButton("Arch"); // Arch path choice
archBall.setSelected(true); // Start as selected
figureOfEightBall = new JRadioButton("Figure of eight"); // Figure of eight path choice
ButtonGroup ballPath = new ButtonGroup(); // So only one path can be selected at a tim
ballPath.add(archBall);
ballPath.add(figureOfEightBall);
// Can split
canSplit = new JCheckBox("Can split", false); // Initialy not selected
selectedBallPanel.add(new JLabel("Select ball")); // Add components to selected ball panel
selectedBallPanel.add(selectBall);
selectedBallPanel.add(deleteBall);
selectedBallPanel.add(new JLabel("Ball colour"));
selectedBallPanel.add(redBall);
selectedBallPanel.add(greenBall);
selectedBallPanel.add(blueBall);
selectedBallPanel.add(new JLabel("Path"));
selectedBallPanel.add(archBall);
selectedBallPanel.add(figureOfEightBall);
selectedBallPanel.add(canSplit);
// Add select ball drop down box action
selectBall.addActionListener(new ActionListener() // Add selection listener to selectBall combo box
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
changeSelectedBall(selectBall.getSelectedIndex()); // Change the selected ball using the index from the select ball drop down box
// Add delete button action
deleteBall.addActionListener(new ActionListener() // Add selection listener to deleteBall button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
int tempIndex = selectBall.getSelectedIndex(); // Temp index
if (gameScene.getBalls().size() > 1) // If there is more than 1 ball left
gameScene.removeBall(tempIndex); // Remove ball
updateSelectBallComboBox(); // Update with new ball list
changeSelectedBall(tempIndex - 1); // Update interface with new current selected ball
// Add radio button colour actions
redBall.addActionListener(new ActionListener() // Add button listener to redBall button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
if (currentBall.getColour() != 0)
currentBall.setColour(0); // currentBall colour = red
greenBall.addActionListener(new ActionListener() // Add button listener to greenBall button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
if (currentBall.getColour() != 1)
currentBall.setColour(1); // currentBall colour = green
blueBall.addActionListener(new ActionListener() // Add button listener to blueBall button
public void actionPerformed(ActionEvent ev) // Background colour = blue
if (currentBall.getColour() != 2)
currentBall.setColour(2); // currentBall colour = blue
// Add path radio button actions
archBall.addActionListener(new ActionListener() // Add button listener to arch button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
currentBall.setPath(new Arch()); // Arch
figureOfEightBall.addActionListener(new ActionListener() // Add button listener to figureOfEight button
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
currentBall.setPath(new FigureOfEight()); // Figure of eight
// Add can split check button actions
canSplit.addActionListener(new ActionListener() // Add button listener to can split
public void actionPerformed(ActionEvent ev) // Overide actionPerformed() method
currentBall.setCanGiveBirth(canSplit.isSelected()); // Ball can split if can split check button is selected
// Add components to ball panel
ballsPanel.add(setAll);
ballsPanel.add(newBallPanel);
ballsPanel.add(selectedBallPanel);
return ballsPanel;
* changeSelectedBall
* @param ballIndexIn - The numbered index of the ball in the game scene list of balls. If less than 0 then equals 0. If more than ball list size then equals last ball
public void changeSelectedBall(int ballIndexIn)
if (ballIndexIn < 0) // Make sure index is within bounds
ballIndexIn = 0;
else if (ballIndexIn >= gameScene.getBalls().size())
ballIndexIn = gameScene.getBalls().size() - 1; // Else put within bounds at either end
currentBall.highlight(false); // Unhighlight current ball
currentBall = gameScene.getBall(ballIndexIn); // Get new current ball
currentBall.highlight(true); // Highlight new current ball
// Update controls to new ball
selectBall.setSelectedIndex(ballIndexIn);
switch (currentBall.getColour()) // Update colour controls
case 0: redBall.setSelected(true); break;
case 1: greenBall.setSelected(true); break;
default: blueBall.setSelected(true); break;
if (currentBall.getPath() instanceof Arch) // If path is arch
archBall.setSelected(true); // Update controls as arch
else
figureOfEightBall.setSelected(true); // Else figure of eight
canSplit.setSelected(currentBall.canGiveBirth()); // Set if the ball can split or not
* updateSelectBallComboBox
* This method updates the combo box selection model with a new one made from the updated balls arraylist from the game scene
public void updateSelectBallComboBox()
DefaultComboBoxModel model = new DefaultComboBoxModel(gameScene.getBallList());
selectBall.setModel(model);
}Kind regards
Liam morrenhttp://docs.info.apple.com/article.html?artnum=301073
This link states Mac OS X 10.4 now supports Java 5.0. It does mention nothing about Mac OS 9 or previous version of OS X. The problem you may be facing is that your Mac is running only 1.4.2 or less. The class files compiled for Java 5.0 can't run in non 5.0 versions of the Java Virtual Machine. Java 5.0 was a major release for the Java language and thus the change in numbering (though it took a little bit for this to change).
Anyway you should confirm what version of Java you have installed on your Mac.
At a command prompt:
java -version
The above URL states that the previous 1.4.2 Java version is not uninstalled, and this could still be the preferred version to use for Java applications even after installing Java 5.0.
The URL above states there is a utility to set your apps to use Java 5.0 as the perferred Java version. Who knows maybe this is all you need to do. I hope this is the case, then it probably is an easy fix, otherwise you may need to rewrite your app in Java 1.4.2 to get it to run on your version of Mac. -
Need help getting my applets to work on web pages!
I've been trying to get it to work for a while now, and I no idea why it won't work! I've tried all kinds of things to get it to work, but it still won't work. All I want to do is make a simple applet, don't care what it does, and put it on a web page.
Here is my HTML code:
<applet code=?Slime2P.class? height=?300? width=?400? codebase=?http://www.spinarcade.com/tests?>
</APPLET>
Here is a link to what happens:
[http://www.spinarcade.com/tests/duk.html|http://www.spinarcade.com/tests/duk.html]
Here is the errors:
load: class ?Slime2P.class? not found.
java.lang.ClassNotFoundException: ?Slime2P.class?
at sun.applet.AppletClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.applet.AppletClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.applet.AppletClassLoader.loadCode(Unknown Source)
at sun.applet.AppletPanel.createApplet(Unknown Source)
at sun.plugin.AppletViewer.createApplet(Unknown Source)
at sun.applet.AppletPanel.runLoader(Unknown Source)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
It works fine when I run the applet in eclipse, and I've tried many different applets. I tried using a cool program I wanted to put online first, then I made a simple program to try, and then I even downloaded the file from a tutorial and didn't edit it at all... nothing works!
Here's code from one of the applets (Simple applet with green lines):
import java.applet.*;
import java.awt.*;
public class Duck extends Applet {
int width, height;
public void init() {
width = getSize().width;
height = getSize().height;
setBackground( Color.black );
public void paint( Graphics g ) {
g.setColor( Color.green );
for ( int i = 0; i < 10; ++i ) {
g.drawLine( width, height, i * width / 10, 0 );
I have all the .class file and the html page in the same place (http://www.spinarcade.com/tests).
Thank you for your help! It is most likely something simple...
Edited by: Donv7 on Jul 17, 2008 2:27 PMHere is your html:
<HTML>
<HEAD>
<TITLE>Duk!</TITLE>
</HEAD>
<body bgcolor="#DAE9F3">
<center>
<applet code=?Slime2P.class? height=?300? width=?400?>
</APPLET>
ducks these dayz...<br>
codebase=?http://www.spinarcade.com/tests?<br>
C:\Documents and Settings\Don\Desktop<br>
http://www.spinarcade.com/tests<br>
</center>
</BODY>
</HTML>Look carefully at the double quotes surrounding the red text (bgcolor).
Look at the double quotes used in the applet tag now!!! -
Display .gif In Applet Problem
I have been making a game. Very simply, the game has a main class and another truely important class that extends JFrame, it is the map. In it i need to upload .gif files and display them. It worked up until recently because i needed to make a sepperate class. I know how to use the getImage() for Images and the the way for ImageIcons, but for some reason, they never display (they display just whiteness). My Code is as follows
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.io.*;
// when this puppy reads from a file, it'll be able to have 55 15 x 15 terrains per row
// 35 15 x 15 terrains per column
// arrows by everythign that u would need to consider in finding the problem
// this is not the main class
public class GameMap extends JPanel implements MouseListener, MouseMotionListener, KeyListener{
public static final int MAX_BULLETS = 200;
public static final int MAX_PLAYERS = 50;
public static final int SPLAT_SIZE = 15;
public static final int PLAYER_SIZE = 15;
public static final int MAX_MESSAGES = 10;
public static final int ROBOT_SIZE = 15;
private static final int rowTerrains = 35;
private static final int columnTerrains = 55;
private static int currentBullets = 0;
private static int currentPlayers = 0;
private static int bulletRotation = 0;
private static int aimX, aimY;
private boolean mapLoaded;
private boolean writingMessage;
private boolean imagesLoaded;
private int messageRotation;
private int tileCoord;
private String messageText = "";
private String currentMap;
private Bullet bullet[] = new Bullet[MAX_BULLETS];
private Player player[] = new Player[MAX_PLAYERS];
private Message message[] = new Message[MAX_MESSAGES];
private Color backgroundColor = new Color(81, 141, 23);
private Image offscreenMap; // offscreen image of map
private Graphics mapGraphics;
private ImageIcon yellowSplat1, yellowSplat2, yellowSplat3, yellowSplat4, yellowSplat5, bluePlayerBack, bluePlayerFront, bluePlayerRight, bluePlayerLeft, grass, tree, mountain, robot1;
private Terrain terrain[] = new Terrain[(rowTerrains * columnTerrains)];
public GameMap(){
this(800, 450);
public GameMap(int width, int height){
addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this); // use method requestFocusInWindow() for this to work
setPreferredSize(new Dimension(width, height));
setBackground(backgroundColor);
for (int x = 0; x < bullet.length; x++){
bullet[x] = new Bullet();
for (int x = 0; x < player.length; x++){
player[x] = new Player();
for (int x = 0; x < message.length; x++){
message[x] = new Message();
for (int x = 0, currentX = 0, currentY = 0; x < (rowTerrains * columnTerrains); x++){
terrain[x] = new Terrain();
terrain[x].setX(currentX);
terrain[x].setY(currentY);
currentX += 15;
if (currentX > columnTerrains * 15){
currentX = 0;
currentY += 15;
player[0].drawPlayer(0, 0);
//loadMap("Map1.txt"); // this is called to load the map right when this object is initialized
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
Composite originalComposite = g2d.getComposite();
if (imagesLoaded == false){
yellowSplat1 = new ImageIcon("yellow1.gif");
yellowSplat2 = new ImageIcon("yellow2.gif");
yellowSplat3 = new ImageIcon("yellow3.gif");
yellowSplat4 = new ImageIcon("yellow4.gif");
yellowSplat5 = new ImageIcon("yellow5.gif");
bluePlayerBack = new ImageIcon("BlueBack.gif");
bluePlayerFront = new ImageIcon("BlueFront.gif");
bluePlayerLeft = new ImageIcon("BlueLeft.gif");
bluePlayerRight = new ImageIcon("BlueRight.gif");
grass = new ImageIcon("Grass.gif");
tree = new ImageIcon("Tree.gif");
mountain = new ImageIcon("Mountain.gif");
robot1 = new ImageIcon("Robot1.gif");
if (mapLoaded == false){ // so a map is loaded when game is started
loadMap("Map1.txt");
mapLoaded = true;
g.drawImage(offscreenMap, 0, 0, this);
for (int x = 0; x < bullet[0].totalBullets; x++){
if (bullet[x].getArrived()){
//find splat type and display it
g2d.setComposite(makeComposite(0.5f));
switch (bullet[x].getSplatType()){
case 0:
yellowSplat1.paintIcon(this, g2d, bullet[x].getDestX() - SPLAT_SIZE / 2, bullet[x].getDestY() - SPLAT_SIZE / 2);
break;
case 1:
yellowSplat2.paintIcon(this, g2d, bullet[x].getDestX() - SPLAT_SIZE / 2, bullet[x].getDestY() - SPLAT_SIZE / 2);
break;
case 2:
yellowSplat3.paintIcon(this, g2d, bullet[x].getDestX() - SPLAT_SIZE / 2, bullet[x].getDestY() - SPLAT_SIZE / 2);
break;
case 3:
yellowSplat4.paintIcon(this, g2d, bullet[x].getDestX() - SPLAT_SIZE / 2, bullet[x].getDestY() - SPLAT_SIZE / 2);
break;
case 4:
yellowSplat5.paintIcon(this, g2d, bullet[x].getDestX() - SPLAT_SIZE / 2, bullet[x].getDestY() - SPLAT_SIZE / 2);
break;
else{
g2d.setComposite(originalComposite);
g2d.setColor(Color.yellow);
g2d.fillOval(bullet[x].getX(), bullet[x].getY(), 3, 3);
g2d.setComposite(originalComposite);
g.setColor(Color.yellow);
for (int x = 0; x < player[0].totalPlayers; x++){
if (player[x].getPlayerPosition().equals("Back")){
bluePlayerBack.paintIcon(this, g2d, player[x].getX(), player[x].getY());
else if (player[x].getPlayerPosition().equals("Right")){
bluePlayerRight.paintIcon(this, g2d, player[x].getX(), player[x].getY());
else if (player[x].getPlayerPosition().equals("Left")){
bluePlayerLeft.paintIcon(this, g2d, player[x].getX(), player[x].getY());
else if (player[x].getPlayerPosition().equals("Front")){
bluePlayerFront.paintIcon(this, g2d, player[x].getX(), player[x].getY());
else{
g2d.fillOval(player[x].getX(), player[x].getY(), 15, 15);
if (writingMessage){
g2d.setColor(new Color(0, 0, 130));
g2d.setComposite(makeComposite(0.5f));
g2d.draw3DRect(8, 7, 800, 17, true);
g2d.setComposite(originalComposite);
g2d.setColor(Color.yellow);
g2d.drawString(messageText, message[0].getX(), 20);
for (int x = 0; x < MAX_MESSAGES; x++){
if (message[x].isDisplayed()){
g2d.drawString(message[x].getMessage(), message[x].getX(), message[x].getY());
private AlphaComposite makeComposite(float alpha) {
int type = AlphaComposite.SRC_OVER;
return(AlphaComposite.getInstance(type, alpha));
public void drawBullet(int aimX, int aimY){
bullet[bulletRotation].drawBullet(player[0].getX() + PLAYER_SIZE / 2, player[0].getY() + PLAYER_SIZE / 2, aimX, aimY);
player[0].setPlayerPosition(bullet[bulletRotation].getPlayerPosition());
bulletRotation++;
if (bulletRotation >= MAX_BULLETS){
bulletRotation = 0;
public void loadMap(String map){
mapLoaded = false;
currentMap = map;
try{
BufferedReader in = new BufferedReader(new FileReader(map));
String input, string1, string2;
for (int x = 0; x < terrain.length; x++){
terrain[x].setFilled(false);
for (int x = 0, currentArray; x < terrain.length; x++){
if ((input = in.readLine()) != null) {
StringTokenizer st = new StringTokenizer(input);
currentArray = Integer.parseInt(st.nextToken());
terrain[currentArray].setTerrainType(st.nextToken());
terrain[currentArray].setFilled(true);
else{
break;
in.close();
offscreenMap = createImage(size().width, size().height);
mapGraphics = offscreenMap.getGraphics();
//mapGraphics.clearRect(0, 0, size().width, size().height);
// everything from here down is to be painted to mapGraphics... but it doesn't get this far cuz of an error
for (int x = 0; x < terrain.length; x++){
if (terrain[x].getTerrainType().equals("Grass")){
grass.paintIcon(this, mapGraphics, terrain[x].getX(), terrain[x].getY());
System.out.println("terrain(" + x + ") is Grass");
else if (terrain[x].getTerrainType().equals("Tree")){
tree.paintIcon(this, mapGraphics, terrain[x].getX(), terrain[x].getY());
System.out.println("terrain(" + x + ") is Tree");
else if (terrain[x].getTerrainType().equals("Mountain")){
mountain.paintIcon(this, mapGraphics, terrain[x].getX(), terrain[x].getY());
System.out.println("terrain(" + x + ") is Mountain");
catch (FileNotFoundException e){
System.out.println("Map not found");
catch (IOException e){
System.out.println("IOException Error!");
// **** mouse Listener ****//
public void mouseClicked(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){
if (e.getButton() == 1){
//System.out.println("player[0].movePlayer(" + e.getX() + ", " + e.getY() + ")");
aimX = e.getX();
aimY = e.getY();
movePlayer(aimX, aimY);
else if (e.getButton() == 3){
aimX = e.getX();
aimY = e.getY();
drawBullet(aimX, aimY);
public void mouseEntered(MouseEvent e){
if (isFocusOwner() != true){
requestFocusInWindow();
public void mouseExited(MouseEvent e){}
// **** end mouse listener ****//
// **** mouse motion listener ****//
public void mouseDragged(MouseEvent e){}
public void mouseMoved(MouseEvent e){}
// **** end mouse motion listener ****/
public void keyPressed(KeyEvent e){}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
}I removed a few unnecessary methods from this code to make it easier to view. EVERYTHING works except for the images displaying. The reason i'm having this problem now is i just redid my workspace and copied the code and i think some glitch stopped it from compiling correctly all along so now i experience this problem in the applet viewer. Though, even before, i couldn't get anything to display in an applet.
And yes, everything is in the same place as the html file.
Thanks for your help!Here's a way to keep track of and paint images with a simple Rectangle array. And also a way to remove lengthy initialization code blocks from paintComponent. Move the images by moving the rectangles.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class GameMapRx
public static void main(String[] args)
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new GameMapPanel());
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
class GameMapPanel extends JPanel
Image[] images;
Rectangle[] rects;
boolean firstTime;
final int PAD;
public GameMapPanel()
loadImages();
firstTime = true;
PAD = 20;
protected void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
int w = getWidth();
int h = getHeight();
if(firstTime)
initializeGameMap(w, h);
for(int i = 0; i < rects.length; i++)
Rectangle r = rects;
g.drawImage(images[i], r.x, r.y, this);
g2.draw(r);
private void loadImages()
String path = "images/duke/";
String ext = ".gif";
images = new Image[10];
for(int i = 0; i < images.length; i++)
try
URL url = getClass().getResource(path + "T" + (i + 1) + ext);
images[i] = ImageIO.read(url);
catch(MalformedURLException mue)
System.out.println("Bad URL: " + mue.getMessage());
catch(IOException ioe)
System.out.println("Unable to read: " + ioe.getMessage());
private void initializeGameMap(int w, int h)
rects = new Rectangle[images.length];
int imageWidth = images[0].getWidth(this);
int imageHeight = images[0].getHeight(this);
int cols = (w - 2*PAD) / imageWidth;
int xInc = imageWidth + (w - cols * imageWidth) / (cols + 1);
int x0 = (w - cols * imageWidth -
(cols - 1) * ((w - cols * imageWidth) / (cols + 1))) / 2;
for(int i = 0; i < images.length; i++)
int x = x0 + xInc * (i % cols);
int rows = i / cols;
int y = PAD + (imageHeight + PAD) * rows;
rects[i] = new Rectangle(x, y, imageWidth, imageHeight);
firstTime = false; -
Applet, Netscape and Opera but not IE, encore
I've got the following trivial applet that runs under Netscape and Opera, but not under IE. It's also at www.MartinRinehart.com as the ColorChooser choice. There's a half dozen Dukes from previous posts, and my sincere gratitude for anyone who can tell me what I need to do so IE doesn't say "Load: class CCApplet not found."
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Label;
public class CCApplet extends java.applet.Applet {
public void start() {
Label l = new Label( "CCApplet!" );
setLayout( new BorderLayout() );
add( l, BorderLayout.NORTH );
add( new Button("South"), BorderLayout.SOUTH );
} // end of class CCAppletThe .class is in the same directory as the .html. Putting it in a .jar doesn't seem to matter. My IE runs other applets from the web, but not the ones I write. Thanks in advance.The applet runs for me in IE with 1.5.0_02, XP Pro (current updates), with class and html files in same directory.
Check that everything in IE's Java Plug-in is valid and correct. Check IE's Internet Options.
What JVM version are you wanting the applet to be able to run with? What does this statement mean? "...most visitors can use without knowing what a JRE is."
To get greatest compatibility, use code that conforms to the 1.1 API, compile to that target version, possibly use the old 1.1 libraries, and then test each jvm. (BTW - Swing has limited compatibility - it isn't MS compatible, and wasn't [Sun] standard until jvm version 1.2.) -
Signed applet, jmf.jar provided, but no connection
hi there!
i'm posting this again in order for you to earn duke-bucks.
i have a similar problem. i wrote an applet that connects to a video-streamserver an requests a live-stream. the applet sends some udp-packets to the server, which retreives the client's ip from the
packet and sends it back to the client ( i did this to avoid signing the applet, since otherwise the client
would have to do a dns-lookup and therefore be signed). the client gets back his public ip (i don't have the 127.0.0.1-problem) , however, i get an
InvalidSessionAddressException :
Local Data Address Does not belong to any of the local interfaces
it seems, the client cannot recognize it's own public ip.
so i thought, signing the applet would do, but it doesn't.
I get the same InvalidSessionAddressException.
now, this only happens on hosts on which jmf is NOT installed.
Installing the jmf solves the problem. but i don't want people who visit my page having to install
jmf in order to watch my livestream. i tried including the whole jmf.jar (also tried, customizing it),
but no success.
i read the posts on the issue: running jmf-applets on non-jmf-systems, but there seems to be a
controversy on wether that is possible or not. some say, jmf must be installed, some say, just include jmf.jar or customized jmf.jar.
what else could i try? i have the clients public ip and i have the applet signed. so, there shouldn't be
any restrictions anymore.
i have no ClassDefNotFoundExceptions, so i suppose, including jmf.jar works.
what else gets changed when i install jmf? there must be some restrictions that keep the vm from
determining the hosts public ip and which will be removed by the installation of jmf.
anyone had similar problems? and, perhaps, a solution to this?
thanks in advance,
honfrek
b.t.w. you can earn some duke-bucks too !hi!
i found a very elaborate solution here:
http://www.mutong.com/fischer/java/usbcam/VideoToAppletWithNoSupport.zip
this link has been posted before,
http://onesearch.sun.com/ClickThru?qt=servlets&url=http%3A%2F%2Fforum.java.sun.com%2Fthread.jsp%3Fforum%3D28%26thread%3D515345&pathInfo=%2Fsearch%2Fdevelopers%2Findex.jsp&hitNum=45&col=devforums
this solution uses jmf only on server side for capturing, then converts the capture-stream into images, splits
the images into smaller regions and evaluates the differences of these regions to the regions of the previous image. if the difference hits a certain threshold, these regions are transmitted to the applet. but the transmission is done via tcp, which slows things down.
the splitting -code is hard for me to understand, since i'm new to java. -
Java Web Start starting applet
Dear all,
I like to run heavy application as an applet and the best way is keep the jar containing the application in the client.
I am wondering whether I can use java web start or not to deploy in the client the jar with the applet and so the client doesn't need to reload the jar from server unless there's some changes in the server.
Can java web start also start the browser to start the application?
I don't see any example in the internet although in java web start documentation says it is possible.
Dani.You don't want the 2 dukes... come Vietnam and I will invite you some beers... can you?
By the way... I know JWS is used to deploy applications.
Maybe my question was not clear... By using jnlp file you can tell jws what is the class to be launched once loaded the jar file, and so just using an URL with the path of the jnlp file in the server, the browser will reload the jar and then the application is launched automatically. What i am wondering is whether i can or not launch my applet just typing the URL where the jnlp file is and so use the same browser. Once the jar is loaded, the applet would be launched in the browser. I don't like every time the user has to use the application, first need to verify he has the latest jar file using one URL in the browser and then he has to type another URL to launch the applet...
Any ideas?
Edited by: Daniel23 on Sep 27, 2007 1:50 AM
Maybe you are looking for
-
KM Scheduler job with MDM APIs
Hi, I am trying to write a background job that makes use of MDM APIs. I created a Portal Application Project and put in the required code. I added the required MDM jar fiels in to the java build path. How ever, I don't know how to add Library Referen
-
Screwed up my default icons with CandyBar - how to get 'em back??
Hi, Okay, this was really dumb of me, I know - please be gentle... I registered Shapeshifter a couple of weeks ago and used it to change my theme and system icons to my liking. Then, today, I downloaded the CandyBar demo to see what that would do. Ba
-
I've had an iPod Nano 7 (16 GB) for just over a year, and I don't sync my entire music library at once--just a few gigs of favorites plus current podcast episodes and an occasional audiobook. I recently received a second-hand 3rd generation iPad (als
-
Using PL/SQL Function with CLOB types and a Java Source
Hi people. I have some problems trying to use a function in pl/sql with a CLOB parameter to a java source function. Here is the problem: I have to read a TXT file and return a CLOB with the data of the file. The reading is done with a java source fun
-
Is there a way to edit the html code of the page directly on iweb?
My web server gives me the error: Parse error: syntax error, unexpected T_STRING, everytime I try to access my site after I've updated it with the FTP server. I leanred that it was because of a bit of extraneous code in the beginning of each page t