Reputation: 1
I am taking a Java course at the moment and am on Chapter 4 in Java Illuminate 3rd edition. we are working on getting an Applet to display text and or designs and colors. i am working with a macbook and i am doing my coding through TextWrangler and am trying to run my on my terminal, but for some reason after i compile my code i cannot get the Applet display to show. Please see below to see the code the book gives us and they expect us to get an Applet Viewer by running the code, as such, but i cannot find out how to do so.
/* Drawing Text
Anderson, Franceschi
*/
import javax.swing.JApplet;
import java.awt.Graphics;
public class DrawingTextApplet extends JApplet
{
public void paint( Graphics g )
{
super.paint( g );
g.drawString( "Programming is not", 140, 100 );
g.drawString( "a spectator sport!", 140, 115 ); //for every new line you add 15 to the Y cord.
}
}
Upvotes: 0
Views: 779
Reputation: 168815
Direct from the applet tag info. page. Take particular note of the multi-line comments.
Applet 'Hello World' Example
This example requires the Java Development Kit installed. Visit Java SE Downloads for the latest JDK.
/* <!-- Defines the applet element used by the appletviewer. -->
<applet code='HelloWorld' width='200' height='100'></applet> */
import javax.swing.*;
/** An 'Hello World' Swing based applet.
To compile and launch:
prompt> javac HelloWorld.java
prompt> appletviewer HelloWorld.java */
public class HelloWorld extends JApplet {
public void init() {
// Swing operations need to be performed on the EDT.
// The Runnable/invokeAndWait(..) ensures that happens.
Runnable r = new Runnable() {
public void run() {
// the crux of this simple applet
getContentPane().add( new JLabel("Hello World!") );
}
};
SwingUtilities.invokeAndWait(r);
}
}
Upvotes: 1
Reputation: 2920
I think it's easier to use other Swing tools instead of applets. You don't have to go through the hassle of finding an applet viewer or possibly changing the security settings for Java if you do; applets are also pretty outdated.
If you changed your program to something like this...
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.awt.Graphics;
public class DrawingTextPanel extends JPanel
{
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString("Programming is not", 140, 100);
g.drawString("a spectator sport!", 140, 115);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.add(new DrawingTextPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
});
}
}
...you'll get the same display that you would using an applet. Similar to how you do your painting in the paint
method with an applet, you would do it in the paintComponent
method in this case.
Upvotes: 0