JApplet, JButtons (Desperate)

Create a JApplet which displays a smiley face (with eyes and mouth) upon startup. Provide two JButtons, labeled "Change Expression" and "Change Color". The "Change Expression" button should cause the face to toggle between a smile and a frown.The "Change Color" button should toggle the fill color of the face between two different colors of your choice, or randomly-generated colors.
Please, can anyone help with this? I welcome any and all help.
Thanks
Jewel24

Kaj, It is Homework. I think that if I could just get this part to get me started. That would be a big help. Create a JApplet which displays a smiley face (with eyes and mouth) upon startup

Similar Messages

  • JApplet not found in Internet Explorer 5.0

    I learning how works JApplet's, but I Have a problem.
    Somebody can say to me because my code does not work?
    My code:
    import javax.swing.JApplet;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    public class JAppletExample extends JApplet
    JButton jb;
    BorderLayout layout;
    public void init()
    layout=new BorderLayout(20,10);
    this.setLayout(layout);
    jb=new JButton("prueba ");
    this.add("Center",jb);
    public void start() { }
    This is the error message from the Java Console:
    java.lang.ClassNotFoundException: javax.swing.JApplet
         at com/ms/vm/loader/URLClassLoader.loadClass
         at java/lang/ClassLoader.loadClassInternal
         at java/lang/ClassLoader.resolveClass
         at com/ms/vm/loader/URLClassLoader.loadClass
         at com/ms/vm/loader/URLClassLoader.loadClass
         at com/ms/applet/AppletPanel.securedClassLoad
         at com/ms/applet/AppletPanel.processSentEvent
         at com/ms/applet/AppletPanel.processSentEvent
         at com/ms/applet/AppletPanel.run
         at java/lang/Thread.run
    Thanks in advance.

    You can force Internet Explorer to use the Sun Java Plugin by changing this key into windows registry:
    Registry>HKEY_LOCAL_MACHINE>SOFTWARE>JavaSoft>Java Plug-in>1.4.1_02>UseJava2Iexplorer
    Modify the value REG_DWORD from 0x00000000 (0) to 0x00000001 (1). This way you force IE to use your installed Sun Java Virtual Machine (with Swing support) instead the old Microsoft Virtual Machine.

  • Help JApplet not co-operating

    Hello.. i have the following code which is just like a pulldown menu in an applet on the web. it wokrs fine (u can test it ) but whenever the mouse leaves the button the menuitems remains. i want to implement a mouse or focus action so that when the mouse leaves the buttons or menuitems the menuitems disappear. try compiling and see it for ur self (it is error free).
    Thanks.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test extends JApplet
         JButton button, button2;
         JPopupMenu jpop, jpop1;
         JMenuItem i1 [], i2 [];
         JMenu m2, m3, m4;
         String si1[] = {"Home", "Corporate Profile", "Our Mission", "Our Clients" , "Careers @ CT Limited"};
         String si2[] = {"Debit Card processing", "Credit Card processing", "Stored Value Card", "Card Personalization", "Card Printing", "Sales of POSs", "ATM Management"};
         String si3[] = {"Virtual Payment Processes", "e-Payment Solutions", "Proprietary Bank Card"};
         String si4[] = {"Biller Service Solutions", "Biller Service Provider", "Merchant Processing"};
    public void init ()
         getContentPane().setLayout (new FlowLayout());
         requestFocus();
         jpop = new JPopupMenu ();
         jpop1 = new JPopupMenu ();
         i1 = new JMenuItem [5];
         for (int i = 0; i < si1.length; i++)
              i1[i] = new JMenuItem (si1);
              jpop.add (i1[i]);
              jpop.addSeparator();
         m2 = new JMenu ("ETF and Card");
         m3 = new JMenu ("Electronic Banking (e-banking) ");
         m4 = new JMenu ("Electronic Presentment & Payment ");
         jpop1.add (m2);
         jpop1.add (m3);
         jpop1.add (m4);
         i2 = new JMenuItem [7];
         for (int i = 0; i < si2.length; i++)
              i2 [i] = new JMenuItem (si2[i]);
              m2.add (i2[i]);
              m2.addSeparator();
         button = new JButton ("Move your mouse here");
         getContentPane().add (button);
         button.addMouseListener (new MouseAdapter ()
              public void mouseEntered(MouseEvent evt)
                   jpop.show (button, 0,25);
         button2 = new JButton ("Move your mouse here");
         getContentPane().add (button2);
         button2.addMouseListener (new MouseAdapter ()
              public void mouseEntered(MouseEvent evt)
                   jpop1.show (button2, 0,25);
         getContentPane().addMouseListener (new MouseAdapter ()
              public void mouseEntered(FocusEvent me)
                   jpop.hide();
                   repaint();

    Any solution ?....
    Thanks.

  • Clearing a Screen in JApplet

    How do I totally clear a screen in JApplet? For exmaple, the following code below adds the JLabel "next" over the JButton "go" after th button is clicked, but I can still see the "go" button under the text. Is there a way to clear the screen before adding the JLabel "next"? Thank you.
       import java.awt.*;
       import java.awt.event.*;
       import javax.swing.*;
        public class TestValidate extends JApplet
          JButton go;
          JLabel next;
           public void init()
             go = new JButton("Go");
             getContentPane().setLayout(new FlowLayout());
             getContentPane().add(go);
             go.addActionListener(new goListener());
           public void next()
             next = new JLabel("Next");
             getContentPane().removeAll();
             getContentPane().add(next);
             getContentPane().validate();
           public class goListener implements ActionListener
              public void actionPerformed(ActionEvent e)
                next();
       }

    use the repaint() method
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TestValidate extends JApplet
         JButton go;
        JLabel next;
        public void init()
              go = new JButton("Go");
            getContentPane().setLayout(new FlowLayout());
            getContentPane().add(go);
            go.addActionListener(new goListener());
        public void next()
              next = new JLabel("Next");
            getContentPane().removeAll();
            getContentPane().add(next);
            getContentPane().validate();
            repaint();
        public class goListener implements ActionListener
              public void actionPerformed(ActionEvent e)
                   next();
    }

  • Can check the code for me??

    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    import java.applet.*;
    public class Mplayer extends Applet
         JButton openButton;
         JButton cancelButton;
         JFileChooser fc;
         int returnVal;
         public void init()
              fc = new JFileChooser();
              returnVal = fc.showOpenDialog(this);
         public void start()
              if(returnVal == JFileChooser.APPROVE_OPTION)
                   File file = fc.getSelectedFile();
                   String path = file.getPath();
                   System.out.println("Opening: " +file.getPath());
              else
                   System.out.println("Cancelled by user");
    -- this code can be compiled, but when i open this applet, the 1st error is about java.security.AccessControlException, i think got some problem about " returnVal = fc.showOpenDialog(this);".. can help me to figure out..?? --

    Try this: this (ie: 'grant{ ...' isn't an Internet solution but it should allow you to use your app locally in appletviewer and develop your skills unhindered
    // not tested
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    public class Mplayer extends JApplet{
       JButton openButton;
       JButton cancelButton;
       JFileChooser fc= new JFileChooser();
       int returnVal;
       public void init(){
          grant{ permission java.security.AllPermission; };
          returnVal = fc.showOpenDialog(this);
          if(returnVal == JFileChooser.APPROVE_OPTION){
             File file = fc.getSelectedFile();
             String path = file.getPath();
             System.out.println("Opening: " +file.getPath());
          else System.out.println("Cancelled by user");

  • Java.lang.NullPointerException what?

    how could i fix the error java.lang.NullPointerException associated with this code?
    import java.applet.Applet;
    import java.awt.*;
    import javax.swing.*;
    public class Visual extends JApplet {
    JButton[] theCase;
    public Visual() {
                   theCase = new JButton[26];
                   ImageIcon[] casePic;
                   casePic = new ImageIcon[26];
    for(int caseImgLoop=0; caseImgLoop<26; caseImgLoop++)
                        casePic[caseImgLoop] = new ImageIcon("H:/Images/caseF" + (caseImgLoop + 1) + ".jpg");
    for(int caseLoop=0; caseLoop<26; caseLoop++)
                        //error on the next line
                        theCase[caseLoop].setIcon(casePic[caseLoop]);
                        theCase[caseLoop].setBorder(BorderFactory.createEmptyBorder());
    public void init() {
                   Visual go = new Visual();
                   setSize(400,300);
    }

    casePic[caseImgLoop] = new ImageIcon("H:/Images/caseF" + (caseImgLoop + 1) + ".jpg");You knew you needed to actually create the ImageIcon objects in this array, so why did you not do likewise for the theCase array of JButton objects? You never created the JButton objects, so when you got to this line:
    theCase[caseLoop].setIcon(casePic[caseLoop]);theCase[caseLoop] == null at this point.

  • Focus with JComboBox? HELP!!!

    How do you set the focus for a JComboBox? When I use the addFocusListener on a JComboBox it does NOT gain or lose any focus. But when applied to a JButton you'll see it gain and lose focus. Is this a bug in java for the JComboBox?
    Here's an example of the usage
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test extends JApplet {
    MyFocusListener focuslistener = new MyFocusListener();
    JButton button_1 = new JButton("regular button 1");     
    JComboBox combo_2 = new JComboBox(new Object[] { "item1", "item2" } );
         public void init() {
              Container contentPane = getContentPane();
              combo_2.setNextFocusableComponent(button_1);
              button_1.addFocusListener(focuslistener);
    combo_2.addFocusListener(focuslistener); //<--------- Add listener here
              contentPane.setLayout(new FlowLayout());
              contentPane.add(button_1);
              contentPane.add(combo_2);
    class MyFocusListener implements FocusListener
              public void focusGained(FocusEvent e)
                   Object object = e.getSource();
                   System.out.println("OBJECT: " + object);          
              public void focusLost(FocusEvent e)
              System.out.println("Focus lost" + e);

    This is a quick hack to the focuslistener added to a JComboBox. I noticed that inorder to obtain some focus on a JComboBox you must requestFocus on it. Therefore what I do is I requestFocus right after the button has lost focus. Might not be the best thing to do but it's a quick hack.
    Code listed below.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test extends JApplet {
    JButton button_1 = new JButton("regular button 1");     
    JComboBox combo_2 = new JComboBox(new Object[] { "item1", "item2" } );
    MyFocusListener focuslistener = new MyFocusListener();
    MyComboListener combolistener = new MyComboListener();
         public void init() {
              Container contentPane = getContentPane();
              combo_2.setNextFocusableComponent(button_1);
    button_1.addFocusListener(focuslistener);
    combo_2.addFocusListener(combolistener);
              contentPane.setLayout(new FlowLayout());
              contentPane.add(button_1);
              contentPane.add(combo_2);
    button_1.requestFocus();
    class MyFocusListener implements FocusListener
              public void focusGained(FocusEvent e)
                   Object object = e.getSource();
                   System.out.println("Button gained Focus");          
              public void focusLost(FocusEvent e)
              System.out.println("Button lost Focus");
    combo_2.requestFocus(); //<------------ This is the trick
    class MyComboListener implements FocusListener
    public void focusGained(FocusEvent e)
                   Object object = e.getSource();
                   System.out.println("COMBO gained Focus");          
              public void focusLost(FocusEvent e)
              System.out.println("COMBO lost Focus");
    }

  • Having trouble with my signed applet(if it's properly signed that is)

    hi
    I'm having trouble with my supposedly signed applet. I'm trying to execute a specific program in this case trilian from my browser. i'm using firefox
    first my java code
    package applet;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class RunApplet extends JApplet {
        JButton jButton = new JButton();
        FlowLayout flowLayout1 = new FlowLayout();
        public RunApplet() {
            try {
                init();
            } catch (Exception ex) {
                ex.printStackTrace();
        private void init() throws Exception {
            try {
                this.getContentPane().setLayout(flowLayout1);
                this.setSize(new Dimension(100, 200));
                jButton.setText("Trillian");
                jButton.addActionListener(new RunApplet_jButton_actionAdapter(this,
                        "\"C:\\Program Files\\Trillian\\trillian.exe\""));
                this.getContentPane().add(jButton, null);
            } catch (Exception e) {
                e.printStackTrace();
    class RunApplet_jButton_actionAdapter implements ActionListener {
        private RunApplet adaptee;
        private String programPath;
        RunApplet_jButton_actionAdapter(RunApplet adaptee, String programPath) {
            this.adaptee = adaptee;
            this.programPath = programPath;
        public void actionPerformed(ActionEvent e) {
            try {
                Runtime.getRuntime().exec(this.programPath);
            } catch (IOException ex) {
    }And my applet code
    <html>
    <body>
    <!--"CONVERTED_APPLET"-->
    <!-- HTML CONVERTER -->
    <object
        classid = "clsid:CAFEEFAC-0015-0000-0005-ABCDEFFEDCBA"
        codebase = "http://java.sun.com/update/1.5.0/jinstall-1_5_0_05-windows-i586.cab#Version=5,0,50,5"
        >
        <PARAM NAME = CODE VALUE = "applet.RunApplet.class" >
        <PARAM NAME = ARCHIVE VALUE = "myfile.jar" >
        <param name = "type" value = "application/x-java-applet;jpi-version=1.5.0_05">
        <param name = "scriptable" value = "false">
        <comment>
         <embed
                type = "application/x-java-applet;jpi-version=1.5.0_05" \
                CODE = "applet.RunApplet.class" \
                ARCHIVE = "myfile.jar"
             scriptable = false
             pluginspage = "http://java.sun.com/products/plugin/index.html#download">
             <noembed>
                </noembed>
         </embed>
        </comment>
    </object>
    <!--
    <applet CODE = "applet.RunApplet.class" ARCHIVE = "myfile.jar">
    </applet>
    -->
    <!--"END_CONVERTED_APPLET"-->
    </body>
    </html>Creating my key:
    keytool -genkey -alias sitekey -keystore "C:\Program Files\Java\jdk1.5.0_05\jre\lib\security\cacerts"Now the process of creating the jar file and signing it:
    1. jar cf myfile.jar *.class
    2. jarsigner -keystore "C:\Program Files\Java\
    jdk1.5.0_05\jre\lib\security\cacerts" myfile.jar sitekeyNow this is the way i've been using then and the first time i get the "do you want to trust" screen but still i get a security exception.
    Exception in thread "AWT-EventQueue-10" java.security.AccessControlException: access denied (java.io.FilePermission <<ALL FILES>> execute)
         at java.security.AccessControlContext.checkPermission(Unknown Source)
         at java.security.AccessController.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkExec(Unknown Source)
         at java.lang.ProcessBuilder.start(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at applet.RunApplet_jButton_actionAdapter.actionPerformed(RunApplet.java:73)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)Is there anybody who have an idea what can be wrong?
    regards
    thallish

    ok i solved i myself. i assigned a different and thereby correct keystore and now it works like it should
    regards
    thallish

  • Weirdness and ignorance

    This is a semi-continuation of another thread in the 'new to java' forum. I'm learning swing and I'm looking for help as I go. Right now I've got a 'lil mini-gui that will let you point to any folder and it will list all of the files subfolders, sufiles, sub-sub files, etc. in that folder. The problem now is that if I resize the window or it loses focus, the list gets wiped. Also the scrollpane isn't scrolling.
    QQ
    Any suggestions?
    package formshow;
    //import java.applet.*;
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
    import java.awt.event.*;
    public class Sync extends JApplet
              JButton bttn1;
              JComboBox Cbox_drives, Cbox_folders;
              JPanel panel;
              JFrame aframe;
              JScrollPane FilePane;
              DefaultListModel Filelistmodel;
              JList Filelist;
              class OnlyPRE implements FilenameFilter
                Vector PRE;
                public OnlyPRE(Vector PRE)
                {this.PRE = PRE;}
                public boolean accept(File dir, String name)
                     boolean accept = false;
                     for (int i=0; i<PRE.size(); i++)
                          if (name.startsWith((String)PRE.get(i)))
                               accept = true;
                     return accept;
              public void init()
                   //this applet
                   this.setSize(800,150);
                   //jpanel
                   panel = new JPanel(null);
                   //Button init stuff
                   bttn1 = new JButton("HAI ROLDR!!!");
                   bttn1.setSize(150,50);
                   bttn1.setLocation(0,100);
                   bttn1.addActionListener( new ActionListener()
                                                  public void actionPerformed(ActionEvent evt)
                                                 {PopList();}
                   panel.add(bttn1);
                   //Cbox_drives init stuff
                   int offset = 'a';                    
                   Cbox_drives = new JComboBox();
                   for (int i=0; i<26; i++)
                        Cbox_drives.addItem((char)(offset+i)+":\\");               
                   Cbox_drives.setSize(150,50);
                   Cbox_drives.setLocation(0,0);
                   Cbox_drives.addActionListener( new ActionListener()
                                                 public void actionPerformed(ActionEvent evt)
                                                {getPatFolders();}
                   panel.add(Cbox_drives);
                   //Cbox_folders init stuff
                   Cbox_folders = new JComboBox();
                   Cbox_folders.setLocation(0,50);
                   Cbox_folders.setSize(150,50);
                   Cbox_folders.addItem("Pick the drive letter you have mapped to 1416_a");
                   panel.add(Cbox_folders);
                   //Filelist init stuff
                   Filelist = new JList();
                   Filelist.setVisibleRowCount(5);
                   //FilePane init stuff
                   FilePane = new JScrollPane(Filelist);
                   FilePane.setLocation(150,0);
                   FilePane.setSize(650,150);
                   panel.add(FilePane);
                   getContentPane().add(panel);                              
              private int getPatFolders()
                   String drive = (String)Cbox_drives.getSelectedItem();
                   Vector prelist = new Vector();
                   prelist.addElement("PAT");
                   prelist.addElement("REL");
                   prelist.addElement("EME");
                   FilenameFilter onlyget = new OnlyPRE(prelist);
                   Cbox_folders.removeAllItems();
                   File rootFolder = new File(drive);
                   String files[] = rootFolder.list(onlyget);
                   for (int i=0; i<files.length; i++)
                        Cbox_folders.addItem((String)files);               
                   return (1);
              private int PopList()
                   File StartFolder = new File(((String)Cbox_drives.getSelectedItem())+
                                                      ((String)Cbox_folders.getSelectedItem()));
                   Filelistmodel = getFiles(StartFolder);
                   Filelist.removeAll();
                   Filelist = new JList(Filelistmodel);
                   FilePane = new JScrollPane(Filelist);
                   FilePane.setLocation(150,0);
                   FilePane.setSize(650,150);
                   panel.add(FilePane);     
                   getContentPane().invalidate();
                   getContentPane().validate();
                   return(1);
              private DefaultListModel getFiles(File ThisPath)
                   DefaultListModel ThisLevel = new DefaultListModel();               
                   String FileList[] = ThisPath.list();
                   for (int i=0; i<FileList.length; i++)
                             File afile = new File(ThisPath.getAbsolutePath()+"\\"+FileList[i]);
                             if (afile.isFile())
                                  ThisLevel.addElement(afile.getAbsolutePath());
                             else
                                  append(ThisLevel,getFiles(afile));                              
                   return ThisLevel;
              private DefaultListModel append(DefaultListModel Left, DefaultListModel Right)
                   for (int i=0; i<Right.getSize();i++)
                        Left.addElement(Right.get(i));
                   return Left;

    Can I embed a JFrame in a web page?Proves you really are a beginner. JFrame is used when developing applications for the Desktop, such as your standard ms word, excel, etc applications. Java is not only restricted to running from a browser and a greater percentage of all current java software created using swing are desktop apps.
    If you really are interested in swing, then you should be looking at creating a Desktop application rather than an Applet (unless you required to do so at the moment). Besides, your current code looks more like an attempt at making a desktop application than an applet, IMHO.
    ICE

  • My applet doesn't run in a browser.

    I written the following code:
    import javax.swing.*;
    public class Logo extends JApplet
         JButton button ;
         Icon icon;
         JPanel panel;
         public void init()
              icon = new ImageIcon("smilogo.gif");
              button = new JButton(icon);
              panel = new JPanel();
              panel.add(button);
              getContentPane().add(panel);
    I also have my html file with the code :
    <HTML>
    <HEAD></HEAD>
    <BODY >
    <CENTER>
    <APPLET code = "Logo.class" width = "100" height = "100"></APPLET>
    </CENTER>
    </BODY>
    </HTML>
    when I run the html file with the appletviewer the image gets loaded like I
    expect it to. But when I run the file in a browser (IE version 5)after converting
    it using the HTMLConverter, the image doesn't load.
    What could be the problem. The code was compiled with J2sdk1.4.0.

    It's a JApplet, it needs the java plug in....
    If you've already got the plugin installed you'll just need to change the tag you're using to load the applet... it'll either be an embed tag or an object tag.. (embed for Netscape, Object for IE)...

  • ShowStatus() not working

    hi, this is the coding im working on , it will compile nicely on blueJ but somehow showStatus wont work. Status bar is empty.
    Thanks for the time :)
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class makmal5c extends JApplet {
        JButton poligaris = new JButton("Poligaris");
        JButton poligon = new JButton("Poligon");
        poligaris_b pol1 = new poligaris_b();
        poligon_b pol2 = new poligon_b();
        JPanel inface = new JPanel();
        Container pane = getContentPane();
        Panel panel = new Panel();
        public void init() {
            poligaris.addActionListener(pol1);
            poligon.addActionListener(pol2);
            inface.setBackground(Color.blue);
            inface.add(poligaris);
            inface.add(poligon);
            pane.add(inface,"North");
            pane.add(panel);
        public class poligaris_b implements ActionListener{
            public void actionPerformed(ActionEvent e){
                panel.poligaris();
        public class poligon_b implements ActionListener{
            public void actionPerformed(ActionEvent e){
                panel.poligon();    
    class Panel extends JApplet implements MouseListener, MouseMotionListener {
        static final int SAIZ = 2;
        ArrayList segi4;
        Rectangle2D rect;
        double list_x[] = new double[200];
        double list_y[] = new double[200];
        int z = 0;
        int ind = 0;
        public Panel() {
            segi4 = new ArrayList();
            rect = null;
            addMouseListener(this);
            addMouseMotionListener(this);
        public void paint(Graphics g) {
            super.paint(g);
            Graphics2D g2 = (Graphics2D) g;
            for(int i=0; i<segi4.size(); i++)
                g2.draw( (Rectangle2D) segi4.get(i));
            if ( ind == 1 ){
                    GeneralPath n1 = new GeneralPath();
                    n1.moveTo(list_x[0],list_y[0]);
                    for(int u=0; u < list_x.length; u++){
                         if ( list_x[u] != 0 ){
                             n1.lineTo(list_x[u],list_y[u]);
                    g2.draw(n1);                  
                    ind = 0 ;
            if ( ind == 2 ){
                    GeneralPath n1 = new GeneralPath();
                    n1.moveTo(list_x[0],list_y[0]);
                    for(int u=0; u < list_x.length; u++){
                         if ( list_x[u] != 0 ){
                             n1.lineTo(list_x[u],list_y[u]);
                    n1.closePath();
                    g2.setColor(Color.blue);
                    g2.fill(n1);
                    g2.draw(n1);                  
                    ind = 0 ;
        public Rectangle2D find(Point2D p) {
            for (int i=0; i < segi4.size(); i++) {
                Rectangle2D r = (Rectangle2D) segi4.get(i);
                if (r.contains(p))
                    return r;
            return null;
        public void add(Point2D p) {
            double x = p.getX();
            double y = p.getY();
            rect = new Rectangle2D.Double(x-SAIZ/2, y-SAIZ/2, SAIZ, SAIZ);
            segi4.add(rect);
            repaint();
        public void remove(Rectangle2D r) {
            if (r == null)
                return;
            if (r == rect)
                rect = null;
            segi4.remove(r);
            this.repaint();
        public void getLine(Point2D p) {       
            double x = p.getX();
            double y = p.getY();
            list_x[z] = x-SAIZ/2;
            list_y[z] = y-SAIZ/2;
            z++;     
        public void poligaris() {
            ind = 1;
            repaint();   
        public void poligon() {
            ind = 2;
            repaint();
            public void mousePressed(MouseEvent e) {
                rect = find(e.getPoint());
                if (rect == null){
                    add(e.getPoint());
                    getLine(e.getPoint());
            public void mouseClicked(MouseEvent e) {
                rect = find(e.getPoint());
                if (rect != null && e.getClickCount() >= 2)
                    remove(rect);
            public void mouseEntered(MouseEvent e) {
            public void mouseExited(MouseEvent e) {
            public void mouseReleased(MouseEvent e) {
            public void mouseMoved(MouseEvent e) {
                showStatus("Mouse is currently at "+e.getX()+" , "+e.getY()+e.getPoint());
                if (find(e.getPoint()) == null)
                    setCursor(Cursor.getDefaultCursor());
                else
                    setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
            public void mouseDragged(MouseEvent e) {
                if (rect != null) {
                    int x = e.getX();
                    int y = e.getY();
                    rect.setFrame(x-SAIZ/2, y-SAIZ/2, SAIZ, SAIZ);
                    repaint();
    }  

    first off check your browser to see if your status bar is enabled.

  • I have a problem with my calculator :(

    hi all,
    i need some help with my calculator..after i wrote the code i discovered my mistake so i made some changes on the code..the problem is that it's still applying the old code !!
    ( i didn't forgot to compile it, & i closed all the browsers b4 trying it )
    i will appreciate ANY suggestion
    P.S : my mistake was with the operations buttons ( add, sub, multip, division ) & the equal button
    if it may help, this is the code ( the new one, then the old one )
    the new code:
    import java.awt.* ; // Container, FlowLayout
    import java.awt.event.* ; // ActionEvent, ActionListener
    import javax.swing.* ; // JApplet , JButton , JLabal, JTextField
    public class Calculator2 extends JApplet implements ActionListener {
    // graphical user interface components
    JTextField field ;
    JButton zero, one, two, three, four, five, six, seven, eight, nine, fraction, clear,
    add, sub, multip , division, equal ,sin , cos, tan ,log ,sqrt ,exp ;
    // variables
    String string = " " ; // to store what is in the text field
    String operation ; // to store the operation selected
    double operate ; // to store the result of the operation selected
    double operand1 , operand2 ; // the operands of the operation
    // set up GUI components
    public void init ()
    Container container = getContentPane ();
    container.setLayout ( new FlowLayout () );
    // create a text field
    field = new JTextField ( 17 );
    container.add ( field ) ;
    // create buttons
    clear = new JButton ( "C" ) ;
    clear.addActionListener ( this ) ;
    container.add ( clear );
    zero = new JButton ( "0" ) ;
    zero.addActionListener ( this ) ;
    container.add ( zero );
    one = new JButton ( "1" ) ;
    one.addActionListener ( this ) ;
    container.add ( one );
    two = new JButton ( "2" ) ;
    two.addActionListener ( this ) ;
    container.add ( two );
    three = new JButton ( "3" ) ;
    three.addActionListener ( this ) ;
    container.add ( three );
    four = new JButton ( "4" ) ;
    four.addActionListener ( this ) ;
    container.add ( four );
    five = new JButton ( "5" ) ;
    five.addActionListener ( this ) ;
    container.add ( five );
    six = new JButton ( "6" ) ;
    six.addActionListener ( this ) ;
    container.add ( six );
    seven = new JButton ( "7" ) ;
    seven.addActionListener ( this ) ;
    container.add ( seven );
    eight = new JButton ( "8" ) ;
    eight.addActionListener ( this ) ;
    container.add ( eight );
    nine = new JButton ( "9" ) ;
    nine.addActionListener ( this ) ;
    container.add ( nine );
    fraction = new JButton ( "." ) ;
    fraction.addActionListener ( this ) ;
    container.add ( fraction );
    add = new JButton ( "+" ) ;
    add.addActionListener ( this ) ;
    container.add ( add );
    sub = new JButton ( "-" ) ;
    sub.addActionListener ( this ) ;
    container.add ( sub );
    multip = new JButton ( "*" ) ;
    multip.addActionListener ( this ) ;
    container.add ( multip );
    division = new JButton ( "�" ) ;
    division.addActionListener ( this ) ;
    container.add ( division );
    sin = new JButton ( "sin" ) ;
    sin.addActionListener ( this ) ;
    container.add ( sin );
    cos = new JButton ( "cos" ) ;
    cos.addActionListener ( this ) ;
    container.add ( cos );
    tan = new JButton ( "tan" ) ;
    tan.addActionListener ( this ) ;
    container.add ( tan );
    log = new JButton ( "log" ) ;
    log.addActionListener ( this ) ;
    container.add ( log );
    sqrt = new JButton ( "sqrt" ) ;
    sqrt.addActionListener ( this ) ;
    container.add ( sqrt );
    exp = new JButton ( "exp" ) ;
    exp.addActionListener ( this ) ;
    container.add ( exp );
    equal = new JButton ( "=" ) ;
    equal.addActionListener ( this ) ;
    container.add ( equal );
    } // end of method init
    public void actionPerformed ( ActionEvent event )
         // button zero
         if ( event.getSource()== zero )
         string = string + "0" ;
         field.setText ( string ) ;
         // button one
         else if ( event.getSource()== one )
              string = string + "1" ;
              field.setText ( string ) ;
         // button two
         else if ( event.getSource()== two )
              string = string + "2" ;
              field.setText ( string ) ;
         // button three
         else if ( event.getSource()== three )
              string = string + "3" ;
              field.setText ( string ) ;
         // button four
         else if ( event.getSource()== four )
              string = string + "4" ;
              field.setText ( string ) ;
         // button five
         else if ( event.getSource()== five )
              string = string + "5" ;
              field.setText ( string ) ;
         // button six
         else if ( event.getSource()== six )
              string = string + "6" ;
              field.setText ( string ) ;
         // button seven
         else if ( event.getSource()== seven )
              string = string + "7" ;
              field.setText ( string ) ;
         // button eight
         else if ( event.getSource()== eight )
              string = string + "8" ;
              field.setText ( string ) ;
         // button nine
         else if ( event.getSource()== nine )
              string = string + "9" ;
              field.setText ( string ) ;
         // button fraction
         else if ( event.getSource()== fraction )
              string = string + "." ;
              field.setText ( string ) ;
         // button clear
         else if ( event.getSource()== clear )
              clear ();
         // button add
         else if ( event.getSource()== add )
              operand1 = Double.parseDouble ( string );
              operation = "+" ;
              clear ();
         // button sub
         else if ( event.getSource()== sub )
              operand1 = Double.parseDouble ( string );
              operation = "-" ;
              clear ();
         // button multip
         else if ( event.getSource()== multip )
              operand1 = Double.parseDouble ( string );
              operation = "*" ;
              clear ();
         // button division
         else if ( event.getSource()== division )
              operand1 = Double.parseDouble ( string );
              operation = "/" ;
              clear ();
         // button sin
         else if ( event.getSource()== sin )
              operate = Double.parseDouble ( string ) ;
              operate = Math.sin( operate );
              field.setText ( Double.toString ( operate ) ) ;
    // button cos
         else if ( event.getSource()== cos )
              operate = Double.parseDouble ( string ) ;
              operate = Math.cos( operate );
              field.setText ( Double.toString ( operate ) ) ;
         // button tan
         else if ( event.getSource()== tan )
              operate = Double.parseDouble ( string ) ;
              operate = Math.tan( operate );
              field.setText ( Double.toString ( operate ) ) ;
         // button log
         else if ( event.getSource()== log )
              operate = Double.parseDouble ( string ) ;
              operate = Math.log( operate );
              field.setText ( Double.toString ( operate ) ) ;
         // button sqrt
         else if ( event.getSource()== sqrt )
              operate = Double.parseDouble ( string ) ;
              operate = Math.sqrt( operate );
              field.setText ( Double.toString ( operate ) ) ;
         // button exp
         else if ( event.getSource()== exp )
              operate = Double.parseDouble ( string ) ;
              operate = Math.exp( operate );
              field.setText ( Double.toString ( operate ) ) ;
         // button equal
         else // if ( event.getSource()== equal )
              operand2 = Double.parseDouble ( string );
              if ( operation == "+" )
                   operate = operand1 + operand2 ;
              else if ( operation == "-" )
                   operate = operand1 - operand2 ;
              else if ( operation == "*" )
                   operate = operand1 * operand2 ;
              else if ( operation == "/" )
                   operate = operand1 / operand2 ;
              field.setText ( Double.toString ( operate ) ) ;
    } // end of method actionPerformed
    public void clear ()
         string = " ";
         field.setText ( string ) ;
    } // end of method clear
    } // end of class
    the old code which have the problem ( which i make the changes on ) :
         // button clear
         else if ( event.getSource()== clear )
              string = "";
              field.setText ( string ) ;
         // button add
         else if ( event.getSource()== add )
              string = string + "+" ;
              field.setText ( string ) ;
         // button sub
         else if ( event.getSource()== sub )
              string = string + "-" ;
              field.setText ( string ) ;
         // button multip
         else if ( event.getSource()== multip )
              string = string + "*" ;
              field.setText ( string ) ;
         // button division
         else if ( event.getSource()== division )
              string = string + "/" ;
              field.setText ( string ) ;
         // button equal
         else // if ( event.getSource()== equal )
              operate = Double.parseDouble ( string ) ;
              field.setText ( Double.toString ( operate ) ) ;
    thanks a lot :)

    Open Java console and press "x" (Clear cache)
    Disable caching in java paremeters.

  • Class not found. Or: THERE'S NO SUCH THING AS APPLETS

    Okay, the problem I�m having seems to be somewhat widespread judging from the forum achieves, but I wasn�t able to find any answers that worked for me. So forgive me if I�m treading old ground, but asking explicitly is my one last attempt to learn what�s going on.
    The problem is the �load: class <someclass.class> not found� gray screen whenever I try to view an applet. Now, looking around online, there are a few applets that I�ve been able to access, and many I haven�t; I�m not certain what causes some to work fine and others to gray screen, but there doesn�t seem to be a pattern to it other than the fact that if I can or can�t view one applet at a site, the same is generally true for all the other applets there as well.
    Now, as for local applets on my computer, I can�t view any of them. Not examples that come with the SDK, none that I�ve compiled myself, and none that I�ve downloaded. Needless to say, in my exasperation I�ve run through every possible permutation of html code for class and classpath and so on trying to modify code into working, but to no avail.
    Now, in the appletviewer, and in an IDE called RealJ, I can run applets just fine. It�s just those embedded in web pages that seem to give me trouble.
    I�ve uninstalled and reinstalled j2sdk 1.4.1. I�m running IE 6.0. Windows 98SE. In my Internet options, I have under Java (Sun) the �Use Java 2 v1.4.1 for applet� box checked, and under Java VM the �Java console enabled� and �JIT Compiler� boxes checked, though I have also gone through every permutation possible here, again, to no avail.
    Any idea what I can change so that I can start running applets with ease?
    Thanks in advance, I desperately appreciate whatever suggestions you can give.
    Travis

    gray screen whenever I try to view an applet.
    Now, looking around online, there are a few applets
    that I�ve been able to access, and many I haven�t; Basically it is partly your browser and partly the version of the jdk /sdk that you are viewing. Generally, IE does not support swing ie JApplet, JButton, JTextArea etc... which is a shame cos it has some pretty neat features - I particularly like the flexibility with textfields and textAreas - and my favourite: imageIcon, allows you to have the sexiest looking buttons in the known universe. For reasons like this, people who like to write Applets like to use swing ... and people who like Sun don't like windoze and IE and the like (and they definitely hate each other). So, if you change your browser to Netscape or Opera - you will see swinging applets galore.
    Shame really on a practical level, as the last survey I saw gave IE a 85 - 90 % share of the browser market. A bigger shame, when it seems to be deliberate that m-$oft do not include the latest JVM in their browser, yet they have the latest Flash plug-in. Both are in fact a good idea.
    Any idea what I can change so that I can start running
    applets with ease? Don't use swing and get a copy of something like jdk1.1.5 or even 1.1.2, if it compiles OK with this then it should be OK, keep it simple - as applets download on the client-side and can be unreliable and erratic so try and avoid images. Generally though Applets are a little bit out of vogue at the moment.

  • Adding a JList to a JScrollPane

    Searching through the archives, this appears to be a pretty frequent question, but so far, none of the answers have worked for me. Behold, what I have:
    Filelist = new JList(Filelistmodel);
    FilePane = new JScrollPane();
    FilePane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    FilePane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    FilePane.setMaximumSize(new Dimension(650,150));
    FilePane.setMinimumSize(new Dimension(650,150));
    FilePane.setPreferredSize(new Dimension(650,150));
    FilePane.setBounds(150, 0, 650, 150);
    FilePane.setViewportView(Filelist);
    panel.add(FilePane);     Message was edited by:
    break_the_chain

    Ok, here's the context. It's not exactly simple, but it should compile and the rest of the code is more or less outside of the problem.
    package formshow;
    //import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.io.*;
    import java.util.*;
    public class Sync extends JApplet
         JButton bttn1;
         JComboBox Cbox_drives, Cbox_folders;
         JPanel panel;
         JFrame aframe;
         JScrollPane FilePane;
         DefaultListModel Filelistmodel;
         JList Filelist;
         class OnlyPRE implements FilenameFilter
           Vector PRE;
           public OnlyPRE(Vector PRE)
           {this.PRE = PRE;}
           public boolean accept(File dir, String name)
                              boolean accept = false;
              for (int i=0; i<PRE.size(); i++)
              if (name.startsWith((String)PRE.get(i)))
              accept = true;
           return accept;
         public void init()
              //applet listener
              this.addFocusListener( new FocusListener()
                public void focusGained(FocusEvent evt)
                                   getContentPane().invalidate();
                   getContentPane().validate();
              public void focusLost(FocusEvent evt)
                 getContentPane().invalidate();
                 getContentPane().validate();
                             //this applet
              this.setSize(800,150);
              //jpanel
              panel = new JPanel(null);
              //Button init stuff
              bttn1 = new JButton("Get Files");
              bttn1.setSize(150,50);
              bttn1.setLocation(0,100);
              bttn1.addActionListener( new ActionListener()
                 public void actionPerformed(ActionEvent evt)
                 {PopList();}
              panel.add(bttn1);
              //Cbox_drives init stuff
              int offset = 'a';                    
              Cbox_drives = new JComboBox();
              for (int i=0; i<26; i++)
              Cbox_drives.addItem((char)(offset+i)+":\\");               
              Cbox_drives.setSize(150,50);
              Cbox_drives.setLocation(0,0);
                              Cbox_drives.addActionListener( new ActionListener()
                public void actionPerformed(ActionEvent evt)
                   try                                  {
                    getPatFolders();
                  catch (Exception e)Cbox_drives.setBackground(Color.RED);}
              panel.add(Cbox_drives);
              //Cbox_folders init stuff
              Cbox_folders = new JComboBox();
              Cbox_folders.setLocation(0,50);
              Cbox_folders.setSize(150,50);
              Cbox_folders.addItem("Pick the drive letter you have mapped to 1416_a");
              panel.add(Cbox_folders);
              //Filelist init stuff
              Filelist = new JList();
              Filelist.setVisibleRowCount(5);
              //FilePane init stuff
              FilePane = new JScrollPane(Filelist);
              FilePane.setLocation(150,0);
              FilePane.setSize(650,150);
              panel.add(FilePane);
              getContentPane().add(panel);                              
              private int getPatFolders () throws Exception
                   String drive = (String) Cbox_drives.getSelectedItem();
                   String files[];
                   Vector prelist = new Vector();
                   prelist.addElement("PAT");
                   prelist.addElement("REL");
                   prelist.addElement("EME");
                   FilenameFilter onlyget = new OnlyPRE(prelist);
                   Cbox_folders.removeAllItems();
                   try{
                   File rootFolder = new File(drive);
                   files = rootFolder.list();
                   catch (Exception E)
                   files = new String[]{"Error Here"};
                   for (int i=0; i<files.length; i++)
                        Cbox_folders.addItem((String)files);               
                   return (1);
              private int PopList()
                   File StartFolder = new File(((String)Cbox_drives.getSelectedItem())+
    (String)Cbox_folders.getSelectedItem()));
                   PopList(getFiles(StartFolder));
                   Filelist.removeAll();
                   Filelist = new JList(Filelistmodel);
                   FilePane = new JScrollPane();
                   FilePane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                   FilePane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                   FilePane.setMaximumSize(new Dimension(650,150));
                   FilePane.setMinimumSize(new Dimension(650,150));
                   FilePane.setPreferredSize(new Dimension(650,150));
                   FilePane.setBounds(150, 0, 650, 150);
                   FilePane.setViewportView(Filelist);
                   panel.add(FilePane);     
                   getContentPane().invalidate();
                   getContentPane().validate();
                   return(1);
              private int PopList(Vector transmute)
                   Filelistmodel = new DefaultListModel();
                   for (int i=0; i<transmute.size(); i++)
                        Filelistmodel.addElement(transmute.elementAt(i));
                   return(1);
              private Vector getFiles(File ThisPath)
                   Vector ThisLevel = new Vector();               
                   String FileList[] = ThisPath.list();
                   for (int i=0; i<FileList.length; i++)
                             File afile = new File(ThisPath.getAbsolutePath()+"\\"+FileList[i]);
                             if (afile.isFile())
                                  ThisLevel.addElement(afile.getAbsolutePath());
                             else
                                  append(ThisLevel,getFiles(afile));                              
                   return ThisLevel;
              private Vector append(Vector Left, Vector Right)
                   for (int i=0; i<Right.size();i++)
                        Left.addElement(Right.get(i));
                   return Left;
    Ok, basically this is for windows users. Pick a drive letter, then pick a folder from the next combo box.
    Hit the button and a list of all of the files in the folders and subfolders shows up in the JList on the right.
    DO NOT try this when the second list box is pointing to something like windows or program files.
    I'd recommend creating your own folder that goes maybe one or two levels deep with just a bunch of empty text files.
    I will <3 anyone that can help me with this forever and bestow upon them rediculous numbers of dukestars.
    Message was edited by:
    break_the_chain

  • Signed Applet can't read an image file??

    Hi my dear java folks,
    I've written a simple applet and self-signed it in order to have access
    to local machine's files.
    The applet as you see needs to read an image file (arrow.gif).
    The applet is:
    import.....
    public class MyApplet extends JApplet{
    JButton button1=new JButton("Save");
    JButton button2=new JButton(new ImageIcon("arrow.gif"));
    public void init(){
    button1.setBounds(10,70,80,20);
    button2.setBounds(10,100,80,20);
    getContentPane().setLayout(null);
    getContentPane().add(button1);
    getContentPane().add(button2);
    The java.policy file is:
    keystore ".//myworkingstore.store";
    grant codeBase "http://fin2000/htdocs/MyApplet.class" {
    permission java.io.FilePermission "<<ALL FILES>>","read";
    permission java.io.AllPermission;
    grant codeBase "." signedBy "MyName" {
    permission java.io.FilePermission "${user.home}/*.*","read,write";
    permission java.io.FilePermission "<<ALL FILES>>","read";
    permission java.io.AllPermission;
    The java.security file is on the server
    (on my server I have Oracle8.1/Apache installed):
    policy.url.1=file:d:/oracle/ora81/apache/apache/htdocs/java.policy;
    My problem is when I run my applet through a html file
    "http://myServerName/test.html" in my browser, the applet
    runs correctly except it's button2 (the iconized button), the
    button comes without it's ImageIcon on it.
    I receive no errors, no messages and no signs of error
    I am completely confused!
    Need Urgent Help
    Thank you , Jamanir

    Hi,
    this has nothing to do with a security problem.
    Change you code as follow:
      JButton button2 = new JButton(new ImageIcon(getClass().getResource("arrow.gif")) ;Pack arrow.gif in the same directory/package as MyApplet.class in the jar file and It should solve your problem...
    The problem is that when you write new ImageIcon("arrow.gif"), it works locally as a standalone application, because "arrow.gif" is mapped to the current directory where you application is started from. This has no meaning when you works online with an applet. That's the reason why your graphic was not found.
    getClass().getResource("arrow.gif") returns an URL pointing to a file "arrow.gif" located at the same location as the class. This always works either locally or online, other packed in a Jar file, or unpacked.
    Yannick

Maybe you are looking for