Code of applets and applications

When I'm writing the beginning of the code for a application I would write:
public class whatever
public static void main (String [] args)
does this differ when writing the beginning for an applet? can i just write it like above and add the applet tags in html?
thanks for reading.
-keyf

public class whatever extends jappletis fine, but an applet does not have a main() method.
It has a
public void init() {}
that works like a constructor (run the first time the page containing the applet is loaded)
and a method
public void start() {}
that would be similar to the main().
HTH,
Dewang

Similar Messages

  • Querry regarding applets and application

    hello sir,
    i am in great trouble! please help me! see i want to know that is it possible that i can create an applet from application! in the sense i am studying in a computer institue and we are told to make a project on notepad! we are told to make a project through java! i have prepared it! but the question in my mind is that i have also created an applet which shows a clock with date and time! but the notepad i have created is an application and in that i have added menu bars in which there is a sub menu called "date/ time". i want that when ever some one clicks on date/ time tab then it should show the clock! i am confused! i cant get any thing as solution please help me! i am in great trouble! i want to submit my notepad by this thursday 2nd aug! please help me! i cant get anyone to help!
    i am also mailing my whole code! please rectify if any present!
    here is the code: for notepad
    import java.awt.*;
    import java.applet.*;
    import java.awt.font.*;
    import javax.swing.event.*;
    import javax.swing.colorchooser.*;
    import java.awt.print.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    import javax.swing.undo.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    public class Notepad implements KeyListener,ActionListener, ItemListener, Runnable
         static JFrame frame;
         static JTextArea txtArea;
         JScrollPane scrollPane;
         JMenuBar menuBar;
         JMenu fileMenu, editMenu, toolsMenu, aboutMenu;
         JMenuItem mNew, popNew, mDelete, mOpen, mSave, mSaveAs, mPrint, mClose, mExit, mCut, popCut, mCopy, popCopy, mPaste, popPaste,popSelectAll, mSelectAll, mDateTime, mAboutNotepad;
         JPanel panel;
         JPopupMenu popMenu;
         JCheckBoxMenuItem chkWordwrap;
         JComboBox cmbFontSize, cmbFont ;
         JToolBar toolbar;
         JButton btnSave, btnNew, btnOpen, btnCut, btnCopy, btnPaste;
         static boolean textChanged = false;
         static String title = " Notepad - by Vicky Saini";
         private static Vector fonts;
         static GraphicsEnvironment env;
         String fontChoice = "Font Choice";
         Integer FontSize ;
         Hashtable actions;
         DefaultStyledDocument document;
         Thread threadTime;
    // static AudioClip clockbeep;     
    public void help()
              JFrame frame= new JFrame();
              JOptionPane op = new JOptionPane(" Vicky Saini's NotePad 1.0, "
                                                                + "\n" + "Created by V I C K Y S A I N I \n"
                                                                + "Batch No: 1103 - SMA007 \n"
                                                                + "Developed under Guidence of Ashish Thakkar \n" + "\n" + "For support information Contact:\n"
                                                                +"[email protected] \n" + "\n"
    + " Copyright 2001-2005 SainiSoft\n"
                                                                     + "Download Version" + " \n"
                                                                     + "All Right Reserved \n" ,
    JOptionPane.INFORMATION_MESSAGE,JOptionPane.CLOSED_OPTION,new ImageIcon("vickyN.jpg"));
                   JDialog dialog = op.createDialog(frame,"About This Notepad");
                   dialog.setSize(450,350);
                   dialog.setResizable(false);
                   dialog.show();          
         public static void main(String args[])
              //clockbeep=getAudioClip(getDocumentBase(),"clockbell.au");     
              //clockbeep.play();
              JOptionPane.showMessageDialog(new JFrame(),"Wel-Come to Vicky's Notepad");
              Notepad notepad = new Notepad();
              notepad.createNotepad();
              txtArea.setRequestFocusEnabled(true);
              txtArea.requestFocus();
              //clockbeep.stop();
         public void createNotepad()
              frame = new JFrame(title);
              frame.setSize(600, 550);
              document = new DefaultStyledDocument();
              txtArea = new JTextArea(document);
              createActionTable(txtArea);
              txtArea.addKeyListener(this);
              scrollPane = new JScrollPane(txtArea);
              menuBar = new JMenuBar();
              frame.setJMenuBar(menuBar);
              createMenu(menuBar);
              panel = new JPanel();
              panel.setLayout(new BorderLayout());
              toolbar = new JToolBar();
              addButton(toolbar);
              panel.add(toolbar, BorderLayout.NORTH);
              frame.addWindowListener(new AppCloser());
              popMenu = new JPopupMenu();
              popMenu.setVisible(true);
              popMenu.setInvoker(scrollPane);
              addpopMenuItem(popMenu);
              MouseListener popupListener = new PopupListener();
              txtArea.addMouseListener(popupListener);
              scrollPane.addMouseListener(popupListener);
              threadTime = new Thread();
              threadTime.start();
              txtArea.setCursor(Cursor.getDefaultCursor());
              try
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch(Exception exc)
                   System.err.println("Error loading L&F: " + exc);
              panel.add(scrollPane, BorderLayout.CENTER);          
              frame.getContentPane().add(panel);
              frame.setVisible(true);     
         public String currentTime()
              Date currentDate = new Date();
              GregorianCalendar gc = new GregorianCalendar();
              gc.setTime(currentDate);
              String year = " " + gc.get(Calendar.YEAR);
              String month = year + "/" + gc.get(Calendar.MONTH);
              String day = month + "/" + gc.get(Calendar.DATE);
              String hour = day + " " + gc.get(Calendar.HOUR);
              String min = hour + ":" + gc.get(Calendar.MINUTE);
              String sec = min + ":" + gc.get(Calendar.SECOND);
              String milli = sec + "." + gc.get(Calendar.MILLISECOND);
              return milli;
         public void run()
              try
                   for(;;)
                        threadTime.sleep(1);
                        currentTime();
              catch(Exception e)
         public void addpopMenuItem(JPopupMenu popMenu)
              popNew = new JMenuItem(" New ");
              popMenu.add(popNew);
              popNew.addActionListener(this);
              popMenu.addSeparator();
              popCut = new JMenuItem(" Cut ");
              popMenu.add(popCut);
              popCut.addActionListener(this);
              popCopy = new JMenuItem(" Copy ");
              popMenu.add(popCopy);
              popCopy.addActionListener(this);
              popPaste = new JMenuItem(" Paste ");
              popMenu.add(popPaste);
              popPaste.addActionListener(this);
              popMenu.addSeparator();
              popSelectAll = new JMenuItem(" Select All ");
              popMenu.add(popSelectAll);
              popSelectAll.addActionListener(this);     
         public void createMenu(JMenuBar menuBar)
              fileMenu = new JMenu(" File ");
              fileMenu.setMnemonic('F');
              menuBar.add(fileMenu);
              editMenu = new JMenu(" Edit ");
              editMenu.setMnemonic('E');
              menuBar.add(editMenu);
              toolsMenu = new JMenu(" Tools ");
              toolsMenu.setMnemonic('T');
              menuBar.add(toolsMenu);
              aboutMenu = new JMenu(" About ");
              aboutMenu.setMnemonic('A');
              menuBar.add(aboutMenu);
              mNew = new JMenuItem(" New ");
              fileMenu.add(mNew);
              mNew.addActionListener(this);
              mNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, KeyEvent.CTRL_MASK));
              mOpen = new JMenuItem(" Open ");
              fileMenu.add(mOpen);
              mOpen.addActionListener(this);
              mOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, KeyEvent.CTRL_MASK));
              mClose = new JMenuItem(" Close ");
              fileMenu.add(mClose);
              mClose.addActionListener(this);
              fileMenu.addSeparator();
              mSave = new JMenuItem(" Save ");
              fileMenu.add(mSave);
              mSave.addActionListener(this);
              mSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK));
              mSaveAs = new JMenuItem(" SaveAs ");
              fileMenu.add(mSaveAs);
              mSaveAs.addActionListener(this);
              fileMenu.addSeparator();
              mPrint = new JMenuItem(" Print.... ");
              fileMenu.add(mPrint);
              mPrint.addActionListener(this);
              mPrint.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, KeyEvent.CTRL_MASK));
              mExit = new JMenuItem(" Exit ");
              fileMenu.add(mExit);
              mExit.addActionListener(this);
              mExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.ALT_MASK));
              editMenu.addSeparator();
              mCut = new JMenuItem(" Cut ");
              editMenu.add(mCut);
              mCut.addActionListener(this);
              mCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.CTRL_MASK));
              mCopy = new JMenuItem(" Copy ");
              editMenu.add(mCopy);
              mCopy.addActionListener(this);
              mCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_MASK));
              mPaste = new JMenuItem(" Paste ");
              editMenu.add(mPaste);
              mPaste.addActionListener(this);
              mPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.CTRL_MASK));          
              mDelete = new JMenuItem(" Delete ");
              mDelete.addActionListener(this);
              editMenu.add(mDelete);
              editMenu.addSeparator();
              mSelectAll = new JMenuItem(" Select All ");
              editMenu.add(mSelectAll);
              mSelectAll.addActionListener(this);
              mSelectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_MASK));          
              toolsMenu.addSeparator();
              chkWordwrap = new JCheckBoxMenuItem(" WordWrap ");
              toolsMenu.add(chkWordwrap);
              chkWordwrap.addItemListener(this);
              toolsMenu.addSeparator();          
              mDateTime = new JMenuItem(" Date/Time ");
              toolsMenu.add(mDateTime);
              mDateTime.addActionListener(this);
              mDateTime.setAccelerator(KeyStroke.getKeyStroke("F5"));
              mAboutNotepad = new JMenuItem(" About Notepad ");
              aboutMenu.add(mAboutNotepad);
              mAboutNotepad.addActionListener(this);
         void addButton(JToolBar toolbar)
              btnOpen = new JButton(new ImageIcon("open.gif"));          
              btnOpen.setToolTipText("Open document");
              btnOpen.addActionListener(this);
              toolbar.add(btnOpen);
              btnOpen.setRequestFocusEnabled(false);
              btnOpen.transferFocus();
              btnNew = new JButton(new ImageIcon("new.gif"));     
              btnNew.setToolTipText("New Document ");
              btnNew.addActionListener(this);
              toolbar.add(btnNew);
              btnNew.setRequestFocusEnabled(false);
              btnNew.transferFocus();
              btnSave = new JButton(new ImageIcon("save.gif"));          
              btnSave.setToolTipText("Save document ");
              btnSave.addActionListener(this);
              toolbar.add(btnSave);
              btnSave.setRequestFocusEnabled(false);
              btnSave.transferFocus();
              toolbar.addSeparator();
              btnCut = new JButton(new ImageIcon("cut.gif"));          
              btnCut.setToolTipText("Cut selection");
              btnCut.addActionListener(this);
              toolbar.add(btnCut);
              btnCut.setRequestFocusEnabled(false);
              btnCut.transferFocus();
              btnCopy = new JButton(new ImageIcon("copy.gif"));          
              btnCopy.setToolTipText("Copy selection ");
              btnCopy.addActionListener(this);
              toolbar.add(btnCopy);
              btnCopy.setRequestFocusEnabled(false);
              btnCopy.transferFocus();
              btnPaste = new JButton(new ImageIcon("paste.gif"));
              btnPaste.setToolTipText("Paste selection ");
              toolbar.add(btnPaste);
              btnPaste.addActionListener(this);
              btnPaste.setRequestFocusEnabled(false);
              btnPaste.transferFocus();
              toolbar.addSeparator();
              env = GraphicsEnvironment.getLocalGraphicsEnvironment();
              String lsFonts[] = env.getAvailableFontFamilyNames();
              cmbFont = new JComboBox();
              cmbFont.setBackground(Color.white);
                   for (int i = 0; i < lsFonts.length; i++)
                        cmbFont.addItem(lsFonts);
              cmbFont.addItemListener(this);
              cmbFont.setMaximumRowCount(15);
              toolbar.add(cmbFont);
                   cmbFontSize = new JComboBox();
                   cmbFontSize.addItemListener(this);
                   cmbFontSize.setBackground(Color.white);
                   cmbFontSize.setRequestFocusEnabled(false);
                   for (int i = 8; i < 36; i+=2)
                             cmbFontSize.addItem(String.valueOf(i));
                             cmbFontSize.setSelectedItem("12");
              toolbar.add(cmbFontSize);
              toolbar.addSeparator();
         public void actionPerformed(ActionEvent e)
              if(e.getSource() == mNew || e.getSource() == btnNew || e.getSource() == popNew)
                   if(textChanged)
                        int option = message();
                        if(option == 0)
                             new Save();
                             frame.setTitle(title);
                             txtArea.setText("");
                             txtArea.addKeyListener(this);
                             textChanged = false;
                        else if(option == 1)
                             frame.setTitle(title);
                             txtArea.setText("");
                             txtArea.addKeyListener(this);
                             textChanged = false;
                        else if(option == 2)
                             return;
                   else
                        frame.setTitle(title);
                        txtArea.setText("");
                        txtArea.addKeyListener(this);
                        textChanged = false;
              else if(e.getSource() == mOpen || e.getSource() == btnOpen)
                   if(textChanged)
                        int option = message();
                        if(option == 0)
                             new Save();
                             new Open();
                             txtArea.addKeyListener(this);
                             textChanged = false;
                        else if(option == 1)
                             new Open();
                             txtArea.addKeyListener(this);
                             textChanged = false;
                        else if(option == 2)
                             return;
                   else
                        new Open();
                        txtArea.addKeyListener(this);
                        textChanged = false;
              else if(e.getSource() == mSave || e.getSource() == btnSave)
                   new Save();
                   txtArea.addKeyListener(this);
                   textChanged = false;
              else if(e.getSource() == mSaveAs)
                   new SaveAs();
              else if(e.getSource() == mPrint)
                   PrinterJob printJob = PrinterJob.getPrinterJob();
                   PageFormat type = printJob.pageDialog(printJob.defaultPage());
                   Book bk = new Book();
                   printJob.setPageable(bk);
                   if(printJob.printDialog())
                        try
                             printJob.print();
              catch (Exception ex)
              else if(e.getSource() == mClose)
                   if(textChanged)
                        int option = message();
                        if(option == 0)
                             new Save();
                             frame.setTitle(title);
                             txtArea.setText("");
                             txtArea.addKeyListener(this);
                             textChanged = false;
                        else if(option == 1)
                             frame.setTitle(title);
                             txtArea.setText("");
                             txtArea.addKeyListener(this);
                             textChanged = false;               
                        else if(option == 2)
                             return;
                   else
                        frame.setTitle(title);
                        txtArea.setText("");
                        txtArea.addKeyListener(this);
                        textChanged = false;
              else if(e.getSource() == mExit )
                   if(textChanged)
                        int option = message();
                        if(option == 0)
                             new Save();
                             JOptionPane.showMessageDialog(new JFrame(),"OH!!!please dont leave me!");
                             System.exit(1);
                        else if(option == 1)
                             JOptionPane.showMessageDialog(new JFrame(),"OH!!!please dont leave me!");
                             System.exit(1);
                        else if(option == 2)
                             return;
                   else
                        JOptionPane.showMessageDialog(new JFrame(),"OH!!!please dont leave me!");
                        System.exit(1);
              else if(e.getSource() == mCut || e.getSource() == btnCut || e.getSource() == popCut)
                   txtArea.cut();
                   textChanged = true;
              else if(e.getSource() == mCopy || e.getSource() == btnCopy || e.getSource() == popCopy)
              {     txtArea.copy();}
              else if(e.getSource() == mPaste || e.getSource() == btnPaste || e.getSource() == popPaste)
                   txtArea.paste(); textChanged = true;
              else if(e.getSource() == mDelete)
                   txtArea.replaceSelection(null);     textChanged = true;
              else if(e.getSource() == mDateTime )
                   txtArea.insert(currentTime(), txtArea.getCaretPosition());
                   textChanged = true;
              else if(e.getSource() == mAboutNotepad)
                   help();
              public void itemStateChanged(ItemEvent ie)
              if(ie.getSource() == chkWordwrap)
                   if(chkWordwrap.getState())
                   {     txtArea.setLineWrap(true);     }
                   else
                   {     txtArea.setLineWrap(false);}
              else if(ie.getSource() == cmbFont)
                   fontChoice = (String)cmbFont.getSelectedItem();
              else if(ie.getSource() == cmbFontSize)
                   FontSize = new Integer((String)cmbFontSize.getSelectedItem());
              txtArea.setFont(new Font(fontChoice,Font.PLAIN, FontSize.intValue()));
              public void keyTyped(KeyEvent ke)
              textChanged = true;
              mSave.setEnabled(true);
              btnSave.setEnabled(true);
              mSaveAs.setEnabled(true);
              txtArea.removeKeyListener(this);
         public void keyPressed(KeyEvent ke)
         public void keyReleased(KeyEvent ke)
         public int print(Graphics g, PageFormat pf, int pi) throws PrinterException
              if (pi >= 1)
                   return Printable.NO_SUCH_PAGE;
              return Printable.PAGE_EXISTS;
         final static int message()
              JFrame frameMessage = new JFrame();
              Object message = "The text in the file has changed........Do u want to save the changes?";
              return JOptionPane.showConfirmDialog(frameMessage, message, " Save ", JOptionPane.YES_NO_CANCEL_OPTION);
         protected final class AppCloser extends WindowAdapter
              public void windowClosing(WindowEvent e)
                   if(textChanged)
                        int option = message();
                        if(option == 0)
                             new Save();
                             JOptionPane.showMessageDialog(new JFrame(),"OH!!!please dont leave me!");
                             System.exit(1);
                        else if(option == 1)
                             JOptionPane.showMessageDialog(new JFrame(),"OH!!!please dont leave me!");
                             System.exit(1);
                        else if(option == 2)
                             return;
                   else
                        JOptionPane.showMessageDialog(new JFrame(),"OH!!!please dont leave me!");
                        System.exit(1);
         class PopupListener extends MouseAdapter
              public void mousePressed(MouseEvent e)
              {     showPopup(e);     }
              public void mouseReleased(MouseEvent e)
              {          showPopup(e);     }
              private void showPopup(MouseEvent e)
                   if(e.isPopupTrigger())
                        popMenu.show(e.getComponent(), e.getX(), e.getY());
         private void createActionTable(JTextArea textArea)
              actions = new Hashtable();
              Action[] actionsArray = txtArea.getActions();
              for (int i = 0; i < actionsArray.length; i++)
                   Action a = actionsArray[i];
                   actions.put(a.getValue(Action.NAME), a);
         private Action getActionByName(String name)
    return(Action)(actions.get(name));
         class Open
              public Open()
                   JFrame frame;
                   FileDialog openFile;
                   frame = new JFrame();
                   frame.setLocation(150,150);
                   openFile = new FileDialog(frame, " Open ", 0);
                   openFile.show();
                   String dirName = openFile.getDirectory();
                   String fileName = openFile.getFile();
                   if(dirName == null || fileName == null)
                   {     return;     }
                   else
                        try
                             FileInputStream readFile = new FileInputStream(dirName + fileName);
                             int fileSize = readFile.available();
                             byte inBuff[] = new byte[fileSize];
                             int readByte = readFile.read(inBuff, 0, fileSize);
                             readFile.close();
                             Notepad.txtArea.setText(new String(inBuff));
                             Notepad.frame.setTitle(openFile.getFile());
                        catch(Exception e)
                             Object warn = "Unable to open";
                             JOptionPane.showMessageDialog(new JFrame(), warn, "Warning.....", JOptionPane.WARNING_MESSAGE );
         class Save
              JFrame frameSave;
              FileDialog saveFile;
              String fileName = frame.getTitle();
              public Save()
                   if(title == fileName)
                        frameSave = new JFrame();
                        frameSave.setLocation(150,150);
                        saveFile = new FileDialog(frameSave, " Save ", 1);
                        saveFile.show();
                        fileName = saveFile.getDirectory() + saveFile.getFile();
                        if(fileName.length() == 8)
                             return;
                        else
                             Notepad.frame.setTitle(saveFile.getFile());
                   try
                        FileOutputStream writeFile = new FileOutputStream(fileName);
                        System.out.flush();
                        String input = Notepad.txtArea.getText();
                        for (int n = 0; n < input.length(); n++ )
                             writeFile.write(input.charAt(n) );
                        writeFile.close();
                   catch (Exception e)
                        Object warn = "Unable to save file.........";
                        JOptionPane.showMessageDialog(new JFrame(), warn, "Warning.....", JOptionPane.WARNING_MESSAGE );
              btnSave.setEnabled(false); mSave.setEnabled(false); mSaveAs.setEnabled(false);
         class SaveAs
              public SaveAs()
                   JFrame frameSaveAs = new JFrame();
                   frameSaveAs.setLocation(150,150);
                   FileDialog saveFileAs = new FileDialog(frameSaveAs, " Save As ", 1);
                   saveFileAs.show();
                   String fileName = saveFileAs.getDirectory() + saveFileAs.getFile();
                   if(fileName.length() == 8)
                        return;
                   else
                        Notepad.frame.setTitle(saveFileAs.getFile());
                   try
                        FileOutputStream writeFile = new FileOutputStream(fileName);
                        System.out.flush();
                        String input = Notepad.txtArea.getText();
                        for (int n = 0; n < input.length(); n++ )
                             writeFile.write(input.charAt(n) );
                        writeFile.close();
                   catch (Exception e)
                        Object warn = "Unable to save file.........";
                        JOptionPane.showMessageDialog(new JFrame(), warn, "Warning.....", JOptionPane.WARNING_MESSAGE );
    here is the code for clock
    import java.awt.Graphics;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.text.DateFormat;
    //<Applet code=ClockDemo5 Height=500 Width=600>
    //</Applet>
    //Clock with beep & buttons tried to enter alam settings into the applet itself
    //instead of using dialog but still unsucessful
    public class ClockDemo5 extends Applet implements ActionListener,Runnable {
         private Thread clock=null;
         Graphics g,g1;
         Image i1;
         int flag =0,fl=0;
         int beep=0;
         AudioClip clockbeep;
         String months[]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
         String msg="";
         Button setalarm, stopalarm, help ,ok,cancel;
         Label hrlabel,minlabel;
         TextField hrtxt,mintxt;
         public void init(){
              try{
                   clockbeep=getAudioClip(getDocumentBase(),"clockbell.au");
                   showStatus("Created by : Yogesh Raje");
                   setalarm=new Button("Set Alarm");
                   stopalarm=new Button("Stop Alarm");
                   help=new Button("Help");
                   hrlabel=new Label("Enter Hour : ");
                   hrtxt=new TextField(2);
                   minlabel=new Label("Enter Minutes : ");
                   mintxt=new TextField(2);
                   ok=new Button("Ok");               
                   cancel=new Button("Cancel");
                   add(setalarm);
                   add(stopalarm);
                   add(help);
                   add(hrlabel);
                   add(hrtxt);
                   add(minlabel);
                   add(mintxt);
                   add(ok);
                   add(cancel);
                   hrlabel.setVisible(false);
                   hrtxt.setVisible(false);
                   minlabel.setVisible(false);
                   mintxt.setVisible(false);
                   ok.setVisible(false);
                   cancel.setVisible(false);
                   setalarm.addActionListener(this);
                   stopalarm.addActionListener(this);
                   help.addActionListener(this);
                   ok.addActionListener(this);
                   cancel.addActionListener(this);
              catch(Exception e){
                   showStatus("Unable To Load Audio Clip");
         public void start(){
              showStatus("Created by : Yogesh Raje");
              if(clock==null){
                   clock=new Thread(this,"clock");
                   clock.start();
         public void actionPerformed(ActionEvent ae){
              String str=ae.getActionCommand     ();
              flag=1;
    //          if(str.equals("Set Alarm")){
              if(ae.getSource()==setalarm){
                   hrlabel.setVisible(true);
                   hrtxt.setVisible(true);
                   minlabel.setVisible(true);
                   mintxt.setVisible(true);
                   ok.setVisible(true);
                   cancel.setVisible(true);
              else if(str.equals("Stop Alarm")){
              else if(str.equals("Help"))
                   msg="About help";
              mypaint();
         public void run(){
              showStatus("Created by : Yogesh Raje");
              Thread myclock=Thread.currentThread();
              g=getGraphics();
              i1=createImage(500,600);
              g1=i1.getGraphics();
              g1.setFont(new Font("Dialog",Font.BOLD,48));
              while(myclock==clock){
                   try{
                        beep--;
                        mypaint();
                        Thread.sleep(1000);
                   }catch(InterruptedException e){}
         public void mypaint(){
              Dimension d=getSize();
              Calendar cal=Calendar.getInstance();
              Date time=cal.getTime();
              DateFormat dateformat=DateFormat.getTimeInstance();
              int s=90+cal.get(Calendar.SECOND)*-6;
              int m=90+cal.get(Calendar.MINUTE)*-6;
              int h=90+cal.get(Calendar.HOUR)*-30+(int)(cal.get(Calendar.MINUTE)*-0.5);     
              //if(cal.get(Calendar.SECOND)==0 && cal.get(Calendar.MINUTE)==0){
                   fl=1;
                   beep=cal.get(Calendar.MINUTE);
              if(fl==1)
                   clockbeep.play();
              if(beep==1)
                   fl=0;
              //if(cal.get(Calendar.HOUR)==Integer.parseInt(cd.h1) && cal.get(Calendar.MINUTE)==Integer.parseInt(cd.m1))
                   //clockbeep.loop();
              showStatus("Created by : Yogesh Raje");          
              g1.setColor(Color.white);
              g1.fillRect(0,0,100,150);
              g1.setColor(Color.black);
              g1.drawString(beep+"",25,125);
              //g1.drawString(s1+"",25,35);
              g1.setColor(Color.black);
              g1.fillOval(d.width/2-200,d.height/2-200,400,400);
              g1.setColor(Color.orange);
              g1.fillOval(d.width/2-175,d.height/2-175,350,350);
              g1.setColor(Color.white);
              g1.setFont(new Font("Dialog",Font.BOLD,25));
              g1.fillRect(0,450,600,30);
              g1.setColor(Color.red);
              g1.drawString(dateformat.format(time),100,475);
              g1.drawString(""+months[cal.get(Calendar.MONTH)]+" "+cal.get(Calendar.DATE)+" "+cal.get(Calendar.YEAR),350,475);
              g1.setColor(Color.white);
              g1.setFont(new Font("Dialog",Font.BOLD,50));
              g1.drawString("12",267,125);
              g1.drawString("6",282,412);
              g1.drawString("9",132,270);
              g1.drawString("3",437,270);
              g1.setColor(Color.black);
              g1.fillArc(d.width/2-75,d.height/2-75,150,150,h,2);
              g1.setColor(Color.gray);
              g1.fillArc(d.width/2-100,d.height/2-100,200,200,m,2);
              g1.setColor(Color.green);
              g1.fillArc(d.width/2-125,d.height/2-125,250,250,s,1);
              g1.fillOval(d.width/2-5,d.height/2-5,10,10);
              g1.setFont(new Font("Dialog",Font.BOLD,18));
              g1.setColor(Color.black);
              if(flag==1){
                   flag=0;
                   g1.setColor(Color.white);
                   g1.fillRect(0,0,225,50);
              g1.drawString(msg,5,40);
              g.drawImage(i1,0,0,null);
         public void stop(){
              clock=null;
    please help me! i beg for ur help!!!!!!!!

    application->applet
    get rid of static variables. if nothing else helps put all your static variables in a class that does nothing but holding them and initialize only one such class and add a reference to it in every of your classes.
    whatever you have done in the main method do it now in the constructor of that class.
    from your applet (or if you have none make one that does nothing else) construct an instance of that class
    applet->application
    put all you have drawn directly on the applet ontpo some sort of window.
    change the init method to a constructor.
    make a class with a main method that constructs such an exapplet

  • Applets and application problem plz help me

    Sir
    i design some buttons in cofeecup applet button factory
    it gives me an applet code.i design all drop down menus
    now i want to and it in my application
    by using a JSplitpane How can i add them in my application
    thanks in advance

    Creating a GUI with Swing
    http://java.sun.com/docs/books/tutorial/uiswing/

  • I'm crazy!Applet and JNA Error:Library 'jnidispatch' was not found!

    Hi all,
    sorry to bother you, I really have no idea how to do JNA and Applet. I'm hardly mazy, man.
    Every time it will throw an error to me :
    Exception in thread "thread applet-JNAApplet-1" java.lang.UnsatisfiedLinkError: Library 'jnidispatch' was not found by class loader sun.plugin2.applet.JNLP2ClassLoader@291aff
         at com.sun.jna.Native.getWebStartLibraryPath(Native.java:858)
         at com.sun.jna.NativeLibrary.<clinit>(NativeLibrary.java:576)
         at com.sun.jna.Library$Handler.<init>(Library.java:140)
         at com.sun.jna.Native.loadLibrary(Native.java:372)
         at com.sun.jna.Native.loadLibrary(Native.java:357)
         at JNAApplet.init(JNAApplet.java:15)
         at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)My program is so easy, I just want use Applet to revoke JNA and use the JNA to load a native lib.
    here is the structure of my program:
    Applet code :
    import javax.swing.JApplet;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    import com.sun.jna.Native;
    public class JNAApplet extends JApplet {
         public static Kernel32 kernel32 = null;
         @Override
         public void init() {
              createGUI();
              kernel32 = (Kernel32)Native.loadLibrary("Kernel32", Kernel32.class);
              if (kernel32 == null) {
                   System.out.println("load kernel32 fail!");
              } else {
                   System.out.println("load kernel32 success!");
         private void createGUI() {
              JPanel panelCenter = new JPanel();
              JButton butTest = new JButton("Test");
              panelCenter.add(butTest);
              setContentPane(panelCenter);
    }When I run it on debug mode, it is ok! but when I deploy it , it will throw above error message to me.
    My Applet html:
    <html>
         <head>
              <title>JNA Applet</title>
         </head>
         <body>
         <script src="deployJava.js"></script>
        <script>
            var attributes = { code:'JNAApplet',  width:300, height:300} ;
            var parameters = {jnlp_href: 'JNAApplet.jnlp'} ;
            deployJava.runApplet(attributes, parameters, '1.5');
        </script>
         </body>
    </html>File 'JNAApplet.jnlp':
    <?xml version="1.0" encoding="UTF-8"?>
    <jnlp spec="1.0+" codebase="" href="">
        <information>
            <title>JNA Applet</title>
            <vendor>Steven</vendor>
        </information>
        <resources>
            <j2se version="1.5+"
                  href="http://java.sun.com/products/autodl/j2se" />
            <jar href="JNAApplet.jar" main="true" />
        </resources>
        <applet-desc
             name="JNA Applet"
             main-class="JNAApplet"
             width="300"
             height="300">
         </applet-desc>
         <update check="background"/>
    </jnlp>     I really have no idea. and I can't search any usefull infomation from Google and officer site.
    Can any one help me? Thank you very much!!!!

    Hi AndrewThompson64:
    Did you mean the JNA project? Or are you refering to JNI, or ..something else?Yes, I mean is that I wanna jna.jar to replace JNI to code with Applet. I want Applet can run native library(.dll files).
    That reads like so much nonsense to me.Sorry fo that.
    Was there any 'caused by' part that you trimmed? I expected to see something to do with 'Security' or 'AccessControl'.Sorry, I can't saw any 'cause by' subsentence there. This message is just gain from Applet Console.(Is there any method to gain more message?)
    About 'Security' and 'AccessControl' I just modify my java.policy file to allpermission. Subsequently, I signed all jar files.
    For now I have 3 jar files(all have been signed ):
    --example.jar :  for this little program.(code include applet and application entry)
    --jna.jar
    --win32-x86.jar : include kernel32.dll and jnidispatch.dll for win32 and x86.
    and 2 JNLP files:
    --JNAApplet.jnlp the entry is JNAApplet.class (this jnlp does not work)
    --JNAApp.jnlp     the entry is JNAApp.class  (this jnlp works)
    And for now new error message show like this:
    Exception in thread "thread applet-JNAApplet-1" java.lang.UnsatisfiedLinkError: Library 'Kernel32' was not found by class loader sun.plugin2.applet.JNLP2ClassLoader@4aeb52
         at com.sun.jna.Native.getWebStartLibraryPath(Native.java:858)
         at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:97)
         at com.sun.jna.NativeLibrary.getInstance(NativeLibrary.java:228)
         at com.sun.jna.Library$Handler.<init>(Library.java:140)
         at com.sun.jna.Native.loadLibrary(Native.java:372)
         at com.sun.jna.Native.loadLibrary(Native.java:357)
         at JNAApplet.init(JNAApplet.java:12)
         at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Did you mean invoke?
    Revoke: To annul by withdrawing.
    Invoke: To call on.Yes, you got it. Thank you.
    The JNLP file is invalid. ..I was about to put my 'standard' text here, but I'm sick of saying it. Search the forum for my posts - 50% of them, at least, mention validation and how to go about it.
    Also, the applet-desc requires a documentbase.Thank you, I really think I have some invalid section. But I can't find it, and you said 'Search the forum for my posts - 50% of them...' , I can read the JNLP structure on site of sun and I can to read you post too(I'm doing like this).*I only want to know about how to load "native lib like *.dll" properly*.
    What 'officer site'?I mean jna project site. Sorry for ambiguity.
    Please fix that sticky '!' key. One '!' indicates astonishment, while two or more typically indicates a bozo. Thanks for your advice. Because I tried to find solution do my best lasting two days. I got nothing. I'm sadness.
    here post my new files:
    import javax.swing.JFrame;
    import com.sun.jna.Native;
    public class JNAApp {
         public static Kernel32 kernel32 = null;
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              kernel32 = (Kernel32)Native.loadLibrary("Kernel32", Kernel32.class);
              JFrame frame = new JFrame();
              frame.setSize(500, 500);
              frame.setVisible(true);
    import javax.swing.JApplet;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    import com.sun.jna.Native;
    public class JNAApplet extends JApplet {
         public static Kernel32 kernel32 = null;
         public void init() {
              createGUI();
                   kernel32 = (Kernel32)Native.loadLibrary("Kernel32", Kernel32.class);
         private void createGUI() {
              JPanel panelCenter = new JPanel();
              JButton butTest = new JButton("Test");
              panelCenter.add(butTest);
              setContentPane(panelCenter);
    <?xml version="1.0" encoding="UTF-8"?>
    <jnlp spec="1.0+" codebase="" href="">
        <information>
            <title>JNA Applet</title>
            <vendor>Steven</vendor>
        </information>
        <resources>
            <j2se version="1.5+"
                  href="http://java.sun.com/products/autodl/j2se" />
             <jar href="JNAApplet.jar" main="true"/>
             <jar href="jna.jar"/>
        </resources>
           <resources os="Windows" arch="x86">
             <nativelib href="win32-x86.jar"/>
             <nativelib href="kernel32.jar"/>
           </resources>
        <applet-desc
             documentBase=""
                name = "success"
             main-class="JNAApplet" width = "200" height = "200">
         </applet-desc>
         <update check="background"/>
           <security>
             <all-permissions/>
           </security>
    </jnlp>     
    <?xml version="1.0" encoding="UTF-8"?>
    <jnlp spec="1.0+" codebase="" href="">
        <information>
            <title>JNA Applet</title>
            <vendor>Steven</vendor>
        </information>
        <resources>
            <j2se version="1.5+"
                  href="http://java.sun.com/products/autodl/j2se" />
             <jar href="JNAApplet.jar" main="true"/>
             <jar href="jna.jar"/>
        </resources>
           <resources os="Windows" arch="x86">
             <nativelib href="win32-x86.jar"/>
             <nativelib href="kernel32.jar"/>
           </resources>
        <application-desc
             main-class="JNAApp">
         </application-desc>
         <update check="background"/>
           <security>
             <all-permissions/>
           </security>
    </jnlp>     Thanks & Best Regards,
    Su Heng

  • Socket communication failure between Java applet and C++ application

    I have a java applet that connects to a C++ application via Java's ServerSocket and Socket objects. THe C++ application is using the Winsock 2 API. The applet and application are running on an NT workstation (SP 6) and using IE (5.5) For a very simple C++ test applications the communictions work fine. Once more code gets added to the C++ application the portion of the socket that C++ listens to seems to close. Upon performing a recv call the return value is a zero. Microsoft insists this is a sign the Java side has shut down the socket. The Java applet can still receive messages from the C++ app but C++ cannot receive responses from the Java side. Java throws no exceptions and an explicit check of the socket shows no errors. Again, what puzzles me is that it works for simple C++ applications. Are there any known conflicts between Java and C++ in this regard?
    I have inlcuded the basic java code segments below.
    / run Method.
      * This method is called by the Thread.start() method. This
      * method is required for the implementation of the Runnable interface
      * This method sets up the server side socket communication and
      * contiuously loops looking for requests from a external
      * socket.
      * @author Chris Duke
      public void run(){
         // create socket connections
         boolean success = false;
         try {
             cServerSocket = new ServerSocket(cPortID);
             System.out.println("Waiting for client to connect...");
             cClientSocket = cServerSocket.accept();
             System.out.println("Client connected");
             // Create a stream to read from the client
             cInStream = new BufferedReader(new InputStreamReader(
               cClientSocket.getInputStream()));
             // Create a stream to write to the client       
             cOutStream = new PrintWriter(
               cClientSocket.getOutputStream(), true);
             success = true;
         }catch (IOException e) {
             System.out.println("CommSocket:Run - Socket Exception(1) " + e);
             success = false;
         // if the socket was successfully created, keep the thread running
         while (success){
             try{
                // check socket to see if it is still available for reading
                if (cInStream != null && cInStream.ready()){
                    // check for an incoming message
                    String message = ReceiveMessage();
                    // Send message to listeners
                    Event(message);
                if (cInStream == null){
                    success = false;
                    System.out.println("CommSocket:Run - shutdown");
             }catch (IOException e){
                System.out.println("CommSocket:Run - Socket not ready exception");
                break;
    // SendMessage method -
      *  Sends a text message to a connected listener through port specified by portID
      * @author Chris Duke
      * @param  String message - This will be the message sent out through the server
      * socket's port specified by portID.
       public void SendMessage(String message){
          cOutStream.println(message);
          if (cOutStream.checkError() == true)
            System.out.println("SendMessage : Flush = Error");
          else{
            System.out.println("SendMessage : Flush - No Error");
       }

    a very simple C++ test applications the communictions work fine. Once more code gets added to the C++ application the portion of the socket that C++ listens to seems to close.
    This quite strongly implicates the extra code in the C++ App. The firstly thing I would try would be telnet. Try connecting to both versions of the C++ Application and manually reproducing a proper exchange.
    a recv call the return value is a zero. Microsoft insists this is a sign the Java side has shut down the socket.
    A correct implementation of recv should return the number of bytes received, or -1 for an error. A zero return indicates no bytes received not a socket closed/error. This sounds like FUD to me.
    Are there any known conflicts between Java and C++ in this regard?
    I can see no obvious faults, though the code is incomplete, I don't think it's an sockets implementation issue, at either end, it sounds more likely to be a protocol/handshaking bug in the C++ App.

  • Applet or application wont compile now?

    I recently got a new computer at work. After I set everything up, including jre & sdk 1.4.1, and path file ifno on my windows xp box (same setup as the other machine), my same applications are now throwing errors?
    It's as if for some reason my old setup was more lax on catching compile time errors.
    Whats even weirder, is the old applets and applications compiled on my old machine still run fine and if I try to compile the old applets and applications without resaving them, I get no error, its just after I resave them, even if I only add a blank line to the file.
    any suggestions
    Jason

    any suggestionsYes, tell us what the errors are exactly! And you should probably show relevant parts of the code too.

  • HELP! How to get an applet and place it into an application?

    Hi,
    We have a third party java applet that runs on a specific server. We don't have the code for this applet, only the .class file. We usually connect to the server using any browser with HTTP protocole like http://ourServer. Then we are asked for our username and password and then the applet loads and we can run it. The applet is design to remotely control a piece of equipment. The applet runs on the server and directly coomunicate with this piece of equipment and gives us bak some information into a graphic interface.
    What we want to do is to integrate the applet into one of our stand alone application to eliminte the need for a browser. Since Applet can be add directly into any Panel I've tried something like :
    public myApp() {
         Container c = getContentPane();
         ThirdPartyApplet myApplet = new ThirdPartyApplet();
         c.setLayout(new BorderLayout());     
         c.add(myApplet,BorderLayout.CENTER);
         myApplet.init();
    Of course I've a local copy of the .class file and I've included it into my ClassPath. I can get the interface this way but I can't run it, nothing seems to work.
    I'm not an expert in applet, I don't know how this one works, but it seems that we need to get the one on the server and run it, just as a browser would do. We've also tried to integrate a Browser into our app. We've tried NetClue and IceBrowser but only IceBrowser seems to work perfectly with our applet and we don't have the money for an IceBrowser license.
    So what is wrong with the integration of an applet into a stand alon application?? How do I simulate a Browser and get the applet from the server?
    Can anyone help me on this one?
    Thanks
    Steeves

    There's a link to download the Java source on this page.
    http://java.sun.com/j2se/downloads.html
    Once you have it, look for the appletviewer source in
    src\share\classes\sun\applet

  • Separte GUI and application code

    Below is my code to separate GUI and application code. When i try to execute the code i get message applet not initiated. Can any one point what mistake i am doing in the code.
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class ColorAction extends AbstractAction
         public ColorAction(String name, Icon icon,Color c, Component comp)
              putValue(Action.NAME, name);
              putValue(Action.SMALL_ICON,icon);
              putValue("Color",c);
              target = comp;
         public void actionPerformed(ActionEvent evt)
              Color c = (Color)getValue("Color");
              target.setBackground(c);
              target.repaint();
         private Component target;
    class ActionButton extends JButton
         public ActionButton(Action a)
              setText((String)a.getValue(Action.NAME));
              Icon icon = (Icon)a.getValue(Action.SMALL_ICON);
              if(icon != null)
                   setIcon(icon);
              addActionListener(a);
    public class SepGUI extends JApplet
         public void init()
              JPanel panel = new JPanel();
              Action blueAction = new ColorAction("Blue",new ImageIcon("a.gif"),Color.blue,panel);
              Action yellowAction = new ColorAction("Yellow",new ImageIcon("a.gif"),Color.yellow,panel);
              Action redAction = new ColorAction("Red",new ImageIcon("a.gif"),Color.red,panel);
              panel.add(new ActionButton(yellowAction));
              panel.add(new ActionButton(blueAction));
              panel.add(new ActionButton(redAction));
              Container contentPane = getContentPane();
              contentPane.add(panel);
    }

    public class SepGUI extends JApplet
      public void init()
        JPanel panel = new JPanel();
        try
          Action blueAction = new ColorAction("Blue",new ImageIcon(new java.net.URL (getCodeBase(),"a.gif")),Color.blue,panel);
          Action yellowAction = new ColorAction("Yellow",new ImageIcon(new java.net.URL (getCodeBase(),"a.gif")),Color.yellow,panel);
          Action redAction = new ColorAction("Red",new ImageIcon(new java.net.URL (getCodeBase(),"a.gif")),Color.red,panel);
          panel.add(new ActionButton(yellowAction));
          panel.add(new ActionButton(blueAction));
          panel.add(new ActionButton(redAction));
        catch(Exception e){}
        Container contentPane = getContentPane();
        contentPane.add(panel);
    }

  • Signed Applet and native code

    Hi all,
    I have an application which I deploy with webstart and includes native code. This all works perfectly with webstart. I now want to deploy it as an applet. This works accept for the native code. I have done heaps of searching and cannot determine the most appropriate way to make the native code visible to the applet.
    Ultimately I am at the point where i recieve a UnsatisfiedLinkError when calling loadLibrary(...) for the native code. Currently i have the native code (dll's for windows, so's for Solaris etc) in independent jars which are also signed (as needed for webstart).
    Could anyone give me some advise or a reference to more info on this topic.
    I am using Java 1.5 and am happy to use 1.6 if neccessary.
    Thanks,
    Dave

    Andrew - of course you were correct about the signed cert - I misspoke when the CA signed applet didn't show a warning. (You were also right that I must have checked 'always accept' the certificate on the server I had the CA signed cert on).
    I think you guys are on to something about the privileged actions. It would explain where one popup has the icon and the other doesn't. We have Javascript making calls into the applet and we do use JNI (although I don't think there are any calls back). We do wrap these calls in privileged actions but maybe we missed something. What I've seen before is a security exception is thrown if we don't wrap them - but maybe there are areas where we don't and it doesn't throw an exception or it does and we eat it somehow (and for whatever reason doesn't cause anything noticeable).
    Now that I know it could likely be the applet code and not necessarily a build issue with signing the jars, I have another place to look...
    I'll check it out and let you know what I find.

  • [svn:fx-trunk] 5464: ASDoc updates for FxApplication and Application ( no code changes)

    Revision: 5464
    Author: [email protected]
    Date: 2009-03-20 11:52:50 -0700 (Fri, 20 Mar 2009)
    Log Message:
    ASDoc updates for FxApplication and Application (no code changes)
    * notes the pageTitle property is for use with the SDK HTML templates
    * update the default values for backgroundGradientColors
    QE Notes: None
    Doc Notes: Please review
    Bugs: SDK-16535, SDK-16693
    Reviewer:
    tests: checkintests
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-16535
    http://bugs.adobe.com/jira/browse/SDK-16693
    Modified Paths:
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/FxApplication.as
    flex/sdk/trunk/frameworks/projects/framework/src/mx/core/Application.as

  • Running and restricting unsafe code within a safe application

    My application (actually a web application) will do the following:
    - Obtain Java source code from an untrusted source. One such piece of source code will be a JUnit test class (and another will be the class(es) it is testing).
    - Compile the source code in memory, storing the compiled classes into byte[] arrays, using the JSR-199 compiler.
    - Load the JUnit test class that was just compiled, using a URLClassLoader.
    - Run the JUnit test (using the JUnitCore core class in JUnit 4.4) and report the results to the client.
    Since the source code is untrusted, it may do malicious things that I want to prevent. I have wide flexibility in limiting the permissions of the code; for example, I can disallow file reading and writing, network access, etc. However, I do not want to restrict these permissions on my own application, or the JUnit code itself (such as the class JUnitCore, which runs the JUnit test). So the flow will go like this:
    1. Allow unrestricted security policy initially.
    2. Obtain source code.
    3. Compile source code.
    4. Apply restricted security policy.
    5. Load compiled classes and use JUnitCore to run the JUnit test class. (Loading should be restricted so that static initializers in the unsafe code cannot do harm.)
    6. Remove restricted security policy.
    7. Report results (in particular, violating the security policy means, "Test failed").
    However, my very basic understanding of the security policies in Java is that permission granting within a call stack seems to go the other way; untrusted code is run with a restricted security policy, but it may make a call to a system library, for instance, that runs as a privileged block and has extra permissions that the unsafe calling code does not have. I want to flip that around and say, "My code is okay, but when it executes the method JUnitCore.run, restrict the access of that method". Or, to be even more fine-grained, "My code, and any code from junit-4.4.jar such as JUnitCore, is okay, but somewhere in the bowels of JUnitCore.run, some unsafe code will eventually be called, and I want its access restricted."
    I don't even know if this is possible the way I have stated it, and if so, I am having trouble mapping the abstract concepts of a codebase, code signers, etc., on to the specific pieces of code in my project. Someone on another forum suggested that the URLClassLoader used to load the unsafe classes would somehow play the role of a codebase, so that I could state that anything loaded with that class loader should be restricted, but I have not seen a syntax for expressing this in the documentation. Plus, I don't see how using the URLClassLoader used to load the unsafe classes would play a role, since permissions are granted, not denied. It seems that I need a way to map a codebase to the safe code, not the unsafe code, and then grant permissions to the unsafe code.
    It seems like it could be as simple as creating a policy file (say, unsafe.policy) with the contents
    grant codebase "My Application + supporting classes I wrote + any class in junit-4.4.jar" {
        permission java.security.AllPermission;
    };and running java -Djava.security.manager -Djava.security.policy=unsafe.policy MyApp, except that I don't really know how to specify the codebase, or if it is possible to draw a box around my code + junit-4.4.jar in that way.
    Thank you,
    Dave
    Edited by: pexatus on Aug 10, 2008 12:48 PM

    >
    Have a look at AccessController and AccessControlContext. These are the tools you need for this task.
    >
    By "this task", do you mean, "writing a custom SecurityManager"? Or do you mean the more general task of creating a security policy (such as by writing a policy file) to ensure untrusted code does no damage?
    I'm sorry to be so slow, but I don't see how to use the two classes you mention for my task. I assume that the only reason I need AccessController is to call AccessController.getContext() to get an instance of AccessControlContext, since the other methods of AccessController don't seem to be what I need. AccessController.checkPermission presumes I have successfully written the security policy already, which is the problem I am trying to solve, and the various AccessController.doPrivileged methods appear to grant extra privileges to code that is called, which is the problem I mentioned earlier: I want certain code that I call to have fewer privileges, rather than more.
    Similarly, I do not see any methods in AccessControlContext that could tell me whether the current executing code is trusted or not. It, too, has a checkPermission method that will work if I set up the security policy correct, which is what I cannot figure out how to do in the first place, and a getDomainCombiner() method. A DomainCombiner has only a single method, which assumes that I already have an array of ProtectionDomain objects. To create a ProtectionDomain, I need to specify a CodeSource, which is, as the documentation indicates, an extension of "the concept of a codebase". It is at this point I get completely lost in the abstract and generic nouns such as domain, codebase, code source, context, and I do not see how to connect them to concrete nouns that I understand such as class file, package, method, etc. Is it the case that I need to create a CodeSource representing the trusted classes? Is there an elegant way to create a CodeSource representing all the classes in a a project (say, under a given directory, or contained within a given jar file), short of enumerating them or digging into directories and jar files doing a search? And once I create this CodeSource within my program, what do I do with it to specify that I want my security policy to allow all permissions for the classes represented by the CodeSource, and restricted permissions for all classes outside the CodeSource, regardless of call order? (since trusted code will call untrusted code, and I do not want the permissions of the trusted code to be inherited by the untrusted code)
    Again, I am sorry to be so ignorant, and I appreciate the help, but I am simply having trouble connecting the concepts described in the documentation to the specific concrete aspects of my application.
    Dave

  • Design web application API codes to extensible and can adapt to change

    Design web application API codes to extensible and can adapt to change with little effort to cater to SOA architecture.
    How will you all design to cater for this kind of requirement?

    RonaldMacdonald wrote:
    Design web application API codes to extensible and can adapt to change with little effort to cater to SOA architecture.I don't worry about change until I can write something that can actually be used once. I worry about use before reuse.
    >
    How will you all design to cater for this kind of requirement?I use Spring. It helps.
    %

  • Signed applet and HTML parameters

    I've created a signed applet and everything works fine, except for the fact that i can't add parameters to the applet.
    Without the parameters in the HTML the applet inits and starts and can be used without problems. But when I add paramaters, the applet reports a "class not found exception".
    I used HTML-converter to convert the applet tag to object/embed tags.
    Has anyone had the same problem or knows what I'm doing wrong? I'd really appreciate some help.
    Thanks in advance,
    Erik
    My HTML source:
    <OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    WIDTH = "600" HEIGHT = "400" codebase="http://java.sun.com/products/plugin/1.3/jinstall-13-win32.cab#Version=1,3,0,0">
    <PARAM NAME = CODE VALUE = "TNA" >
    <PARAM NAME = ARCHIVE VALUE = "TNA.jar" >
    <PARAM NAME="type" VALUE="application/x-java-applet;version=1.3.0">
    <PARAM NAME="scriptable" VALUE="false">
    <COMMENT>
    <EMBED type="application/x-java-applet;version=1.3.0" CODE = "TNA" ARCHIVE = "tna.jar" WIDTH = "600" HEIGHT = "400" scriptable=false pluginspage="http://java.sun.com/products/plugin/1.3/plugin-install.html"><NOEMBED></COMMENT>
    </NOEMBED></EMBED>
    </OBJECT>
    <!--
    <APPLET CODE = "TNA" ARCHIVE = "tna.jar" WIDTH = "600" HEIGHT = "400">
    </APPLET>
    -->

    Try this:
    OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    WIDTH = "600" HEIGHT = "400" codebase="http://java.sun.com/products/plugin/1.3/jinstall-13-win32.cab#Version=1,3,0,0">
    <PARAM NAME = "java_code" VALUE = "TNA.class" >
    <PARAM NAME = "java_archive" VALUE = "TNA.jar" >
    <PARAM NAME = "java_type" VALUE="application/x-java-applet;version=1.3.1">
    <PARAM NAME="scriptable" VALUE="false">
    <COMMENT>
    <EMBED type="application/x-java-applet;version=1.3.0" CODE = "TNA" ARCHIVE = "tna.jar" WIDTH = "600" HEIGHT = "400" scriptable=false pluginspage="http://java.sun.com/products/plugin/1.3/plugin-install.html"><NOEMBED></COMMENT>
    </NOEMBED></EMBED>
    </OBJECT>
    <!--
    <APPLET CODE = "TNA" ARCHIVE = "tna.jar" WIDTH = "600" HEIGHT = "400">
    </APPLET>

  • Run applet as application

    Hi To All,
    I'm converting a Applet into Application.
    All the things are runing well but when my Applet gets to try the access getDocumentBase() method
    its giving a nullPointerException
    My all code is written below please help me to find out the problem
    import java.awt.Frame;
    import java.awt.event.*;
    import java.awt.Dimension;
    import java.applet.Applet;
    // Applet to Application Frame window
    public class AppletFrame extends Frame implements java.awt.event.WindowListener
    public static void startApplet(String className, String title,String args[])
    { Dimension appletSize;
    try
    // create an instance of your applet class
    myApplet = (Applet) Class.forName(className).newInstance();
    catch (ClassNotFoundException e)
    { System.out.println("AppletFrame " + e);
    return;
    catch (InstantiationException e)
    System.out.println("AppletFrame " + e);
    return;
    } catch (IllegalAccessException e)
    System.out.println("AppletFrame " + e);
    return;
    } // initialize the applet myApplet.init();
    myApplet.start();
    AppletFrame f = new AppletFrame(title);
    f.add("Center", myApplet);
    f.addWindowListener(f);
    appletSize = myApplet.getSize();
    f.pack();
    f.setSize(appletSize);
    f.show();
    public AppletFrame(String name)
    { super(name);
    } public void windowClosing(java.awt.event.WindowEvent ev)
    { myApplet.stop();
    myApplet.destroy();
    java.lang.System.exit(0);
    } public void windowClosed(java.awt.event.WindowEvent ev) {}
    public void windowActivated(java.awt.event.WindowEvent ev) {}
    public void windowDeactivated(java.awt.event.WindowEvent ev) {}
    public void windowOpened(java.awt.event.WindowEvent ev) {}
    public void windowIconified(java.awt.event.WindowEvent ev) {}
    public void windowDeiconified(java.awt.event.WindowEvent ev) {}
    private static Applet myApplet;
    public static void main(String args[]){
    startApplet("appletImageBook.appletImage.Standalone2","XApplets",args);
    ====================================================
    And Standalone2.java is
    public class Standalone2 extends Applet {
    Image img ;
    public void init()
    { add(new Button("Standalone Applet Button"));
    img = getImage(getDocumentBase(),"images/office1.jpg");
    public void paint(Graphics g) {
    g.drawImage(img,0,0,null);
    =====================================================
    And while runing AppletFrame.java it is giving Error below
    ===============================
    Exception in thread "main" java.lang.NullPointerException at java.applet.Applet.getDocumentBase(Applet.java:125)
    at appletImageBook.appletImage.Standalone2.init(Standalone2.java:20) at appletImageBook.appletImage.AppletFrame.startApplet(AppletFrame.java: 38)
    at appletImageBook.appletImage.AppletFrame.main(AppletFrame.java:99)
    ===============================
    Any type of help will be fine for me
    Thanks in advance

    The only difference between an applet and an application should be the way they are started.
    Instead of adding an applet to a frame, open a frame from the applet. Open the same frame from your application.
    Or instead of a frame, use a (J)Panel. Add it directly to your applet, or add it to a new frame when you want to run it as an application.
    In any case: separate the way the UI is created from the way the application is started.

  • Can a servlet launch an Applet or Application?

    Hello:
    Is it possible for a servlet to launch an Applet or Application? I am new to servlet technology, and am trying to find out what I can and cannot do. I've gone through much of the forums, and see that servlet can correspond with Applets, but can servlets launch something other than a servlet? If so, can someone please provide an implementation example?
    Thanks in advance for your replies!

    Thanks for replying, but I would love for you to be a bit more specific. My knowledge of servlets is limited. I just purchased Marty Hall's moreservlet book, and am just getting done with chapter 3. I would like to write a servlet from which I can launch an applet, but that is not covered in his book (I don't think). I know it can be done because I've seen a code snippet using the applet tag and codebase, but I do not know how to put it together in a complete servlet. Can you please help? I would truly appreciate it!

Maybe you are looking for