Applet in a pack

my java Applet class has package
package com.web;
import java.applet.Applet;
import java.awt.*;
public class Display extends Applet
..........i want to use this class in JSP
<applet code="Display.class" width="300" height="150">
</applet>
How do i write it ?

Applets run on the CLIENT jsp runs on the SERVER.
What you put in the @page (import) is used on the SERVER and the applet has
nothing to do with it.
put your applet in the correct directory (or make a jar).
In this case the applet is in:
[codebase]\com\web\Display.class
Your applet tag should look like:
<applet codebase="../WhateverTheCodeBaseToYourAppletIs" code="com.web.Display">
Then convert the applet tag to object tag using the htmlconverter in the jdk dir.
Then make sure you have a correct working object tag for IE users:
http://forum.java.sun.com/thread.jspa?threadID=640305&tstart=135
1st and 7th post

Similar Messages

  • Custom classloader in Applet?

    Hi
    I have for some time tried to load an Applet from within an Applet by means of custom classloader.
    However when reading various specifications for classloader they state it is not possible for an Applet to do so.
    Does anyone know otherwise?

    Hi
    To be more specific.. I have 2 Applets yes. In the first signed Applet I run as a jar I have created a custom classloader that extends ClassLoader hence the java bytecode I wish to load (also an Applet) must be (a) class file(s). As far as I know the ClassLoader is not able to define classes from jars right?
    It is only the loading Applet that is packed as a jar and there is no nested jars. However the loaded Applet is now loaded as a class file but I would like to load is a jar for speeding up loading time.
    Quote from http://www.javaworld.com/javaworld/jw-10-1996/jw-10-indepth.html:
    There is a cost, however, because the class loader is so powerful (for example, it can replace java.lang.Object with its own version), Java classes like applets are not allowed to instantiate their own loaders. (This is enforced by the class loader, by the way.) This column will not be useful if you are trying to do this stuff with an applet, only with an application running from the trusted class repository (such as local files).

  • Applet is not loading second time with Jre7 u9

    Hi,
    I have found serious problem with Jre7 update 9, Java Applet is not loading in 2nd time, it loads properly first time but in 2nd time it hangs for infinite time.
    Interesting part is same applet works perfectly with Jre7 which have stability & security issues.
    Is this is cache problem or I have to do some configuration changes?
    I have to delete everytime cache resources from Java Control Panel to run applet.
    See logs for more details:
    cache: Initialize resource manager: com.sun.deploy.cache.ResourceProviderImpl@966905
    security: property package.access value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.
    security: property package.access new value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws
    security: property package.access value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws
    security: property package.access new value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy
    security: property package.access value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy
    security: property package.access new value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy,com.sun.jnlp
    security: property package.definition value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.
    security: property package.definition new value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws
    security: property package.definition value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws
    security: property package.definition new value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy
    security: property package.definition value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy
    security: property package.definition new value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy,com.sun.jnlp
    security: property package.access value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy,com.sun.jnlp
    security: property package.access new value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy,com.sun.jnlp,org.mozilla.jss
    security: property package.definition value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy,com.sun.jnlp
    security: property package.definition new value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy,com.sun.jnlp,org.mozilla.jss
    basic: Added progress listener: sun.plugin.util.ProgressMonitorAdapter@920ee7
    basic: Added progress listener: sun.plugin.util.ProgressMonitorAdapter@1e74d83
    security: Blacklist revocation check is enabled
    security: Trusted libraries list check is enabled
    network: Cache entry found [url: http://subdomain.domain.com/application/applet/myapplet.jar, version: null] prevalidated=true/0
    cache: Resource http://subdomain.domain.com/application/applet/myapplet.jar has expired.
    network: Connecting http://subdomain.domain.com/application/applet/myapplet.jar.pack.gz with proxy=DIRECT
    network: Connecting http://subdomain.domain.com:80/ with proxy=DIRECT
    network: Connecting http://subdomain.domain.com/application/applet/myapplet.jar.pack.gz with cookie "JSESSIONID=C45ABD26D27224F74EA675A2CB7B08A4; JSESSIONID=54898DDD281CFF281956381DE51C07B6"
    network: CleanupThread used 445274 us
    network: Connecting http://subdomain.domain.com/application/applet/myapplet.jar with proxy=DIRECT
    network: Connecting http://subdomain.domain.com:80/ with proxy=DIRECT
    network: Connecting http://subdomain.domain.com/application/applet/myapplet.jar with cookie "JSESSIONID=C45ABD26D27224F74EA675A2CB7B08A4; JSESSIONID=54898DDD281CFF281956381DE51C07B6"
    network: ResponseCode for http://subdomain.domain.com/application/applet/myapplet.jar : 304
    network: Encoding for http://subdomain.domain.com/application/applet/myapplet.jar : null
    network: Disconnect connection to http://subdomain.domain.com/application/applet/myapplet.jar
    Regards,
    Deepak Garg

    Hi RogerL,
    Jre7 update10 is working fine, currently I am doing testing my applet with Jre7 update10.
    Very Strange behaviour same applet working fine with Jre7 & Jre7 update10 but it is not working with Jre7 update9 official release.
    I am very keen to know the exact reason or what's new in update 9 & update 10.
    Thanks a lot.
    Deepak Garg

  • Applet / Application Sound problem

    Hey everyone,
    I'm programming a game named None Left, and the main file (NoneLeft.java) contains a constructor :
    public class NoneLeft extends javax.swing.JApplet implements Runnable, ContextListenerIt also contains a main method:
        public static void main(String s[]) {
            JFrame f = new JFrame("NoneLeft");
            f.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {System.exit(0);}
            JApplet applet = new NoneLeft();
            f.getContentPane().add("Center", applet);
            applet.init()        f.pack();
            f.setSize(new Dimension(800,600));
            f.setVisible(true);
    AudioClip music;
    music = applet.getAudioClip(new URL("file:///K:/BinaryFinary2.wav"));
    music.loop();The problem is that whenever I try to use the applet's method getAudioClip,
    i get the following error:
    Exception in thread "main" java.lang.NullPointerException
            at java.applet.Applet.getAppletContext(Applet.java:187)
            at java.applet.Applet.getAudioClip(Applet.java:295)
            at noneleft.NoneLeft.main(NoneLeft.java:865)The code at line 865 is:
    music = applet.getAudioClip(new URL("file:///K:/BinaryFinary2.wav"));
    music.loop();The NullPointerException is really what has me puzzled. The applet is there: It's created in the public static void main method, but it just won't work. Anyone have a clue about why that is?
    I have a feeling it's because of the Applet inheritance and the application; it's not sure which one is which...or maybe not.
    Thanks so much!
    Edited by: simpavid on May 27, 2008 4:11 PM

    Thank you so much for your help so far;
    However, I still haven't gotten this to work.
    I now have the code:
    JFrame f = new JFrame("NoneLeft");
    JApplet applet = new NoneLeft();
    f.getContentPane().add("Center", applet);
    applet.init();
    f.pack();
    f.setSize(new Dimension(800,600));
    f.setVisible(true);
    AudioClip music = applet.getAudioClip(applet.getCodeBase(), "BinaryFinary.wav");
    music.loop();but my error still exists:
    Exception in thread "main" java.lang.NullPointerException
            at java.applet.Applet.getCodeBase(Applet.java:152)
            at noneleft.NoneLeft.main(NoneLeft.java:861)The strange part is that getAudioClip no longer gives me a null pointer but getCodeBase() does. I also tried getDocumentBase() and it gives me an error. I'm wondering if this has to do with the fact that this is called on an applet from a main method? The applet is instantiated as a NoneLeft object, which extends JApplet, so that shouldn't be the problem. Do you have a clue on how to fix that?
    Again, thanks so much for the help.

  • What is wrong with my applet

    hi;
    i wrote this applet but it didn't work only with opera 8?
    so why only opera?
    package editeur;
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.*;
    import java.io.*;
    //Use double buffering to remove rectangle flickers and make it repaint faster.
    public class ShapeMover extends JApplet{
        static protected Label label = new Label(
                "Drag rectangle around within the area");
        MyCanvas mycanvas = new MyCanvas();
        BarreOutils barre=new BarreOutils();
        public static ColorChooserDemo barreCouleur=new ColorChooserDemo();
         public static  XMLayout xml=new XMLayout();
        public void init() {
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(BorderLayout.CENTER,mycanvas);
            getContentPane().add(BorderLayout.WEST, barre);
            getContentPane().add(BorderLayout.EAST, barreCouleur);
        public static void main(String s[]) {
            JFrame f = new JFrame("ShapeMover");
            f.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            Applet applet = new ShapeMover();
            f.getContentPane().add("Center", applet);
            applet.init();
            f.pack();
            f.setSize(new Dimension(550, 250));
            f.show();
    /code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    maybe opera's the only one with the classes - won't even compile for me
    C:\TestApplet.java:15: cannot find symbol
    symbol  : class MyCanvas
    location: class TestApplet
    MyCanvas mycanvas = new MyCanvas();
    ^
    C:\TestApplet.java:16: cannot find symbol
    symbol  : class BarreOutils
    location: class TestApplet
    BarreOutils barre=new BarreOutils();
    ^
    C:\TestApplet.java:17: cannot find symbol
    symbol  : class ColorChooserDemo
    location: class TestApplet
    public static ColorChooserDemo barreCouleur=new ColorChooserDemo();
                  ^
    C:\TestApplet.java:18: cannot find symbol
    symbol  : class XMLayout
    location: class TestApplet
    public static XMLayout xml=new XMLayout();
                  ^
    C:\TestApplet.java:15: cannot find symbol
    symbol  : class MyCanvas
    location: class TestApplet
    MyCanvas mycanvas = new MyCanvas();
                            ^
    C:\TestApplet.java:16: cannot find symbol
    symbol  : class BarreOutils
    location: class TestApplet
    BarreOutils barre=new BarreOutils();
                          ^
    C:\TestApplet.java:17: cannot find symbol
    symbol  : class ColorChooserDemo
    location: class TestApplet
    public static ColorChooserDemo barreCouleur=new ColorChooserDemo();
                                                    ^
    C:\TestApplet.java:18: cannot find symbol
    symbol  : class XMLayout
    location: class TestApplet
    public static XMLayout xml=new XMLayout();
                                   ^
    C:\TestApplet.java:39: cannot find symbol
    symbol  : class ShapeMover
    location: class TestApplet
    Applet applet = new ShapeMover();
                        ^
    Note: C:\TestApplet.java uses or overrides a deprecated API.
    Note: Recompile with -Xlint:deprecation for details.
    9 errors
    Process completed.Message was edited by:
    Michael_Dunn
    change file structure - easier to read

  • Page Functionality(Prev and Next) using applet

    Hi,
    I am trying to implement an applet which has the paging functionality(previous and next). How do I handle the mouse event for that.
    Appreciate your help.
    Thanks
    Sankar.

    ok. Sorry about that, Here is my applet implementation,
    public class PageApplet extends JApplet implements ActionListener,MouseListener
         JTextField name,age;
         JRadioButton male, female;
         static String maleStr = "Male";
         static String femaleStr = "Female";
    private boolean inAnApplet = true;
    JComboBox status;
         JPanel pane;
         GridBagConstraints c;
         private static int count =0;
         private String nameStr;
         public PageApplet() {
         this(true);
    public PageApplet(boolean inAnApplet) {
    this.inAnApplet = inAnApplet;
    if (inAnApplet) {
    getRootPane().putClientProperty("defeatSystemEventQueueCheck",
    Boolean.TRUE);
         * The entry point for the applet.
         public void init()
              setContentPane(makeContentPane());
         public Container makeContentPane() {
              //Add Components to a JPanel, using the default FlowLayout.
         pane = new JPanel(new GridBagLayout());
    c = new GridBagConstraints();
              c.fill = GridBagConstraints.HORIZONTAL;
    JLabel namel = new JLabel("Name : ",JLabel.LEFT);
              c.weightx = 0.6;
              c.gridx = 0;
              c.gridy = 0;
    pane.add(namel,c);
              name = new JTextField(20);
              name.setColumns(20);
              c.gridx = 5;
              c.gridy = 0;     
              name.addActionListener(this);
              pane.add(name,c);
    JLabel agel = new JLabel(" Age : ", JLabel.LEFT);
              c.gridx = 0;
              c.gridy = 1;
    pane.add(agel,c);
              age = new JTextField(2);
              age.setColumns(2);
              age.addActionListener(this);
              c.gridx = 5;
              c.gridy = 1;
    pane.add(age,c);
              JLabel gender = new JLabel(" Gender :", JLabel.LEFT);
              c.gridx = 0;
              c.gridy = 2;
    pane.add(gender,c);
              male = new JRadioButton(maleStr);
         male.setMnemonic(KeyEvent.VK_C);
         male.setActionCommand(maleStr);
              male.setSelected(true);
              male.setBackground(Color.WHITE);
              male.addActionListener(this);
              c.gridx = 5;
              c.gridy = 2;     
    pane.add(male,c);
    female = new JRadioButton(femaleStr);
    female.setMnemonic(KeyEvent.VK_D);
         female.setActionCommand(femaleStr);
         female.setBackground(Color.WHITE);
              female.addActionListener(this);
              c.gridx = 10;
              c.gridy = 2;
              pane.add(female,c);
              JLabel statusl = new JLabel(" Status :", JLabel.LEFT);
         c.gridx = 0;
              c.gridy = 3;
    pane.add(statusl,c);
              String[] statusStr = {"Single","Married","Divorced"};
              status = new JComboBox(statusStr);
              status.setSelectedIndex(0);
              status.setEditable(false);
              status.setBackground(Color.WHITE);
              status.addActionListener(this);
              c.gridx = 5;
              c.gridy = 3;
    pane.add(status,c);
    JButton next = new JButton("Next");
              c.ipady = 0;
              c.weightx=0.0;
              c.weighty=1.0;
              c.anchor = GridBagConstraints.SOUTH;
              c.insets = new Insets(10,0,0,0);
              c.gridwidth = 1;     
              c.gridx = 5;
              c.gridy = 4;
              next.addMouseListener(this);
              pane.add(next,c);
         //pane.setBackground(new Color(255,255,204));
         pane.setBackground(Color.WHITE);
              //pane.setLayout(new GridBagLayout(2,2));
         pane.setBorder(BorderFactory.createMatteBorder(1,1,2,2,Color.black));
    return pane;
         public Container makeContentPane1() {
              //pane = new JPanel(new GridBagLayout());
              pane.removeAll();
    c = new GridBagConstraints();
              JLabel label1 = new JLabel("Hello ",JLabel.RIGHT);
              c.gridx = 0;
              c.gridy = 0;
    pane.add(label1,c);
              JTextField text1 = new JTextField(20);
              text1.setText(nameStr);
              text1.setColumns(20);
              text1.setEditable(false);
              c.gridx = 5;
              c.gridy = 0;
    pane.add(label1,c);
              JButton finish = new JButton("Finish");
              finish.addMouseListener(this);
              c.anchor = GridBagConstraints.CENTER;
              c.insets = new Insets(10,0,0,0);
              c.gridwidth = 1;     
              c.gridx = 5;
              c.gridy = 2;
              pane.add(finish,c);
              //Add Components to a JPanel, using the default FlowLayout.
         // JPanel pane = new JPanel();
              // pane.add(label1);
              // pane.add(text1);
              // pane.add(finish);
         //pane.setBackground(new Color(255,255,204));
         pane.setBackground(Color.WHITE);     
         pane.setBorder(BorderFactory.createMatteBorder(1,1,2,2,Color.black));
    return pane;
         public void actionPerformed(ActionEvent e)
                   if (e.getActionCommand().equals(maleStr)) {
                   male.setSelected(true);
         female.setSelected(false);
              } else if(e.getActionCommand().equals(femaleStr)){
              male.setSelected(false);
         female.setSelected(true);
                   nameStr = name.getText();
                   JComboBox cb = (JComboBox)e.getSource();
                   String statusStr = (String)cb.getSelectedItem();
                   if(statusStr.equals("Single"))
                   status.setSelectedIndex(0);
                   else if(statusStr.equals("Married"))
                   status.setSelectedIndex(1);
                   else if(statusStr.equals("Divorced"))
                   status.setSelectedIndex(2);
              public void mousePressed(MouseEvent me){
              public void mouseClicked(MouseEvent me){
                   JButton next = (JButton)me.getSource();
                   String str = next.getName();
                   if(((me.getClickCount()==1)) || (str.equals(next))){
                   setContentPane(makeContentPane1());
                   count=1;
                   }else{
                   URL url;
                   try {
                   String nextPage="http://"+this.getCodeBase().getHost()+":"+this.getCodeBase().getPort()+"/ShowPage.jsp";
                        url=new URL(nextPage);
                        getAppletContext().showDocument(url);
                   }catch(MalformedURLException ex) {
                             ex.printStackTrace();
              public void mouseReleased(MouseEvent me){
              public void mouseEntered(MouseEvent me){
              public void mouseExited(MouseEvent me){
              private static void createAndShowGUI(){
              JFrame frame = new JFrame("Application version: AppletDemo");
              frame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
              System.exit(0);
         PageApplet applet = new TestPartner(false);
         if(count==1)
                   frame.setContentPane(applet.makeContentPane1());
         else
              frame.setContentPane(applet.makeContentPane());
         frame.pack();
         frame.setVisible(true);
              public static void main(String[] args) {
                   javax.swing.SwingUtilities.invokeLater(new Runnable() {
         public void run() {
              createAndShowGUI();
    Here is what I am trying to do, when the user hits the next button it should go to the next page. but when I hit the next page, its hanging in the same page. Since I am new to applet coding, I couldn't proceed.
    Thanks
    Sankar.

  • Black background of saved image file.

    Hello All,
    My code is set up to create an image then save the image into a file in JPEG format. Everything works well except the background of the saved image is balck. How can I get a white background on the saved file?
    I have posted my code below. I have allocated 10 duke dollars for the person solves who this? Thank You!!!!
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import com.sun.image.codec.jpeg.*;
    import java.io.*;
    import java.awt.image.BufferedImage;
    public class Test2 extends JApplet {
    public void init() {
    //Initialize drawing colors
    setBackground(Color.white);
    setForeground(Color.black);
    public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    Dimension d = getSize();
    int gridWidth = d.width / 6;
    int gridHeight = d.height / 2;
    // fill Rectangle2D.Double (red)
    g2.setPaint(Color.red);
    g2.fill(new Rectangle2D.Double(100, 100, 100, 100));
    g2.setPaint(Color.black);
    g2.drawString("My Rectangle", 125, 85);
    public static void main(String s[]) {
    JFrame f = new JFrame("Test2");
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}
    JApplet applet = new Test2();
    f.getContentPane().add("Center", applet);
    applet.init();
    f.pack();
    f.setSize(new Dimension(400,300));
    f.show();
    saveAsJPEG(applet, 1.0F, "myJPEG.jpg");
         public static void saveAsJPEG(Component component, float quality, String filename)     {
              try          {
                   Dimension d = component.getSize();
                   BufferedImage bimage = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
                   component.paint(bimage.createGraphics());
                   Graphics2D g = (Graphics2D)bimage.getGraphics();
                   g.setPaint(Color.white);
                   if(!filename.endsWith(".jpg"))
                        filename += ".jpg";
                   OutputStream out = new FileOutputStream(filename);
                   JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                   // Create JPEG encoder
                   JPEGEncodeParam jpegParams = encoder.getDefaultJPEGEncodeParam(bimage);
                   jpegParams.setQuality(quality, false);
                   // Set quality to (quality*100)% for JPEG
                   encoder.setJPEGEncodeParam(jpegParams);
                   encoder.encode(bimage);
                   // Encode image to JPEG and send to browser
                   out.close();
              catch (Exception e)          {
                   System.out.println(e);
    }

    I've added 2 lines to your paint, it works now.
    public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    Dimension d = getSize();
    int gridWidth = d.width / 6;
    int gridHeight = d.height / 2;
    // make a white background
    g2.setPaint(Color.white);
    g2.fill(new Rectangle2D.Double(0, 0, d.width, d.height));
    // fill Rectangle2D.Double (red)
    g2.setPaint(Color.red);
    g2.fill(new Rectangle2D.Double(100, 100, 100, 100));
    g2.setPaint(Color.black);
    g2.drawString("My Rectangle", 125, 85);
    }

  • Hello Universe 2D 3D Translation

    of course since i hate using command prompt, and i dont understand how the hell it works, i cant get JAR to work, so i cant compile this(which means i have no protection from anyone claiming it as their own.. i dont really care now that ive seen what Java 3D has to offer), but i made this program based on a few formulas ive found(this is before i knew about Java 3D), after i found out about java3D, ive looked all over for a Java 3D tutorial because thats basicly how i learn everything in java, unfourtionally i couldnt find one. Anyways i was hoping if anyone would be so kind to translate this code into the Java 3D form(its like the Hello Universe Demo at Java.net)
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.Shape;
    * This is like the FontDemo applet in volume 1, except that it
    * uses the Java 2D APIs to define and render the graphics and text.
    public class ThreeDTool extends JApplet implements MouseListener, MouseMotionListener,ActionListener,KeyListener{
        final static Color bg = Color.black;
        final static Color fg = Color.white;
         double x =0;//xcenter
        double y = 0;//ycenter
        double z = 100;///set size of shape
        double zf = 2;
        double xaw = 100;//xaway ///set size of shape
        double yaw = 100;//yaway ///set size of shape
        double scale = 1000;
    //  double tri= .5*100*Math.sqrt(3);
    //     double[] points = {0,tri,-tri,-100,-tri,-tri,100,-tri,-tri,0,tri,-tri,0,0,tri,-100,-tri,-tri,100,-tri,-tri,0,0,tri};
         double[] points = {x-xaw,y-yaw,z,x+xaw,y-yaw,z,x+xaw,y+yaw,z,x-xaw,y+yaw,z,x-xaw,y-yaw,z,x-xaw,y-yaw,z-(zf*z),x-xaw,y+yaw,z-(zf*z),x+xaw,y+yaw,z-(zf*z),x+xaw,y-yaw,z-(zf*z),x-xaw,y-yaw,z-(zf*z),x-xaw,y+yaw,z-(zf*z),x-xaw,y+yaw,z,x+xaw,y+yaw,z,x+xaw,y+yaw,z-(zf*z),x+xaw,y-yaw,z-(zf*z),x+xaw,y-yaw,z};
        double[] points2 = new double[points.length];
        int sides = 3; //sides of shape -1
        double angle = 0;
        double cos = Math.cos(angle);
        double sin = Math.sin(angle);
        int lines;
        int lcount;
        int count;
        double X=0;
        double Y=0;
        double Z=0;
        double X2=0;
        double Y2=0;
        double Z2=0;
         boolean rotateZ=false;
         boolean rotateY=false;
         boolean rotateX=false;
         boolean showName = false;
         double xangle=0;
         double yangle=0;
         double zangle=0;
         int Xcoord;
         int Ycoord;
         boolean zoom=true;
    //     int zoomA = 0;
    // int colorcount=0;
                     public ThreeDTool(javax.swing.JFrame f)
    //        JMenuBar menuBar = new JMenuBar();
    //        JMenu fileMenu = new JMenu("File");
    //        fileMenu.setMnemonic(KeyEvent.VK_F);
    //        fileMenu.getAccessibleContext().setAccessibleDescription("File");
    //        menuBar.add(fileMenu);
    //        JMenuItem menuItem = new JMenuItem("Close", KeyEvent.VK_C);
    //          menuItem.addActionListener(this);
    //          fileMenu.add(menuItem);
    //          JMenu rotateMenu = new JMenu("Rotate");
    //          rotateMenu.setMnemonic(KeyEvent.VK_R);
    //          menuBar.add(rotateMenu);
    //          menuItem = new JMenuItem("Rotate Left",KeyEvent.VK_L);
    //          menuItem.setAccelerator(KeyStroke.getKeyStroke(
    //      KeyEvent.VK_L, ActionEvent.ALT_MASK));
    //       menuItem.addActionListener(this);
    //          rotateMenu.add(menuItem);
    //          menuItem = new JMenuItem("Rotate Right",KeyEvent.VK_R);
    //          menuItem.setAccelerator(KeyStroke.getKeyStroke(
    //      KeyEvent.VK_R, ActionEvent.ALT_MASK));
    //        menuItem.addActionListener(this);
    //          rotateMenu.add(menuItem);
    //          menuItem = new JMenuItem("Rotate Up",KeyEvent.VK_U);
    //          menuItem.setAccelerator(KeyStroke.getKeyStroke(
    //      KeyEvent.VK_U, ActionEvent.ALT_MASK));
    //          menuItem.addActionListener(this);
    //          rotateMenu.add(menuItem);
    //          menuItem = new JMenuItem("Rotate Down",KeyEvent.VK_D);
    //          menuItem.setAccelerator(KeyStroke.getKeyStroke(
    //      KeyEvent.VK_D, ActionEvent.ALT_MASK));
    //          menuItem.addActionListener(this);
    //          rotateMenu.add(menuItem);
    //          f.setJMenuBar(menuBar);
              f.addMouseListener(this);
              f.addMouseMotionListener(this);
        public void init() {
            setBackground(bg);
            setForeground(fg);
            addMouseListener(this);
              addMouseMotionListener(this);
              addKeyListener(this);
         public void actionPerformed(ActionEvent e)
              double rotation = .1;
              String action = e.getActionCommand();
              if(action.equals("Turn Right"))
              while(rotation>0)
                   xangle+=.01;
                   rotateX = true;
                   this.repaint();
                   rotation-=.1;
              if(action.equals("Turn Left"))
              while(rotation>0)
                   xangle-=.01;
                   rotateX = true;
                   this.repaint();
                   rotation-=.1;
              if(action.equals("Turn Up"))
              while(rotation>0)
                   yangle+=.01;
                   rotateY = true;
                   repaint();
                   rotation-=.1;
              if(action.equals("Turn Down"))
              while(rotation>0)
                   yangle-=.01;
                   rotateY = true;
                   repaint();
                   rotation-=.1;
         public void mouseEntered(MouseEvent e)
         public void mouseExited(MouseEvent e)
         public void mouseReleased(MouseEvent e)
         public void keyReleased(KeyEvent e)
         public void keyPressed(KeyEvent e)
              double speed =.05;
              int action = e.getKeyCode();
              if(action==(KeyEvent.VK_DOWN))
                   xangle=-speed;
                   rotateX = true;
                   this.repaint();
                   return;
              if(action==(KeyEvent.VK_UP))
                   xangle=speed;
                   rotateX = true;
                   this.repaint();
                   return;
              if(action==(KeyEvent.VK_Z))
                   zangle-=.001;
                   rotateZ = true;
                   this.repaint();
                   return;
              if(action==(KeyEvent.VK_X))
                   zangle+=.001;
                   rotateZ = true;
                   this.repaint();
                   return;
              if(action==(KeyEvent.VK_LEFT))
                   yangle=-speed;
                   rotateY = true;
                   repaint();
                   return;
              if(action==(KeyEvent.VK_RIGHT))
                   yangle=speed;
                   rotateY = true;
                   repaint();
                   return;
              if(action==(KeyEvent.VK_EQUALS))
                   x+=10;
                   zoom = true;
                   repaint();
                   return;
              if(action==(KeyEvent.VK_MINUS))
                   x-=10;
                   zoom = true;
                   repaint();
                   return;
              showName = true;
              repaint();
         public void keyTyped(KeyEvent e)
         public void mousePressed(MouseEvent e)
              Xcoord=e.getX();
              Ycoord=e.getY();
              System.out.println("Click: "+Xcoord + " " + Ycoord);
         public void mouseMoved(MouseEvent e)
         public void mouseDragged(MouseEvent e)
              double speed =.03;
              if(Ycoord < e.getY())
                  System.out.println("DragLeft: "+Xcoord + " " + Ycoord);
                   xangle=-speed;
                   rotateX = true;
                   this.repaint();
              if(Xcoord < e.getX())
                   System.out.println("DragUp: "+Xcoord + " " + Ycoord);
                   yangle=speed;
                   rotateY = true;
                   repaint();
              if(Ycoord > e.getY())
                   System.out.println("DragRight: "+Xcoord + " " + Ycoord);
                   xangle=speed;
                   rotateX = true;
                   repaint();
              if(Xcoord > e.getX())
                   System.out.println("DragDown: "+Xcoord + " " + Ycoord);
                   yangle=-speed;
                   rotateY = true;
                   repaint();
              Xcoord = e.getX();
              Ycoord = e.getY();
         public void mouseClicked(MouseEvent e)
        public void paint(Graphics g) {
            Graphics2D g2 = (Graphics2D) g;
              g2.translate(500,350);
              if(rotateX || rotateY || rotateZ)
                   g2.setPaint(Color.black);
                   g2.fill(new Rectangle2D.Double(-500,-350,1000,700));
              g2.setPaint(fg);
              if(rotateY)
               System.out.println("RotateY");
             lines = points.length/3;
             cos = Math.cos(yangle);
             sin = Math.sin(yangle);
             lcount = lines;
             count =0;
             Y = points[1];
             X = (points[0]*cos)-(points[2]*sin);
             Z = (points[0]*sin)+(points[2]*cos);
             GeneralPath filledPolygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD,points.length);
              filledPolygon.moveTo((float)((scale*X)/(Z+scale)+x),(float)((scale*Y)/(Z+scale)+x));  
             while(lines>0)
                    X2=X;
                  Y2=Y;
                  Z2=Z;
    //              X = points[count];
                  Y = points[count+1];
    //              Z = points[count+2];
                  X = (points[count]*cos)-(points[count+2]*sin);
                  Z = (points[count]*sin)+(points[count+2]*cos);
                    points2[count]=X;     
                    points2[count+1]=Y;
                    points2[count+2]=Z;
    //              points2[count]=(X*cos)-(Z*sin);
    //              points2[count+1]=Y;
    //              points2[count+2]=(X*sin)+(Z*cos);
                  count+=3;
            if(lines<points.length/3-sides)
                  if(lines == lcount)
                  g2.draw(new Line2D.Double((int)(scale*X)/(Z+scale)+x,(int)(scale*Y)/(Z+scale)+x,(int)(scale*X)/(Z+scale)+x,(int)(scale*Y)/(Z+scale)+x));
                  if(lines != lcount)
                  g2.draw(new Line2D.Double((int)(scale*X)/(Z+scale)+x,(int)(scale*Y)/(Z+scale)+x,(int)(scale*X2)/(Z2+scale)+x,(int)(scale*Y2)/(Z2+scale)+x));
               else if(lines>points.length/3-sides)
                   filledPolygon.lineTo((float)((scale*X)/(Z+scale)+x),(float)((scale*Y)/(Z+scale)+x));     
             else
                  filledPolygon.lineTo((float)((scale*X)/(Z+scale)+x),(float)((scale*Y)/(Z+scale)+x));     
                  filledPolygon.closePath();
                   g2.setPaint(new Color(0,100,150));
                   g2.fill(filledPolygon);
                   g2.setPaint(Color.white);
                     lines--;
             for(int j = 0; j<points.length;j++)
             points[j]=points2[j];
             if(rotateX)
               System.out.println("RotateX");
             lines = points.length/3;
             cos = Math.cos(xangle);
             sin = Math.sin(xangle);
             lcount = lines;
             count =0;
             X = points[count];
             Y = (points[count+2]*sin)+(points[count+1]*cos);
             Z = (points[count+2]*cos)-(points[count+1]*sin);
             GeneralPath filledPolygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD,points.length);
              filledPolygon.moveTo((float)((scale*X)/(Z+scale)+x),(float)((scale*Y)/(Z+scale)+x));  
             while(lines>0)
                  X2=X;
                  Y2=Y;
                  Z2=Z;
                  X = points[count];
    //              Y = points[count+1];
    //              Z = points[count+2];
                  Y = (points[count+2]*sin)+(points[count+1]*cos);
                  Z = (points[count+2]*cos)-(points[count+1]*sin);
                    points2[count]=X;     
                    points2[count+1]=Y;
                    points2[count+2]=Z;
    //              points2[count]=(Z*cos)-(Y*sin);
    //              points2[count+1]=Y;
    //              points2[count+2]=(Z*sin)+(Y*cos);
                  count+=3;
    if(lines<points.length/3-sides)
                  if(lines == lcount)
                  g2.draw(new Line2D.Double((int)(scale*X)/(Z+scale)+x,(int)(scale*Y)/(Z+scale)+x,(int)(scale*X)/(Z+scale)+x,(int)(scale*Y)/(Z+scale)+x));
                  if(lines != lcount)
                  g2.draw(new Line2D.Double((int)(scale*X)/(Z+scale)+x,(int)(scale*Y)/(Z+scale)+x,(int)(scale*X2)/(Z2+scale)+x,(int)(scale*Y2)/(Z2+scale)+x));
               else if(lines>points.length/3-sides)
                   filledPolygon.lineTo((float)((scale*X)/(Z+scale)+x),(float)((scale*Y)/(Z+scale)+x));     
             else
                  filledPolygon.lineTo((float)((scale*X)/(Z+scale)+x),(float)((scale*Y)/(Z+scale)+x));     
                  filledPolygon.closePath();
                   g2.setPaint(new Color(0,100,150));
                   g2.fill(filledPolygon);
                   g2.setPaint(Color.white);
                     lines--;
             for(int j = 0; j<points.length;j++)
             points[j]=points2[j];
    //       colorcount = 0;
            if(rotateZ)
               System.out.println("RotateZ");
             lines = points.length/3;
             cos = Math.cos((int)zangle);
             sin = Math.sin((int)zangle);
             lcount = lines;
             count =0;
             while(lines>0)
                  X2=X;
                  Y2=Y;
                  Z2=Z;
    //              X = points[count];
    //              Y = points[count+1];
                  Z = points[count+2];
                  X = (points[count]*cos)-(points[count+1]*sin);
                  Y = (points[count]*sin)+(points[count+1]*cos);
                  System.out.print("X:"+X+"Y:"+Y+"Z:"+Z);
                    points2[count]=X;     
                    points2[count+1]=Y;
                    points2[count+2]=Z;
    //              points2[count]=(X*cos)-(Y*sin);
    //              points2[count+1]=(X*sin)+(Y*cos);
    //              points2[count+2]=Z;
                  count+=3;
                  if(lines == lcount)
                  g2.draw(new Line2D.Double((int)(scale*X)/(Z+scale)+x,(int)(scale*Y)/(Z+scale)+x,(int)(scale*X)/(Z+scale)+x,(int)(scale*Y)/(Z+scale)+x));
                  if(lines != lcount)
                  g2.draw(new Line2D.Double((int)(scale*X)/(Z+scale)+x,(int)(scale*Y)/(Z+scale)+x,(int)(scale*X2)/(Z2+scale)+x,(int)(scale*Y2)/(Z2+scale)+x));
                     lines--;
             for(int j = 0; j<points.length;j++)
             points[j]=points2[j];
    /*        if(zoom)
             System.out.println("Zoom");
             lines = points.length/3;
             lcount = lines;
             count =0;
             while(lines>0)
                   Z = points[count+2];
                  // if(Z<=0)
             //      Z+=zoomA;
             // if(Z>0)
                   Z-=zoomA;
                  X = points[count];
              //      if(X<=0)
            //       X+=zoomA;
            //       if(Z>0)
                   X-=zoomA;
                  Y = points[count+1];
        //           if(Y<=0)
      //             Y+=zoomA;
    //               if(Y>0)
                   Y-=zoomA;
                   points2[count]=X;     
                    points2[count+1]=Y;
                    points2[count+2]=Z;
                   if(lines == lcount)
                  g2.draw(new Line2D.Double((int)(scale*X)/(Z+scale),(int)(scale*Y)/(Z+scale),(int)(scale*X)/(Z+scale),(int)(scale*Y)/(Z+scale)));
                  if(lines != lcount)
                  g2.draw(new Line2D.Double((int)(scale*X)/(Z+scale),(int)(scale*Y)/(Z+scale),(int)(scale*X2)/(Z2+scale),(int)(scale*Y2)/(Z2+scale)));
                     lines--;     
             for(int j = 0; j<points.length;j++)
             points[j]=points2[j];
             if(showName)
                  g2.drawString("Made by Chris Hules", 350,300);
              rotateY = false;
              rotateX = false;
              rotateZ = false;
              showName = false;
              zoom = false;
        public static void main(String s[])
            JFrame f = new JFrame("3DTool");
            f.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {System.exit(0);}
            JApplet applet = new ThreeDTool(f);
            f.getContentPane().add("Center", applet);
            applet.init();
            f.pack();
            f.setSize(new Dimension(1000,700));
            f.show();
    }basicly... if you havent read through the code... arrow keys and mouse drag rotate the shape and - and = move the shape, there are a few bugs which i have to work out, there is another shape(located in the commented array) but if you use it you have to change variable sides to 2 instead of 3

    Hi some-guy94 :-)
    Both checkboxes concerning 3d acceleration are active, with vmplayer and also with virtualbox. For the last one, I've also spent 128 MB of graphical memory, but no way to make that f****g xmoto working in an arch guest with a reasonable speed.
    Ubuuuuuuuuuuntuuuu, one night before halloween, what's wrong here :-)
    Lots of love to all
    Eddi
    Last edited by etienne (2009-10-30 21:47:27)

  • Flash - Java - SerialData Translation issues

    This is for an art installation we're building in a gallery here in NYC. It opens Saturday, and we are in a jam with a problem.
    I'm using Dan O'Sullivan's Serial Server http://itp.nyu.edu/~dbo3/SerialServer/SerialServer.html , which is a little java server that connects to Flash via XML socket and to the serial port. It passes data back and forth since Flash doesn't talk to the serial port.
    The problem is this: Flash won't put the incoming data into the object and trigger the onData handler until it sees a null byte delimiter. On the other side, my serial device -- an encoder & adapter -- has no interest in producing a delimiter and cannot be programmed to do so. The data from the encoder is generally in the form of 4 bytes. You send it 1 byte to poll it.
    Thus the server app has to step in and patch things up, either (a) by indiscriminately appending 0's to everything it sees from the encoder (and figuring it all out in Flash) or better, (b) by having the server do the polling and keeping the current 4 bytes in a string, ready for when Flash requests it.
    This doesn't seem too bad - the server code is relatively simple - but I'm not a Java programmer (sorry, wish I were). I'm inserting the code here - any chance someone can help us out ... immediately?? Thanks very much.
    /Eric Liftin
    MESH Architectures http://mesh-arc.com
    * SerialServer.java
    * Title:               SerialServer
    * Description:          This relays bytes between a serial port and a socket connection.
    * @author               Administrator
    * @version               
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Frame;
    import java.awt.Toolkit;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.StringTokenizer;
    public class SerialServer extends java.applet.Applet  implements SerialListener {
         // IMPORTANT: Source code between BEGIN/END comment pair will be regenerated
         // every time the form is saved. All manual changes will be overwritten.
         // BEGIN GENERATED CODE
         // member declarations
         java.awt.Choice baud = new java.awt.Choice();
         java.awt.Checkbox interpretation = new java.awt.Checkbox();
         java.awt.Choice ports = new java.awt.Choice();
         java.awt.TextField socketPort = new java.awt.TextField();
         java.awt.Label softwarePort = new java.awt.Label();
         java.awt.Button sendToSocket = new java.awt.Button();
         java.awt.Button sendToSerial = new java.awt.Button();
         java.awt.TextField sendText = new java.awt.TextField();
         java.awt.TextArea traffic = new java.awt.TextArea();
         java.awt.Checkbox debugButton = new java.awt.Checkbox();
         java.awt.Label socketStatus = new java.awt.Label();
         java.awt.Label serialStatus = new java.awt.Label();
         java.awt.Label numbersFootnote = new java.awt.Label();
         java.awt.Button clearButton = new java.awt.Button();
         java.awt.Button cover = new java.awt.Button();
         // END GENERATED CODE
         String serialType = null;
         static Socketer mySocket;
         static Serial mySerial;
         boolean isStandalone = false;
         static boolean debug = false;
         public SerialServer() {}
         static HashMap argsHash;
         int substituteChar = 0;
         public void start() {
              //figure out what driver to use
              if (isStandalone == false) {
                        serialType =  getParameter("SerialDriver");
                   } else {
                        serialType = (String) argsHash.get("SerialDriver");
              if( serialType != null){  //if they did not specify
                   serialType= serialType.toLowerCase();
              newSerial();
              if (isStandalone == false) {
                   System.out.println("This is an Applet");
                   useParameters(getParameter("Baud"), getParameter("SerialPort"), getParameter("SocketPort"), getParameter("Sub0ForChar"), getParameter("SerialDriver"));
              } else {
                   useParameters((String) argsHash.get("Baud"), (String) argsHash.get("SerialPort"), (String) argsHash.get("SocketPort"), (String) argsHash.get("Sub0ForChar"),(String) argsHash.get("SerialDriver"));
              newSocket();
              connectSerial();
              //          event handling
              baud.addItemListener(new java.awt.event.ItemListener() {
                   public void itemStateChanged(java.awt.event.ItemEvent e) {
                        baudItemStateChanged(e);
              interpretation.addItemListener(new java.awt.event.ItemListener() {
                   public void itemStateChanged(java.awt.event.ItemEvent e) {
                        interpretationItemStateChanged(e);
              ports.addItemListener(new java.awt.event.ItemListener() {
                   public void itemStateChanged(java.awt.event.ItemEvent e) {
                        portsItemStateChanged(e);
              socketPort.addTextListener(new java.awt.event.TextListener() {
                   public void textValueChanged(java.awt.event.TextEvent e) {
                        socketPortTextValueChanged(e);
              sendToSocket.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        sendToSocketPerformed(e);
              sendToSerial.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        sendToSerialActionPerformed(e);
              sendText.addTextListener(new java.awt.event.TextListener() {
                   public void textValueChanged(java.awt.event.TextEvent e) {
                        sendTextTextValueChanged(e);
              ////     traffic.addTextListener(new java.awt.event.TextListener() {
              //     public void textValueChanged(java.awt.event.TextEvent e) {
              //          trafficTextValueChanged(e);
              debugButton.addItemListener(new java.awt.event.ItemListener() {
                   public void itemStateChanged(java.awt.event.ItemEvent e) {
                        debugItemStateChanged(e);
              clearButton.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        clearActionPerformed(e);
              //populatePorts();
         // Initialize the applet
         public void init() {
              try {
                   initComponents();
              } catch (Exception e) {
                   e.printStackTrace();
         public void useParameters(String _baud, String _serialPort, String _socketPort, String _subChar, String _serialType) {
              System.out.println("Input Parameters Baud:" + _baud + " SerialPort:" + _serialPort + " SocketPort:" + _socketPort + " SubChar:" + _subChar+ " SerialType:" + _serialType);
              if (_baud != null) {
                   baud.select(_baud);
              if (_subChar != null) {
                   substituteChar = Integer.parseInt(_subChar);
              } else {
                   substituteChar = 0;
              //else{
              //          baud.select("9600");
              if (_serialPort != null) {
                   ports.select(_serialPort);
              } //else{
              //     ports.select("COM1") ;
              //if ((_baud != null) || (_serialPort != null)){
              //     newSerial();
              if (_socketPort != null) {
                   socketPort.setText(_socketPort);
                   //     newSocket();
         public void initComponents() throws Exception {
              // IMPORTANT: Source code between BEGIN/END comment pair will be regenerated
              // every time the form is saved. All manual changes will be overwritten.
              // BEGIN GENERATED CODE
              // the following code sets the frame's initial state
              baud.setVisible(true);
              baud.setLocation(new java.awt.Point(222, 31));
              baud.setSize(new java.awt.Dimension(70, 21));
              interpretation.setVisible(true);
              interpretation.setLabel("Use decimals instead of letters.");
              interpretation.setLocation(new java.awt.Point(43, 175));
              interpretation.setSize(new java.awt.Dimension(200, 20));
              ports.setVisible(true);
              ports.setLocation(new java.awt.Point(222, 10));
              ports.setSize(new java.awt.Dimension(108, 21));
              socketPort.setLocation(new java.awt.Point(18, 10));
              socketPort.setVisible(true);
              socketPort.setText("9001");
              socketPort.setSize(new java.awt.Dimension(40, 20));
              softwarePort.setVisible(true);
              softwarePort.setLocation(new java.awt.Point(60, 10));
              softwarePort.setText("<Socket > ------------- <Serial>");
              softwarePort.setSize(new java.awt.Dimension(160, 20));
              sendToSocket.setVisible(true);
              sendToSocket.setLabel("<TestSend");
              sendToSocket.setLocation(new java.awt.Point(1, 60));
              sendToSocket.setSize(new java.awt.Dimension(80, 20));
              sendToSerial.setVisible(true);
              sendToSerial.setLabel("Test Send>");
              sendToSerial.setLocation(new java.awt.Point(279, 60));
              sendToSerial.setSize(new java.awt.Dimension(80, 20));
              sendText.setLocation(new java.awt.Point(82, 60));
              sendText.setVisible(true);
              sendText.setSize(new java.awt.Dimension(197, 20));
              traffic.setLocation(new java.awt.Point(5, 95));
              traffic.setVisible(true);
              traffic.setSize(new java.awt.Dimension(352, 80));
              debugButton.setFont(new java.awt.Font("Serif", 0, 12));
              debugButton.setVisible(true);
              debugButton.setLabel("debug");
              debugButton.setLocation(new java.awt.Point(130, 39));
              debugButton.setSize(new java.awt.Dimension(50, 20));
              socketStatus.setVisible(true);
              socketStatus.setAlignment(java.awt.Label.CENTER);
              socketStatus.setLocation(new java.awt.Point(65, 26));
              socketStatus.setSize(new java.awt.Dimension(45, 20));
              serialStatus.setVisible(true);
              serialStatus.setAlignment(java.awt.Label.CENTER);
              serialStatus.setLocation(new java.awt.Point(177, 26));
              serialStatus.setSize(new java.awt.Dimension(40, 20));
              numbersFootnote.setVisible(false);
              numbersFootnote.setLocation(new java.awt.Point(49, 79));
              numbersFootnote.setText("*Put spaces between numbers for test send.");
              numbersFootnote.setSize(new java.awt.Dimension(280, 20));
              clearButton.setVisible(true);
              clearButton.setLabel("Clear");
              clearButton.setLocation(new java.awt.Point(260, 178));
              clearButton.setSize(new java.awt.Dimension(58, 19));
              setLocation(new java.awt.Point(0, 0));
              setLayout(null);
              add(cover);
              add(baud);
              add(interpretation);
              add(ports);
              add(socketPort);
              add(softwarePort);
              add(sendToSocket);
              add(sendToSerial);
              add(sendText);
              add(traffic);
              add(debugButton);
              add(socketStatus);
              add(serialStatus);
              add(numbersFootnote);
              add(clearButton);
              setSize(new java.awt.Dimension(356, 274));
              // END GENERATED CODE
              baud.add("110");
              baud.add("300");
              baud.add("1200");
              baud.add("2400");
              baud.add("4800");
              baud.add("9600");
              baud.add("19200");
              baud.add("31250"); //   //31250
              baud.add("38400");
              baud.add("57600");
              baud.add("230400");
              baud.add("460800");
              baud.add("921600");
              baud.select("9600");
              cover.setVisible(true);
              //cover.setLayout(null);
              cover.setLocation(new java.awt.Point(-10, 57));
              cover.setSize(new java.awt.Dimension(964, 287));
         public void relayToSerial(int what) {
              boolean ok = mySerial.send(what).equals("OKAY");
              if (debug) {
                   socketStatus.setText("<IN>");
                   if (ok) {
                        serialStatus.setText("<OUT>");
                   showText(what);
         public void gotFromSerial(byte[] _byteArray){
         //public void relayToSocket(int what) {
             for(int i = 0; i < _byteArray.length; i++){
                 int what = (int) (_byteArray[i] & 0xff);
              if ((substituteChar != 0) && (what == substituteChar))
                   what = 0;
              boolean ok = mySocket.send(what).equals("OKAY");
              if (debug) {
                   serialStatus.setText("<IN>");
                   if (ok) {
                        socketStatus.setText("<OUT>");
                   showText(what);
         public void appendDebug(String what) {
              if (traffic.getText().toCharArray().length > 200)
                   traffic.setText(traffic.getText().substring(50));
              traffic.setText(traffic.getText() + "\n" + what + "\n");
              String strMessage = traffic.getText();
              traffic.setCaretPosition(strMessage.length());
         public void showText(int what) {
              if (interpretation.getState()) {
                   traffic.setText(traffic.getText() + " " + what);
              } else {
                   traffic.setText(traffic.getText() + ((char) what));
              String strMessage = traffic.getText();
              traffic.setCaretPosition(strMessage.length());
         // Standard method to start the applet
         //public void start() {
         //     newSocket();
         //     newSerial();
         public void populatePorts() {
              ports.removeAll();
              ArrayList portList = mySerial.getPortsList();
              for (int i = 0; i < portList.size(); i++) {
                   String[] portAndOwner = (String[]) portList.get(i);
                   System.out.println("owner" + portAndOwner[1]);
                   String port = portAndOwner[0];
                   String owner = portAndOwner[1];
                   //System.out.println(owner + " " + port + " number of Ports " + portList.size());
                   if (owner == null || owner.equals("Port currently not owned")) {
                        boolean alreadyThere = false;
                        for (int j = 0; j < ports.getItemCount(); j++) {
                             String alrdy = ports.getItem(j);
                             //System.out.println(port+ " Ports Already " + alrdy );
                             if (alrdy.equals(port)) {
                                  alreadyThere = true;
                                  break;
                        if (alreadyThere == false) {
                             ports.add(port);
                   } else {
                        System.out.println("Can't use it!" + port + owner);
                   //ports.add(((String) portList.get(i)));
         public void newSerial() {
              serialStatus.setText("!");
              mySerial = new Serial(this, serialType);
              if (ports.getItemCount() == 0) {
                   populatePorts();
         public void connectSerial() {
              if (ports.getItemCount() == 0) {
                   appendDebug("No serial ports found.");
              } else {
                   String status = mySerial.connect(ports.getSelectedItem(), Integer.parseInt(baud.getSelectedItem()));
                   if (status.startsWith("Got")) {
                        serialStatus.setText("<OK>");
                        //mySerial.start();
                   } else {
                        serialStatus.setText("Bad");
                        //populatePorts();
                   appendDebug(status);
         public void newSocket() {
              mySocket = new Socketer(Integer.parseInt(socketPort.getText()), this);
         public void socketStatus(String status) {
              if (status.startsWith("Got")) {
                   socketStatus.setText("<OK>");
              } else if (status.startsWith("Waiting")) {
                   socketStatus.setText("Waiting");
              } else {
                   socketStatus.setText("Bad");
              appendDebug(status);
         // Standard method to stop the applet
         public void stop() {
              mySerial.kill();
              mySocket.kill();
         // Standard method to destroy the applet
         public void destroy() {}
         // Main entry point when running standalone
         public static void main(String[] args) {
              SerialServer applet = new SerialServer();
              applet.isStandalone = true;
              Frame frame = new Frame();
              frame.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        Frame f = (Frame) e.getSource();
                        f.setVisible(false);
                        f.dispose();
                        System.exit(0);
              frame.setTitle("Serial Server");
              frame.add(applet, BorderLayout.CENTER);
              frame.setSize(400, 320);
              Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
              frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);
              frame.setVisible(true);
              applet.init();
              argsHash = new HashMap();
              for (int i = 0; i < args.length; i++) {
                   String pair = args;
                   String parts[] = pair.split(":");
                   if (parts.length == 2) {
                        argsHash.put(parts[0], parts[1]);
                   }else{
                        System.out.println("Problem with format of parameter "+ pair);
              applet.start();
              frame.pack();
         public void sendTextTextValueChanged(java.awt.event.TextEvent e) {}
         public void interpretationItemStateChanged(java.awt.event.ItemEvent e) {
              numbersFootnote.setVisible(interpretation.getState());
              System.out.println("Interpretation" + interpretation.isVisible());
         public void socketPortTextValueChanged(java.awt.event.TextEvent e) {
              mySocket.kill();
              mySocket = null;
              newSocket();
              System.out.println("Changed Socket");
         public void sendToSocketPerformed(java.awt.event.ActionEvent e) {
              if (interpretation.getState()) {
                   StringTokenizer st = new StringTokenizer(sendText.getText(), " ");
                   while (st.hasMoreTokens()) {
                        try {
                             int what = Integer.parseInt(st.nextToken());
                             if ((substituteChar != 0) && (what == substituteChar))
                                  what = 0;
                             //System.out.println(substituteChar + "debugSend" + what);
                             mySocket.send(what);
                        } catch (NumberFormatException nfe) {
                             System.out.println("You are are entering letters but you checked the decimal interpretation.");
              } else {
                   byte[] asbytes = sendText.getText().getBytes();
                   for (int i = 0; i < asbytes.length; i++) {
                        int what = asbytes[i];
                        if ((substituteChar != 0) && (what == substituteChar))
                             what = 0;
                        System.out.println(substituteChar + "debugSend" + what);
                        mySocket.send(what);
         public void sendToSerialActionPerformed(java.awt.event.ActionEvent e) {
              if (interpretation.getState()) {
                   StringTokenizer st = new StringTokenizer(sendText.getText(), " ");
                   while (st.hasMoreTokens()) {
                        try {
    mySerial.send(Integer.parseInt(st.nextToken()));
    } catch (NumberFormatException e1) {
         appendDebug("Enter a number.");
              } else {
                   byte[] asbytes = sendText.getText().getBytes();
                   for (int i = 0; i < asbytes.length; i++) {
                        mySerial.send(asbytes[i]);
         public void portsItemStateChanged(java.awt.event.ItemEvent e) {
              mySerial.kill();
              mySerial = null;
              newSerial();
              connectSerial();
              System.out.println("Serial Port Changed");
         public void baudItemStateChanged(java.awt.event.ItemEvent e) {
              mySerial.kill();
              mySerial = null;
              newSerial();
              connectSerial();
              System.out.println("Serial Baud Changed");
         public void debugItemStateChanged(java.awt.event.ItemEvent e) {
              debug = debugButton.getState();
              if (debug) {
                   cover.setLocation(-1000, -1000);
              } else {
                   cover.setLocation(-10, 57);
                   //cover.setVisible(true);
              //System.out.println("debugl Changed" + debug);
         public void clearActionPerformed(java.awt.event.ActionEvent e) {
              traffic.setText("");

    Whoops, I'll fix it up so it's more presentable
    for (int row = 0; row <= 8 ; row++){
        for (int column = 1; column <= row; column++ )
         System.out.print(" ");
        for (int i = 0; i < row; i++){
         System.out.print(" " + (int) Math.pow(2,i));
        for (int j = row-1; j >= 0; j--)
         System.out.print(" " + (int)Math.pow(2, j));
        System.out.println();
    }About the space, I was checking to see what adding and removing them would do, although even after fixing it I seem to get a bunched up mass.
    -edit-
    Another thing I've noted is that pasting the text here seems to throw off the indentations which look normal in eclipse.
    Edited by: Yummyfishman on Oct 5, 2007 8:33 PM
    Edited by: Yummyfishman on Oct 5, 2007 8:35 PM
    Edited by: Yummyfishman on Oct 5, 2007 8:36 PM
    Edited by: Yummyfishman on Oct 5, 2007 8:40 PM

  • Easy swing question for Java friends

    Hi could somebody test this short application and tell me why the "DRAW LINE" button doesnt draw a line as I expected?
    thank you very much!
    Circuitos.java:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.URL;
    import java.awt.geom.*;
    public class Circuitos extends JApplet {
         protected JButton btnRect;
         protected Terreno terreno;
         private boolean inAnApplet = true;
         //Hack to avoid ugly message about system event access check.
         public Circuitos() {
              this(true);
         public Circuitos(boolean inAnApplet) {
            this.inAnApplet = inAnApplet;
              if (inAnApplet) {
                   getRootPane().putClientProperty("defeatSystemEventQueueCheck",Boolean.TRUE);
         public void init() {
              setContentPane(makeContentPane());
         public Container makeContentPane() {
              btnRect = new JButton("DRAW LINE");
          btnRect.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                terreno.pintarTramo();
              terreno = new Terreno();
              JPanel panel = new JPanel();
              panel.setLayout(new BorderLayout());
              panel.add("North",btnRect);
              panel.add("Center",terreno);
              return panel;
         public static void main(String[] args) {
            JFrame frame = new JFrame("Dise�o de Circuitos");
              frame.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              Circuitos applet = new Circuitos(false);
              frame.setContentPane(applet.makeContentPane());
              frame.pack();
              frame.setVisible(true);
    }Terreno.java:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.geom.*;
    public class Terreno extends JPanel {
         Graphics2D g2;
         public Terreno() {
              setBackground(Color.red);
              setPreferredSize(new Dimension(500,500));
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
          g2 = (Graphics2D) g;
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);    
         public void pintarTramo () {     
              Point2D.Double start   = new Point2D.Double(250,250);
              Point2D.Double end     = new Point2D.Double(250,285);
              g2.draw(new Line2D.Double(start,end));            
    }

    I don't think the date I became a member has anything to do with it. Yes, I signed up a year ago to ask a question or two when I didn't know anything. It wasn't until recently have I started to use this forum again, only to try and help people as well as ask my questions. It took me a year to get to this point to where I can actually answer questions instead of just asking. So don't be silly and judge a person based on their profile.
    Secondly, I agree with you, the search utility is great. I use it all the time and usually I'll find my answers, but if I don't is it such a pain in the butt for you to see the same problem posted again?? I know how much you want people to use the resources available before wasting forum space with duplicate questions, but it's not going to happen. Some people are not as patient and you being a butt about it won't stop it.
    My point in general is that there are nice ways to help people and even rude ways, and your comments at times come across rude to me, even condescending. You have a lot of knowledge, therefore certain things seem trivial to you... but try to understand where some of the new people are coming from. The Swing tutorial is extremely helpful but if you don't understand the concept of programming or java that well... then it can be overwhelming and you don't know where to start. It's a huge tutorial and when people are stuck they just want an answer to their one question. Most figure it's easier to ask someone who already knows instead of reading an entire tutorial to get their answer.
    I've learned by both methods, by taking the time to research it myself and by asking a lot of questions. I have the time. Some don't. Please realize that not everyone is like you and they will continue to ask whether you like it or not. You have a choice, either help them or not.

  • Adding java 2d graphices to a JScrollPane

    How can I use the graphics 2d in a Java Applet JScrollPane?
    here is me code. I have a a ImageOps.java file that does a bunch of Java 2d, but I need it to fit into my applet's JScrollPane. Can anyone help me?
    package louis.tutorial;
    import java.awt.BorderLayout;
    import javax.swing.JPanel;
    import javax.swing.JApplet;
    import java.awt.Dimension;
    import javax.swing.JInternalFrame;
    import javax.swing.JButton;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GridBagLayout;
    import java.awt.GridBagConstraints;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import java.awt.Image;
    import java.awt.MediaTracker;
    import java.awt.Rectangle;
    import java.awt.Point;
    import javax.swing.JComboBox;
    import javax.swing.JList;
    import javax.swing.JTextArea;
    import javax.imageio.ImageIO;
    import javax.swing.Icon;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JLabel;
    import javax.swing.JMenuItem;
    import javax.swing.ImageIcon;
    import javax.swing.KeyStroke;
    import java.awt.FileDialog;
    import java.awt.Toolkit;
    import java.awt.Color;
    import java.awt.image.BufferedImage;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.File;
    import java.io.IOException;
    import java.net.URL;
    import javax.swing.JScrollPane;
    * Place class description here
    * @version 1.0
    * @author llakser
    public class ImageApplet extends JApplet {
    private JPanel jContentPane = null;
    private JPanel jpLower = null;
    private JButton JBFirst = null;
    private JButton JBPrevious = null;
    private JButton JBNext = null;
    private JButton JBLast = null;
    private JButton JBZoonIn = null;
    private JButton JBZoomOut = null;
    private JButton JBAnimate = null;
    private JButton JBPause = null;
    private JButton JBAutoRepeat = null;
    private JComboBox jcbFrameDelay = null;
    private BufferedImage image; // the rasterized image
    private Image[] numbers = new Image[10];
    private Thread animate;
    private MediaTracker tracker;
    private int frame = 0;
    private ImageIcon[] icon = null;
    private JFrame f = new JFrame("ImageOps");
    * This is the xxx default constructor
    public ImageApplet() {
         super();
    * This method initializes this
    * @return void
    public void init() {
         this.setSize(600, 600);
         this.setContentPane(getJContentPane());
         this.setName("");
         this.setMinimumSize(new Dimension(600, 600));
         this.setPreferredSize(new Dimension(600, 600));
    // f.addWindowListener(new WindowAdapter() {
    // public void windowClosing(WindowEvent e) {System.exit(0);}
    ImageOps applet = new ImageOps();
    //getJContentPane().add("Center", f);
    getJContentPane().add("Center", applet);
    //applet.add(f);
    applet.init();
    f.pack();
    f.setSize(new Dimension(550,550));
    f.setVisible(true);
    public void load() {
         tracker = new MediaTracker(this);
         for (int i = 1; i < 10; i++) {
         numbers[i] = getImage (getCodeBase (), i+".jpeg");//getImage(getDocumentBase(), "Res/" + i + ".gif");
         //Image img;
         //ico[i] = new ImageIcon(getCodeBase (), i+".jpeg");
         /* if (fInBrowser)
         img = getImage (getCodeBase (), "1.jpeg");
         else
         img = Toolkit.getDefaultToolkit ().getImage (
         "1.jpeg");*/
         tracker.addImage(numbers, i);
         try {
         tracker.waitForAll();
         } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
         int i = 1;
         // for (int i = 1; i < 10; i++)
              icon[0] = new ImageIcon ("C:/images2/1.jpeg");//getImage(getDocumentBase(), "Res/" + i + ".gif");
              //icon[0] = new ImageIcon("C:/images2/1.jpg");
              //System.out.println("Made it after icon " + ico.toString());
              //ImageIcon ii = new ImageIcon("1.jpg");
              //jLabel = new JLabel(icon);
              //jLabel.setText("JLabel");
              //jLabel.setIcon(icon[0]);
         Graphics g = null;
              //g.drawImage(numbers[1],0,0,1500,1400,jScrollPane);
         //ImageIcon ii = new ImageIcon(numbers[2]);
         //this.jScrollPane.add(new JLabel(ii));// = new JScrollPane(new JLabel(ii));
         // System.out.println("Gee I made it..");
              //scroll.paintComponents(g);
              //paintComponents(g);
    public void paintComponents(Graphics g) {
    super.paintComponents(g);
    // Retrieve the graphics context; this object is used to paint shapes
    Graphics2D g2d = (Graphics2D)g;
    // Draw an oval that fills the window
    int width = this.getBounds().width;
    int height = this.getBounds().height;
    Icon icon = new ImageIcon("C:/images2/1.jpg");
    //jLabel.setIcon(icon);
    //g2d.drawImage(0,0,1500,1400);
    g2d.drawOval(10,20, 300,400);
    // and Draw a diagonal line that fills MyPanel
    g2d.drawLine(0,0,width,height);
    * This method initializes jContentPane
    * @return javax.swing.JPanel
    private JPanel getJContentPane() {
         if (jContentPane == null) {
         jContentPane = new JPanel();
         jContentPane.setLayout(new BorderLayout());
         jContentPane.setPreferredSize(new Dimension(768, 576));
         jContentPane.setMinimumSize(new Dimension(768, 576));
         jContentPane.setName("");
         jContentPane.add(getJpLower(), BorderLayout.SOUTH);
         return jContentPane;
    * This method initializes jpLower     
    * @return javax.swing.JPanel     
    private JPanel getJpLower() {
    if (jpLower == null) {
         try {
         jpLower = new JPanel();
         jpLower.setLayout(null);
         jpLower.setPreferredSize(new Dimension(500, 100));
         jpLower.setMinimumSize(new Dimension(500, 160));
         jpLower.add(getJBFirst(), null);
         jpLower.add(getJBPrevious(), null);
         jpLower.add(getJBNext(), null);
         jpLower.add(getJBLast(), null);
         jpLower.add(getJBZoonIn(), null);
         jpLower.add(getJBZoomOut(), null);
         jpLower.add(getJBAnimate(), null);
         jpLower.add(getJBPause(), null);
         jpLower.add(getJBAutoRepeat(), null);
         jpLower.add(getJcbFrameDelay(), null);
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return jpLower;
    * This method initializes JBFirst     
    * @return javax.swing.JButton     
    private JButton getJBFirst() {
    if (JBFirst == null) {
         try {
         JBFirst = new JButton();
         JBFirst.setText("First");
         JBFirst.setLocation(new Point(7, 7));
         JBFirst.setSize(new Dimension(59, 26));
         JBFirst.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent e) {
              System.out.println("First Button Clicked()");
         load();
              // TODO Auto-generated Event stub actionPerformed()
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBFirst;
    * This method initializes JBPrevious     
    * @return javax.swing.JButton     
    private JButton getJBPrevious() {
    if (JBPrevious == null) {
         try {
         JBPrevious = new JButton();
         JBPrevious.setText("Previous");
         JBPrevious.setLocation(new Point(69, 7));
         JBPrevious.setSize(new Dimension(94, 26));
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBPrevious;
    * This method initializes JBNext     
    * @return javax.swing.JButton     
    private JButton getJBNext() {
    if (JBNext == null) {
         try {
         JBNext = new JButton();
         JBNext.setText("Next");
         JBNext.setLocation(new Point(166, 7));
         JBNext.setSize(new Dimension(66, 26));
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBNext;
    * This method initializes JBLast     
    * @return javax.swing.JButton     
    private JButton getJBLast() {
    if (JBLast == null) {
         try {
         JBLast = new JButton();
         JBLast.setText("Last");
         JBLast.setLocation(new Point(235, 7));
         JBLast.setSize(new Dimension(59, 26));
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBLast;
    * This method initializes JBZoonIn     
    * @return javax.swing.JButton     
    private JButton getJBZoonIn() {
    if (JBZoonIn == null) {
         try {
         JBZoonIn = new JButton();
         JBZoonIn.setText("Zoom In");
         JBZoonIn.setLocation(new Point(408, 7));
         JBZoonIn.setPreferredSize(new Dimension(90, 26));
         JBZoonIn.setSize(new Dimension(90, 26));
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBZoonIn;
    * This method initializes JBZoomOut     
    * @return javax.swing.JButton     
    private JButton getJBZoomOut() {
    if (JBZoomOut == null) {
         try {
         JBZoomOut = new JButton();
         JBZoomOut.setBounds(new Rectangle(503, 7, 90, 26));
         JBZoomOut.setPreferredSize(new Dimension(90, 26));
         JBZoomOut.setText("Zoom Out");
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBZoomOut;
    * This method initializes JBAnimate     
    * @return javax.swing.JButton     
    private JButton getJBAnimate() {
    if (JBAnimate == null) {
         try {
         JBAnimate = new JButton();
         JBAnimate.setText("Animate");
         JBAnimate.setSize(new Dimension(90, 26));
         JBAnimate.setPreferredSize(new Dimension(90, 26));
         JBAnimate.setLocation(new Point(408, 36));
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBAnimate;
    * This method initializes JBPause     
    * @return javax.swing.JButton     
    private JButton getJBPause() {
    if (JBPause == null) {
         try {
         JBPause = new JButton();
         JBPause.setPreferredSize(new Dimension(90, 26));
         JBPause.setLocation(new Point(503, 36));
         JBPause.setSize(new Dimension(90, 26));
         JBPause.setText("Pause");
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBPause;
    * This method initializes JBAutoRepeat     
    * @return javax.swing.JButton     
    private JButton getJBAutoRepeat() {
    if (JBAutoRepeat == null) {
         try {
         JBAutoRepeat = new JButton();
         JBAutoRepeat.setBounds(new Rectangle(446, 65, 106, 26));
         JBAutoRepeat.setText("Auto Repeat");
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBAutoRepeat;
    * This method initializes jcbFrameDelay     
    * @return javax.swing.JComboBox     
    private JComboBox getJcbFrameDelay() {
    if (jcbFrameDelay == null) {
         try {
         jcbFrameDelay = new JComboBox();
         jcbFrameDelay.setSize(new Dimension(156, 25));
         jcbFrameDelay.setName("Frame Delay");
         jcbFrameDelay.setLocation(new Point(7, 35));
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return jcbFrameDelay;
    } // @jve:decl-index=0:visual-constraint="10,10"

    I think you've got it:
    public class ImageComponent extends JPanel { //or JComponent
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            //do your rendering here
    }The fact that ImageComponent sits inside JScrollPane is accidental, right?
    It should be able to function on its own, without a JScrollPane present, just as JTextArea can.
    So I'm not sure what your question is. Can you post a small (<1 page)
    example program demonstrating your problem.
    For example, here are a very few lines demonstrating what I am trying to say:
    import java.awt.*;
    import javax.swing.*;
    class CustomExample extends JPanel {
        public CustomExample() {
            setPreferredSize(new Dimension(800,800));
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.fillOval(0, 0, getWidth(), getHeight());
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable(){
                public void run() {
                    JFrame f = new JFrame("CustomExample");
                    f.getContentPane().add(new JScrollPane(new CustomExample()));
                    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    f.setSize(400,400);
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
    }Now you post your problem in a program that is just as short.

  • Annoying program, please help

    I wrote an JFrame draw program which can work well by itself class D. However, when I call it from the other class B using B's JFrame, the drawing can't display. What happens?
    import java.io.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class D extends JApplet{
        public void init() {
        public void paint(Graphics g) {
      Graphics2D g2=(Graphics2D)g;
         g2.draw(new Line2D.Double(0,0,100,100));
    /*public static void main(String[] args){
            JFrame f = new JFrame("2D draw");
            f.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {System.exit(0);}
            JApplet applet = new D();
            f.getContentPane().add("Center", applet);
            applet.init();
            f.pack();
            f.setSize(new Dimension(500,500));
            f.show();
    When I use in B class:
    JFrame f=new JFrame();
    Container content=f.getContentPane();
    JButton button4=new JButton("Test");
         ActionListener b4_al=new ActionListener(){
                 public void actionPerformed(ActionEvent ae){
                    try{
                    JApplet applet = new D();
                   content.add("Center", applet);
                   applet.init();
                   f.pack();
                   f.setSize(new Dimension(500,500));
                   f.show(true);
           }catch (Exception e){}
            button4.addActionListener(b4_al);

    Worked for me.
    Some few changes I made (had to make the frame final,
    add the button to the frame, size and show the frame).
    (sorry 'bout name of MouseMoveTest, just use it as my general test file now...)
    import java.io.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MouseMoveTest {
      public static void main (String[] args) {
           final JFrame f=new JFrame();
           final Container content=f.getContentPane();
           JButton button4=new JButton("Test");
           ActionListener b4_al=new ActionListener(){
                public void actionPerformed(ActionEvent ae){
                     try{
                          JApplet applet = new D();
                          content.add("Center", applet);
                          applet.init();
                          f.pack();
                          f.setSize(new Dimension(500,500));
                          f.show(true);
                     }catch (Exception e){}
           button4.addActionListener(b4_al);
           content.add(button4);
           f.setSize(new Dimension(500,500));
           f.show(true);
    class D extends JApplet {
         public void init() {
         public void paint(Graphics g) {
              Graphics2D g2=(Graphics2D)g;
              g2.draw(new Line2D.Double(0,0,100,100));
    }

  • Java Card 3.0.1 Debugger Netbeans

    Hello,
    i want to use the debugger with netbeans but it doesn't work the excpected way.
    So i used Mini.calss created with java 1.3 and the hte -g option.
    i startet debugproxy with debugproxy -c Mini.class
    i attached the netbeans ide to the debugproxy port.
    i started cjcre -debugger.
    so far so good.
    But the only thing i can see in netbeans is a list of threads.
    I can't see any source code or something like this.
    What i want to have is a debugger like the eclipse debugger: i can see what i am doing and can follow everything stept by step.
    So what i have to do in oder to run it like in eclipse.
    Thanks a lot.
    byebye

    So I done it.
    I was stupid. Right way how to build and install your applet:
    go to samples folder, select project that looks like your, copy it, replace *.java with yours, correct build-impl.xml and some other files if needed, run ant like that:
    set JAVA_HOME=D:\JDK\j2sdk1.6_16
    set PATH = ANT_HOME\bin;%PATH%
    D:\ANT\bin\ant.bat run
    everything goes right - applet builded, converted, packed, loaded & create into simulator eeprom
    than run cjcre.exe -resume -e2pfile cjcre.eeprom
    and connect from your host app

  • Update 10.6.8 and the combo pack v1.1 but java applets still not working

    Checked all the java settings in the browsers and in java preferences and they are correct.
    Tried both Firefox 5.0.1 and Safari 5.0.5 (6533.21.1) neither worked. Runing Java SE 6 (both 64 and 32 bit) version 1.6.0_26-b03-384
    Even tried to uncheck and disable then re-enable java and restart, cleared cache, etc. Tried it all.
    Thought the combo update version 1.1 would help. Nope didn't do anything.
    Wanted to upgrade the OS today, so installed all current updates. Never upgraded the OS because I want to have this fixed first.
    I don't use time machine since I don't store my folder system locally, so I can't revert back before the OS updates. Don't want to reinstall the OS, actually can't even remember where I put it. Any suggestions? When is the issue going to be fixed?
    Checked around on a dozen or so message boards, seems like this is happen quite a bit. Even heard upgrading to the new OS has the same issue.
    So, fustrated. Need the java applet working asap.

    None of those things you mentioned were what I suggested.
    I'm guessing the "ctrl click in printer preferences" means you Reset the Printing System?
    If so, that is what I would have suggested if deleting it by selecting the ( - ) button and then adding it with the ( + ) button.
    But, if HP has a fix, it likely needs to update its drivers.

  • Problem: Applets cannot Create SOAP Message Objects using JAX Pack

    Hi all
    I want to invoke a simple webservice located at a url.
    I wish to send a SOAP Message . The Message is creating using
    javax.xml.soap package
    Here is the code
    public void init(){
    try{
    MessageFactory MF = MessageFactory.newInstance();
    SOAPMessage message = MF.createMessage();
    SOAPPart SP = message.getSOAPPart();
    SOAPEnvelope SE = SP.getEnvelope();
    SOAPHeader SH = SE.getHeader();
    SOAPBody SB = SE.getBody();
    Name bodyName = SE.createName
    ("testString","L","http://tempuri.org/");
    SOAPBodyElement SBE = SB.addBodyElement(bodyName);
    }catch(Exception e){}
    When I run the applet in a browser I am getting ExceptionInInitializerError or NullPointer Exception.
    The same application works when i run as a standalone application. But not in APPLET.
    Can somebody help me in this regard

    Im trying to do the same thing !!, i have a servlet that processes SOAP messages, and return SOAP messages back.
    Like you i have a implementation running with a stand alone client instead of an applet, which runs fine (there are several .jar files that have to be included in the jre/lib/ext directory, in total about a meg!).
    Im now looking to incorporate this client into an applet, but it moans about cannot find classes (the JAXM and SOAP classes).
    Have you found a solution to this yet ?? Surely you cannot expect the user to download all the required jar files along with the applet??
    With regards to your problem try setting up a button that fires off the SOAP Msg and processes the response, i read on the Sun Java Applet tutorials that some code should stay out of the init method(its a bit vague about WHAT should stay out..), maybe this is an example.
    Thanks,
    (i dont really expect a response as you posted this ages ago !!, but it would be nice.)

Maybe you are looking for