Beep in an applet

Hi !
I would like to find a portable way, if possible without an audio file, to make a "bip" in an applet.
Is printing the character with code 07 to standard output, or standard error, could
work and be portable enough ?
Thanks,
-- Alexis

Not sure what you mean here, but you can use the client resources without any added overhead with;-
if(conition=error); // catch(Exception ...
java.awt.Toolkit.getDefaultToolkit().beep();

Similar Messages

  • It works as an app but not as an applet!

    First of all many thanks to this forum for the help I have received already, this is true community spirit in action.
    Right I am writing a program that works both as an application and as an applet. It is starting to take shape, what I have so far is a text area and a button for pasting the contents of the clipboard to the text area. The code pastes perfectly when run as an application but when I try the code in a browser it does not seem to paste the clipboard contents into the text area. Any help gratefuly received, Dave.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.datatransfer.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class BigRedsBanBuster extends JApplet implements ClipboardOwner,ItemListener,ActionListener
         JTextArea data=new JTextArea(20,60);
         JButton action=new JButton("Hit Me!");
      JLabel area=new JLabel("Copy file to Clipboard and the press Hit Me!");
      JScrollPane scroll= new JScrollPane(data,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
         public void init()
           FlowLayout fL=new FlowLayout();
        Container contentArea=getContentPane();
        contentArea.setLayout(fL);
        setVisible(true);
        contentArea.setBackground(Color.blue);
              contentArea.add(area);
              contentArea.add(scroll);
              contentArea.add(action);
              action.addActionListener(this);
         public void actionPerformed(ActionEvent e)
           if (e.getSource()==action)
                paste();
         public void paste()
        Clipboard c = this.getToolkit().getSystemClipboard();
           Transferable t = c.getContents(this);
           try
             if (t.isDataFlavorSupported(DataFlavor.stringFlavor))
                  String s = (String) t.getTransferData(DataFlavor.stringFlavor);
                  data.setText(s);
             else if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
                  java.util.List files = (java.util.List)
                  t.getTransferData(DataFlavor.javaFileListFlavor);
                  java.io.File file = (java.io.File)files.get(0);
                  data.setText(file.getName());
           catch (Exception e)
             this.getToolkit().beep();
      public void itemStateChanged(ItemEvent e)
      public void lostOwnership(Clipboard c, Transferable t)
      public static void main(String args[])
           BigRedsBanBuster brbb=new BigRedsBanBuster();
        JFrame f=new JFrame();
           brbb.init();
           f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.setContentPane( brbb.getContentPane() );
        f.setSize(1000,600);
        f.addWindowListener(new java.awt.event.WindowAdapter()
          public void windowClosing(java.awt.event.WindowEvent evt)
            System.exit(0);
        f.show();
    }P.S. Excuse the warped indentation caused through copy & paste.

    There is a security error. I am not sure that an Applet can access the clipboard.
    Here is the error generated:
    java.security.AccessControlException: access denied (java.awt.AWTPermission accessClipboard)
         at java.security.AccessControlContext.checkPermission(AccessControlContext.java:270)
         at java.security.AccessController.checkPermission(AccessController.java:401)
         at java.lang.SecurityManager.checkPermission(SecurityManager.java:542)
         at java.lang.SecurityManager.checkSystemClipboardAccess(SecurityManager.java:1387)
         at sun.awt.windows.WToolkit.getSystemClipboard(WToolkit.java:632)
         at untitled5.BigRedsBanBuster.paste(BigRedsBanBuster.java:43)
         at untitled5.BigRedsBanBuster.actionPerformed(BigRedsBanBuster.java:38)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1767)
         at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1820)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:419)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:258)
         at java.awt.Component.processMouseEvent(Component.java:5021)
         at java.awt.Component.processEvent(Component.java:4818)
         at java.awt.Container.processEvent(Container.java:1525)
         at java.awt.Component.dispatchEventImpl(Component.java:3526)
         at java.awt.Container.dispatchEventImpl(Container.java:1582)
         at java.awt.Component.dispatchEvent(Component.java:3367)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3359)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3074)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3004)
         at java.awt.Container.dispatchEventImpl(Container.java:1568)
         at java.awt.Component.dispatchEvent(Component.java:3367)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:445)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:191)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)

  • How to show progress - Applet - Servlet

    Hi,
    I am new to applet-servlet communication. I have to show the progress at the applet front-end using a JProgressBar for a task being done at the servlet end. I request the gurus on the forum to post any example code for the above situation.

    Hi,
    U will have to use the SwingWorker to popup the JProgressBar, but in here i dont think u will be getting any input from servlet giving the job completed, if u are using jdk1.4.1 u can use
    setIndeterminate(true);
    I am attaching 2 methods below which i use to display the JProgressBar
    Method long task is where i actually call the servlet and in method buildData i create the URLConnection etc
    //appletData must implement Serializable
    public void buildData(Object appletData)throws Exception
    //define servlet name here
    ObjectInputStream inputFromServlet = null;
    URL          studentDBservlet = new URL("MyServlet");
    URLConnection servletConnection = studentDBservlet.openConnection();
    servletConnection.setDoInput(true);
    servletConnection.setDoOutput(true);
    servletConnection.setUseCaches(false);
    servletConnection.setRequestProperty("Content-Type", "application/octet-stream");
    ObjectOutputStream outputToServlet =
              new ObjectOutputStream(servletConnection.getOutputStream());
         // serialize the object
         if (!SwingUtilities.isEventDispatchThread())
              outputToServlet.writeObject(input);
              outputToServlet.flush();
              outputToServlet.close();
              inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
         else
              inputFromServlet = longTask(servletConnection, outputToServlet, appletData);
    private ObjectInputStream longTask(final URLConnection servletConnection,
                        final ObjectOutputStream outputToServlet,
                        final Object appletData)
         final JDialog dialog = new JDialog(PlanApplet.appletFrame, "Please Wait", true);
    isProcess = true;
         MapsPanel panel = new MapsPanel();
         panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
         //MapsLabel label = new MapsLabel("Work in process....");
    //label.setFont(Constant.bigFont);
         //label.setPreferredSize(new Dimension(230, 40));
         JProgressBar progressBar = new JProgressBar();
         progressBar.setIndeterminate(true);
         progressBar.setPreferredSize(new Dimension(140, 30));
    // final JugglerLabel jugLabel = new JugglerLabel();
    // jugLabel.startAnimation();
    // panel.setPreferredSize(new Dimension(175, 175));
         MapsPanel progressPanel = new MapsPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
         progressPanel.setPreferredSize(new Dimension(140, 80));
    progressPanel.add(progressBar);
    //     progressPanel.add(jugLabel);
    //     panel.add(Box.createVerticalStrut(5));
         //panel.add(label);
         panel.add(Box.createVerticalStrut(15));
         panel.add(progressPanel);
         panel.add(Box.createVerticalStrut(15));
         dialog.setSize(150, 115);
         dialog.setResizable(false);
    //     dialog.getContentPane().add(jugLabel);
    dialog.getContentPane().add(panel);
    dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    dialog.setLocation(ScreenSize.getDialogLocation(dialog));
    //      final javax.swing.Timer popupTimer = new javax.swing.Timer(2000, new TimerListener(dialog));
         final SwingWorker worker = new SwingWorker()
         public Object construct()
              try
              PlanApplet.applet.setCursor(new Cursor(Cursor.WAIT_CURSOR));
              outputToServlet.writeObject(appletData);
              outputToServlet.flush();
              outputToServlet.close();
              return new ObjectInputStream(servletConnection.getInputStream());
              catch (Exception exc)
              return null;
         public void finished()
    // jugLabel.stopAnimation();
              dialog.dispose();
    Toolkit.getDefaultToolkit().beep();
    isProcess = false;
              LogWriter.out("the long process is finished", LogWriter.BASIC);
         worker.start();
    // popupTimer.start();
         //System.out.println("Process complete");
         dialog.show();
    // while(isProcess)
         return (ObjectInputStream) worker.getValue();

  • Applet won't proceed past "activate" command

    I am unable to work around this any longer.
    I have a script saved as an application bundle:
    (*BEGIN SCRIPT FOR APPLET 1*)
    set BA_ to ((path to me as Unicode text) & "Contents:Resources:BeepApplet.app")
    beep 3
    display dialog "Okay, this dialog shows.  But will the one AFTER the activate command show?"
    tell application BA_ to activate --should cause another 5 beeps, and probably will
    --But will the following dialog show?
    display dialog "Foiled Again?"
    --THE ANSWER IS NO!
    (*END SCRIPT FOR APPLET 1*)
    As you can see, the applet contains a second applet (in the bundle, but it could be anywhere if its path is properly specified).
    When the second applet is called (tell application BA_ to activate), the second applet does its thing properly (provides another 5 beeps), but for me the first applet won't proceed past the "activate" command.
    I've tried calling application BA_ in a variety of ways, but always seem to get the same result.  Is this normal behavior?  Is there a way around it?
    (Here's the very simple underlying script for application BA_:
    beep 5)

    Please see my response to red_menace.  I've indicated that both your and his response were "helpful"
    It appears that my response to red_menace has disappeared.  Basically, it provided a version of the applet script that seems to work;
    (*BEGIN REVISED SCRIPT FOR APPLET 1*)
    set BA_ to ((path to me as Unicode text) & "Contents:Resources:BeepApplet.app")
    beep 3
    display dialog "Okay, this dialog shows.  But will the one AFTER the launch-run command show?"
    tell application BA_ to launch
    tell application BA_ to run
    --But will the following dialog show?
    display dialog "Foiled Again?"
    --THE ANSWER IS (it seems to)!
    (*END REVISED SCRIPT FOR APPLET 1*)
    I also experimented with the load script/run script approach; while promising, it wasn't suited to my purposes.

  • Toolkit.getDefaultToolkit().beep() does not beep!

    Hi,everyone:
    I met a problem when I used Toolkit.getDefaultToolkit().beep() .
    When running, no beep can be heard!
    My Environment is as follows:
    Hardware: Dell dimension 2400
    OS : Windows 2003 Enterprise Edition
    JDK : J2SDK1.4.2
    Code :
    Toolkit.getDefaultToolkit().beep();
    (In java application)
    Does My enviornment not support this operation? Can anyone tell me?
    Thank you.

    Yes, its a bit buggy. Does this work for you?
    ** Will you please tell me where to find evidence that this is a bit buggy?
    Thank you.
    System.out.print ( "\007" );In my java application, System.out.print ( "\007" ) works.
    ** But when I write it in my applet, no beep can be heard!
    import java.applet.*;
    import java.awt.*;
    public class MyBeepApplet extends Applet
        int cx = 50;
        int cy = 50;
        String msg="";
        public boolean mouseDown(Event e, int x, int y)
            msg = " Beep?";
            cx = x;
            cy = y;   
            for(int i=0; i<260;i++){
                System.out.print("\007");
                System.out.flush();
            repaint();      
            return true;
        public void paint(Graphics g)
            g.drawString(msg, cx,cy);
    }

  • Help ON Using Applets

    Hello,
    I've written an applet that is supposed to allow users to use my program on the Internet. The applet works alright but the problem is that when the applet containing the program is loaded, the functions(close, open file, and so on) doesn't work. Can somebody help to resolve this? Please go to www.geocities/keito30582 to view the applet. PLS help

    public class DTApplet extends Applet
    implements ActionListener, Observer
    DecisionTable dt; //DT
    Frame mainFrame;
    int posx, posy;
    boolean listEm;
    Font btnFont;
    String name = "DT";
    public DTApplet()
    setSize(100,200);
    public void init() {
    btnFont = new Font("SansSerif", Font.BOLD, 14);
    posx = 14;
    posy = 14;
    setLayout(new GridLayout(0,1,2,2));
    setBackground(new Color(0x0FFEECC));
    Panel p1;
    Button btn;
    p1 = new Panel();
    p1.setLayout(new FlowLayout(FlowLayout.LEFT));
    btn = new Button(name);
    btn.setFont(btnFont);
    btn.setActionCommand(name);
    btn.addActionListener(this);
    p1.add(btn);
    add(p1);
    try {
    String list_em = getParameter("list");
    if (list_em == null)
    list_em = getParameter("preset");
    if (list_em == null)
    list_em = getParameter("presetlist");
    if (list_em == null || list_em.equals("0") || list_em.equals("false"))
    listEm = false;
    else
    listEm = true;
    catch (NullPointerException npe) { }
    public void actionPerformed(ActionEvent e) {
    String nam = e.getActionCommand();
    int i;
    String title = "Decision Table ";
    Frame f = new Frame(title);
    DecisionTable dt = new DecisionTable();
    f.add("Center", dt);
    f.pack();
    f.setResizable(false);
    f.setLocation(posx, posy);
    posx += 12;
    posy += 10;
    canvasesUp += 1;
    f.show();
    public void update(Observable o, Object arg) {
    if (arg != null && arg instanceof URL) {
    getAppletContext().showDocument((URL)arg, "sd");
    return;
    public int canvasesUp = 0;
    static Frame f;
    static DTApplet sa;
    public static void main(String []args) {
    f = new Frame("DT");
    sa = new DTApplet();
    if (args.length > 0) sa.listEm = true;
    f.add("Center",sa);
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    if (sa.canvasesUp > 0) {
    try {
    Toolkit.getDefaultToolkit().beep();
    } catch (SecurityException se) { }
    else
    System.exit(0);
    sa.init();
    sa.start();
    f.pack();
    f.show();

  • Complete code to customize Ora/Jbo/Dac errors in applets.

    Note : In this code you will see I just took one row from the stringBuffer which is hold all the error message details, But you can modify it in your concern.
    Good luck...Ali
    1- add following classes to your project package
    1-1-This class parses the errors. With this the error message is in your hand as a String/StringBuffer and of course you can substring that.
    import oracle.dacf.util.errormanager.*;
    import oracle.dacf.dataset.*;
    import oracle.jbo.*;
    public class myErrorParser{
    ** Walk through JBO error stack and create a concatenated
    error message.
    ** @return JBO error message
    public static String getJboErrorMessageStack(ErrorMessage em){
    StringBuffer returnvalue = new StringBuffer();
    String errMsg="";
    ErrorMessageContext context=em.getErrorMessageContext();
    if(context!=null && context instanceof DacfErrorMessageContext){
    if(((DacfErrorMessageContext)context).getException() instanceof DacfRuntimeException){
    Exception origException=((DacfRuntimeException) ((DacfErrorMessageContext)context).getException()).getOriginalException();
    if(origException!=null){
    //returnvalue.append(origException.getMessage());
    errMsg=(origException.getMessage()).toString();
    Object [] details = null;
    if(origException instanceof JboException){
    details=((JboException)origException).getDetails();
    if(details!=null && details.length>0){
    for(int i=0;i<details.length;i++){
    if(details[i] instanceof JboException){
    //returnvalue.append("\n");
    //returnvalue.append(((JboException)details).getMessage());
    errMsg=(((JboException)details[i]).getMessage()).toString();
    }else if (details[i] instanceof Exception){
    //returnvalue.append("\n");
    //returnvalue.append(((Exception)details[i]).getMessage());
    errMsg=(((Exception)details[i]).getMessage()).toString();
    if (errMsg.indexOf("ORA_2")!=1) // take trigger errors errMsg=errMsg.substring(errMsg.indexOf("ORA_2")+1,errMsg.indexOf("\n"));
    else if (errMsg.indexOf("DAC_")!=1)// take DAC error errMsg=errMsg.substring(errMsg.indexOf("DAC_")+1,errMsg.indexOf("\n"));
    else if (errMsg.indexOf("ORA_")!=1)//take other ORA erros errMsg=errMsg.substring(errMsg.indexOf("ORA_")+1,errMsg.indexOf("\n"));
    return errMsg;
    1-2- This class defines your own error listener. If you like you can customize the errors (change the text) one by one as shown in this class.(the code which is commented out)
    import javax.swing.*;
    import java.awt.*;
    import oracle.dacf.util.errormanager.*;
    public class myErrorListener implements ErrorManagerListener{
    public void addingErrorMessage(ErrorMessage message)
    throws oracle.dacf.util.errormanager.ErrorMessageVetoException {
    String errorMessage=myErrorParser.getJboErrorMessageStack(message);
    /* if(errorMessage.indexOf("ORA-00001")!=-1)
    JOptionPane.showMessageDialog(null,"Class name should be unique", "Error",JOptionPane.ERROR_MESSAGE);
    else if(errorMessage.indexOf("DAC-603")!=-1){
    //catch the client error, ignore the similar server one
    if(message.getMessageText().getId().toString().equals("DAC-307"))
    JOptionPane.showMessageDialog(null,"Class name should not be empty", "Error",JOptionPane.ERROR_MESSAGE);
    else
    return;
    if (errorMessage.length()!=0){
    Toolkit myBeep = Toolkit.getDefaultToolkit();
    myBeep.beep();
    JOptionPane.showMessageDialog(null,errorMessage, "Error",JOptionPane.ERROR_MESSAGE);
    throw new ErrorMessageVetoException("Error processed. "+getName());
    public String getName(){
    return "Class editor's error handler";
    public void removingErrorMessage(ErrorMessage parm1)
    throws oracle.dacf.util.errormanager.ErrorMessageVetoException{
    public void rollingBackAddingErrorMessage(ErrorMessage parm1){
    public void rollingBackRemovingErrorMessage(ErrorMessage parm1){
    2- add following statements at top of the jbInit() method in the main applet/frame.
    this code removes the default error listener and add your customized one. You can comment this out whenever you want to back to default listener.
    if (ErrorManager.findLoggerByName(DacfErrorPopupLogger.NAME)!=null){
    ErrorManager.removeErrorLogger(ErrorManager.findLoggerByName(DacfErrorPopupLogger.NAME));
    ErrorManager.addErrorManagerListener(new myErrorListener());
    null

    JDev in default shows a long trace stack with several lines for the errors. The above statement takes (substring) only that line of stack error, which is started by "ORA-2".
    Meaning of "ORA-2": As you know in PL/SQL all user defined errors (rasie_application_error) must be in range -20000 to -29999 (hope i am right, for sure started with -2) for example if you coded in trigger like this:
    raise_applecation_error(-20001,"Not Found");
    this error shows in JDev default error message like this:
    ORA-20001: Not Found
    So to take this from the JDev error string buffer, i said :
    if (errMsg.indexOf("ORA_2")!=1) /* take trigger errors */
    errMsg=errMsg.substring(errMsg.indexOf("ORA_2")+1,errMsg.indexOf("\n"));
    The other nested If(s) check for other type of errors .
    notes:
    - "!=1" means if exist.
    - Yes you should use "ORA-2" instead of "ORA_2"
    Hope be clear.Ali
    null

  • Can somebody help me find a bug in my applet?

    Hi,
    I am in the process of creating a RPG program using Java. I am not very experienced with java, however the problem i am currently facing is something i can't seem to figure out. I would like to draw a simple grid where a character (indicated by a filled circle) moves around this grid collecting items (indicated by a red rectangle). When the character moves on top of the grid with the item, i would like it to disappear. Right now i am not worrying about the fact that the item will reappear after the character moves away again, because sometimes, when the character moves over the item, nothing happens/another item disappears. i have been at this for 4 days and still cannot figure out what is goign on. can somebody please help me? it would be most appreciated.
    Thanks

    State is the key. Here the rects array keeps track of things. Of course, there are lots of ways to put these things together. Use the arrow keys to move the token and the x key to reset the rectangles.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class RPG extends JApplet
        public void init()
           RPGPanel rpgPanel = new RPGPanel();
           Container cp = getContentPane();
           cp.setLayout(new BorderLayout());
           cp.add(rpgPanel);
        public static void main(String[] args)
            JApplet applet = new RPG();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(applet);
            f.setSize(400,400);
            f.setLocation(200,200);
            applet.init();
            f.setVisible(true);
    class RPGPanel extends JPanel
        final int
            GRID_SIZE = 8,
            PAD       = 20;
        Rectangle[] rects;
        int rectSize;
        Ellipse2D.Double token;
        int dx, dy;
        public RPGPanel()
            TokenController controller = new TokenController(this);
            dx = 2;
            dy = 2;
            requestFocusInWindow();
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            drawGrid(g2);
            drawRects(g2);
            g2.setPaint(Color.red);
            g2.fill(token);
        public void moveToken(int horiz, int vert)
            int x = dx * horiz;
            int y = dy * vert;
            if(isWithinBounds(x, y))
                token.x += x;
                token.y += y;
                repaint((int)(token.x - dx), (int)(token.y - dy),
                        (int)(token.x + token.width + dx),
                        (int)(token.y + token.height + dy));
            else
                Toolkit.getDefaultToolkit().beep();
            // check for contact with rects
            checkForContact();
        public void reset()
            for(int j = 0; j < rects.length; j++)
                if(rects[j].width == 0)
                    rects[j].width = rectSize;
            token.x = getWidth()/2 - token.width/2;
            token.y = getHeight()/2 - token.height/2;
            repaint();
        private boolean isWithinBounds(int x, int y)
            int w = getWidth();
            int h = getHeight();
            Rectangle r = token.getBounds();
            if(r.x + x < 0 || r.x + r.width + x > w)
                return false;
            if(r.y + y < 0 || r.y + r.height + y > h)
                return false;
            return true;
        private void checkForContact()
            for(int j = 0; j < rects.length; j++)
                Rectangle r = rects[j];
                if(token.intersects(r.x, r.y, r.width, r.height))
                    r.width = 0;
            repaint();
        private void drawGrid(Graphics2D g2)
            int w = getWidth();
            int h = getHeight();
            double xInc = (double)(w - 2*PAD) / GRID_SIZE;
            double yInc = (double)(h - 2*PAD) / GRID_SIZE;
            double x1 = PAD, y1 = PAD, x2 = w - PAD, y2;
            // horizontal lines
            for(int j = 0; j <= GRID_SIZE; j++)
                g2.draw(new Line2D.Double(x1, y1, x2, y1));
                y1 += yInc;
            // vertical lines
            y1 = PAD; y2 = h - PAD;
            for(int j = 0; j <= GRID_SIZE; j++)
                g2.draw(new Line2D.Double(x1, y1, x1, y2));
                x1 += xInc;
        private void drawRects(Graphics2D g2)
            if(rects == null)
                initRectsAndToken();
            g2.setPaint(Color.blue);
            for(int row = 0; row < GRID_SIZE; row++)
                for(int col = 0; col < GRID_SIZE; col++)
                    int index = row * GRID_SIZE + col;
                    g2.fill(rects[index]);
        private void initRectsAndToken()
            int w = getWidth();
            int h = getHeight();
            double xInc = (double)(w - 2*PAD) / GRID_SIZE;
            double yInc = (double)(h - 2*PAD) / GRID_SIZE;
            rectSize = (int)(0.3 * Math.min(xInc, yInc));
            rects = new Rectangle[GRID_SIZE * GRID_SIZE];
            double x0 = PAD + (xInc - rectSize)/2 + 1;
            double y0 = PAD + (yInc - rectSize)/2 + 1;
            double x = x0, y = y0;
            for(int row = 0; row < GRID_SIZE; row++)
                for(int col = 0; col < GRID_SIZE; col++)
                    int index = row * GRID_SIZE + col;
                    rects[index] = new Rectangle((int)x, (int)y, rectSize, rectSize);
                    x += xInc;
                x = x0;
                y += yInc;
            // token
            int d = (int)(0.8 * Math.min(w, h) - 2*PAD) / GRID_SIZE;
            token = new Ellipse2D.Double(w/2 - d/2, h/2 - d/2, d, d);
    class TokenController
        RPGPanel rpgPanel;
        public TokenController(RPGPanel rpgp)
            rpgPanel = rpgp;
            registerKeys();
        private Action up = new AbstractAction()
            public void actionPerformed(ActionEvent e)
                rpgPanel.moveToken(0, -1);
        private Action left = new AbstractAction()
            public void actionPerformed(ActionEvent e)
                rpgPanel.moveToken(-1, 0);
        private Action down = new AbstractAction()
            public void actionPerformed(ActionEvent e)
                rpgPanel.moveToken(0, 1);
        private Action right = new AbstractAction()
            public void actionPerformed(ActionEvent e)
                rpgPanel.moveToken(1, 0);
        private Action reset = new AbstractAction()
            public void actionPerformed(ActionEvent e)
               rpgPanel.reset();
        private void registerKeys()
            rpgPanel.getInputMap().put(KeyStroke.getKeyStroke("UP"), "UP");
            rpgPanel.getActionMap().put("UP", up);
            rpgPanel.getInputMap().put(KeyStroke.getKeyStroke("LEFT"), "LEFT");
            rpgPanel.getActionMap().put("LEFT", left);
            rpgPanel.getInputMap().put(KeyStroke.getKeyStroke("DOWN"), "DOWN");
            rpgPanel.getActionMap().put("DOWN", down);
            rpgPanel.getInputMap().put(KeyStroke.getKeyStroke("RIGHT"), "RIGHT");
            rpgPanel.getActionMap().put("RIGHT", right);
            rpgPanel.getInputMap().put(KeyStroke.getKeyStroke("X"), "X");
            rpgPanel.getActionMap().put("X", reset);
    }

  • 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

  • Hidden dialog renders applet unusable

    i have a problem with dialogs in my applet.
    if an applet dialog is open, and the user minimizes the browser or switches to another application, the dialog gets pemanently hidden (at least in firefox). there's no way to locate the applet again, and hence, no way for the applet to regain focus.
    clicking around on the applet generates a system beep but does not cause the dialog to reappear.
    one obvious approach is to eliminate dialogs. i need the dialogs, though, and want to ask the community if better alternatives exist.
    any ideas? does anyone else have this problem?
    thanks!

    i figured how to make the applet modal with both the Microsoft JVM and the SUN JVM. from reading posts elsewhere on the web, it seems like people have also had trouble with making dialogs modal with the Microsoft JVM. this solution also makes it possible for someone to switch applications while a modal dialog is open without causing the applet to be unusable. when the user switches back to the browser/applet, the blocking dialog is on top of all windows versus being hidden as it would normally.
    ==================
    BEGIN CODE
    ==================
    public NonblockingDialog (Frame parent, String title) {
              super(parent, title, true);
    addWindowListener(new WindowAdapter() {
                   public void windowDeactivated (WindowEvent we) {
                        requestFocus();
                        toFront();
    ==================
    END CODE
    ==================

  • Firefox won't maximise from taskbar and beeps, takes up to 20 times to actually reopen, anyone help?

    When I have a window minimized to taskbar, when I click the taskbar to maximise it, I get a beep and nothing happens, the only way I can open it is it click between 3 and 20 times with right click and restore, but for the many times inbetween it finally opening I get the beep and nothing happens, its quite annoying lol
    == This happened ==
    Every time Firefox opened
    == Everytime I minimize to taskbar

    Firefox often doesn't close properly if I have been using the Blackboard 'virtual learning environment'. Task Manager always reveals that the Firefox process is still running and Java as well. Killing Java allows Firefox to close. Is there a more elegant way of ensuring that Java isn't going to block Fx from closing, e.g. because an applet is invisibly waiting for something? It would be good to have a way of pre-emptively 'clearing' Java before closing Firefox. (Gryllida's solution of disabling Java altogether isn't suitable, because Blackboard and many other sites need it.) Thanks.
    I run Firefox 4.0.1 on various machines with different OSs: Win XP Pro x64, Win 7 Pro x64 and Win XP Pro x32. All behave the same in this respect.
    David

  • Updating Applet Screen while in actionPerformed

    I'm trying to indicate, on my main applet, that the code is busy.
    In my sample applet, I have a label, with an icon, and a button.
    When I click the button, I spit out a "beep".
    I would like to change the icon before I beep, then change it back after I beep.
    in my "actionPerformed" linked to my button, I have a reference to the label, so I simply...
    ����label.setIcon("blah.gif");
    ����label.repaint(); // doesn't work
    ����label.getParent().repaint(); // doesn't work either
    ����for (int i=0; i<10; i++) {
    ��������ToolKit.getDefaultToolkit.beep();
    ����}
    ����label.setIcon("yadda.gif");
    ����label.repaint(); // still doesn't work
    ����label.getParent().repaint(); // still doesn't work
    Now, when the method returns, my icon DOES get set back to "yadda.gif", but it isn't visible while in the actionPerformed() method.
    I know this because I threw in a pause, and after the 2 second pause, the icon changed back.
    What am I doing wrong?
    How do applications indicate the "system" is busy? Wouldn't you typically change the cursor to an hourglass when you start the event, and change it back at the end of the event?
    Thanks in advance,
    Don Brown

    That worked perfectly. I should have checked the class documentation for JComponent. Sorry about wasting your time.
    I'm getting better at RTFM.
    Thanks

  • Beeper - loopable sound using Clip.

    // <applet code='Beeper' width='300' height='300'></applet>
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.text.DecimalFormat;
    import javax.sound.sampled.*;
    import java.io.ByteArrayInputStream;
    /** Beeper presents a small, loopable tone that can be heard
    by clicking on the Code Key.  It uses a Clip to loop the sound,
    as well as for access to the Clip's gain control.
    @author Andrew Thompson
    @version 2009-12-19
    @license LGPL */
    public class Beeper extends JApplet {
    public void init() {
      getContentPane().add(new BeeperPanel());
      validate();
    public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
       public void run() {
        JFrame f = new JFrame("Beeper");
        f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        BeeperPanel BeeperPanel = new BeeperPanel();
        f.setContentPane(BeeperPanel);
        f.pack();
        f.setMinimumSize( new Dimension(300,300) );
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    /** The main UI of Beeper. */
    class BeeperPanel extends JPanel {
    JComboBox sampleRate;
    JSlider framesPerWavelength;
    JLabel frequency;
    JCheckBox harmonic;
    Clip clip;
    DecimalFormat decimalFormat = new DecimalFormat("###00.00");
    BeeperPanel() {
      super(new BorderLayout());
      JPanel options = new JPanel();
      BoxLayout bl = new BoxLayout(options,BoxLayout.Y_AXIS);
      options.setLayout(bl);
      Integer[] rates = {
       new Integer(8000),
       new Integer(11025),
       new Integer(16000),
       new Integer(22050)
      sampleRate = new JComboBox(rates);
      sampleRate.setToolTipText("Samples per second");
      sampleRate.setSelectedIndex(1);
      JPanel pSampleRate = new JPanel(new BorderLayout());
      pSampleRate.setBorder(new TitledBorder("Sample Rate"));
      pSampleRate.add( sampleRate );
      sampleRate.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent ae) {
        setUpSound();
      options.add( pSampleRate );
      framesPerWavelength = new JSlider(JSlider.HORIZONTAL,10,200,25);
      framesPerWavelength.setPaintTicks(true);
      framesPerWavelength.setMajorTickSpacing(10);
      framesPerWavelength.setMinorTickSpacing(5);
      framesPerWavelength.setToolTipText("Frames per Wavelength");
      framesPerWavelength.addChangeListener( new ChangeListener(){
       public void stateChanged(ChangeEvent ce) {
        setUpSound();
      JPanel pFPW = new JPanel( new BorderLayout() );
      pFPW.setBorder(new TitledBorder("Frames per Wavelength"));
      pFPW.add( framesPerWavelength );
      options.add( pFPW );
      JPanel bottomOption = new JPanel( new BorderLayout(4,4) );
      harmonic = new JCheckBox("Add Harmonic", false);
      harmonic.setToolTipText(
       "Add harmonic to second channel, one octave up");
      harmonic.addActionListener( new ActionListener(){
       public void actionPerformed(ActionEvent ae) {
        setUpSound();
      bottomOption.add( harmonic, BorderLayout.WEST );
      frequency = new JLabel();
      bottomOption.add( frequency, BorderLayout.CENTER );
      options.add(bottomOption);
      add( options, BorderLayout.NORTH );
      JPanel play = new JPanel(new BorderLayout(3,3));
      play.setBorder( new EmptyBorder(4,4,4,4) );
      JButton bPlay  = new JButton("Code Key");
      bPlay.setToolTipText("Click to make tone!");
      Dimension preferredSize = bPlay.getPreferredSize();
      bPlay.setPreferredSize( new Dimension(
       (int)preferredSize.getWidth(),
       (int)preferredSize.getHeight()*3) );
      // TODO comment out to try KeyListener!
      bPlay.setFocusable(false);
      bPlay.addMouseListener( new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent me) {
         loopSound(true);
        @Override
        public void mouseReleased(MouseEvent me) {
         loopSound(false);
      play.add( bPlay );
      try {
       clip = AudioSystem.getClip();
       final FloatControl control = (FloatControl)
        clip.getControl( FloatControl.Type.MASTER_GAIN );
       final JSlider volume = new JSlider(
        JSlider.VERTICAL,
        (int)control.getMinimum(),
        (int)control.getMaximum(),
        (int)control.getValue()
       volume.setToolTipText("Volume of beep");
       volume.addChangeListener( new ChangeListener(){
        public void stateChanged(ChangeEvent ce) {
         control.setValue( volume.getValue() );
       play.add( volume, BorderLayout.EAST );
      } catch(Exception e) {
       e.printStackTrace();
      add(play, BorderLayout.CENTER);
      setUpSound();
    /** Sets label to current frequency settings. */
    public void setFrequencyLabel() {
      float freq = getFrequency();
      if (harmonic.isSelected()) {
       frequency.setText(
        decimalFormat.format(freq) +
        "(/" +
        decimalFormat.format(freq*2f) +
        ") Hz" );
      } else {
       frequency.setText( decimalFormat.format(freq) + " Hz" );
    /** Generate the tone and inform the user of settings. */
    public void setUpSound() {
      try {
       generateTone();
       setFrequencyLabel();
      } catch(Exception e) {
       e.printStackTrace();
    /** Provides the frequency at current settings for
    sample rate & frames per wavelength. */
    public float getFrequency() {
      Integer sR = (Integer)sampleRate.getSelectedItem();
      int intST = sR.intValue();
      int intFPW = framesPerWavelength.getValue();
      return (float)intST/(float)intFPW;
    /** Loops the current Clip until a commence false is passed. */
    public void loopSound(boolean commence) {
      if ( commence ) {
       clip.setFramePosition(0);
       clip.loop( Clip.LOOP_CONTINUOUSLY );
      } else {
       clip.stop();
    /** Generates a tone, and assigns it to the Clip. */
    public void generateTone()
      throws LineUnavailableException {
      if ( clip!=null ) {
       clip.stop();
       clip.close();
      } else {
       clip = AudioSystem.getClip();
      boolean addHarmonic = harmonic.isSelected();
      int intSR = ((Integer)sampleRate.getSelectedItem()).intValue();
      int intFPW = framesPerWavelength.getValue();
      float sampleRate = (float)intSR;
      // oddly, the sound does not loop well for less than
      // around 5 or so, wavelengths
      int wavelengths = 20;
      byte[] buf = new byte[2*intFPW*wavelengths];
      AudioFormat af = new AudioFormat(
       sampleRate,
       8,  // sample size in bits
       2,  // channels
       true,  // signed
       false  // bigendian
      int maxVol = 127;
      for(int i=0; i<intFPW*wavelengths; i++){
       double angle = ((float)(i*2)/((float)intFPW))*(Math.PI);
       buf[i*2]=getByteValue(angle);
       if(addHarmonic) {
        buf[(i*2)+1]=getByteValue(2*angle);
       } else {
        buf[(i*2)+1] = buf[i*2];
      try {
       byte[] b = buf;
       AudioInputStream ais = new AudioInputStream(
        new ByteArrayInputStream(b),
        af,
        buf.length/2 );
       clip.open( ais );
      } catch(Exception e) {
       e.printStackTrace();
    /** Provides the byte value for this point in the sinusoidal wave. */
    private static byte getByteValue(double angle) {
      int maxVol = 127;
      return (new Integer(
       (int)Math.round(
       Math.sin(angle)*maxVol))).
       byteValue();
    }

    This code was written (rather belatedly) in response to a question in [Example: Code to generate audio tone|http://forums.sun.com/thread.jspa?threadID=5243872]. Due to it's age, it has been locked.
    The replier wanted to know how to use JavaSound for a Morse code key. Actually now I think about it, the sound loops nicely, but it still demonstrates a slight click at start and stop. I tried using Clip.loop(0) to stop the sound, but that did not avoid the 'click'! I suppose you would need to do as the person was musing, and adjust the GAIN of the Clip up and down.
    In any case - questions.
    - Can anyone make this work for key presses? The first thing you'd need to do is a find on "TODO" and comment out the line that ensures the Code Key is not focusable (and then add a KeyListener(1)). The problem I encountered was that the KeyEvents were getting fired continuously, which caused the sound to 'stutter'. A Timer to ignore quickly repeated keys might work (though I could not make it work for me), but then that would introduce a lag between when whe key was released, and when the sound stopped. It would need to be a very short delay, to use it much in the way the mouse click currently works.
    - Any ideas on improvements to the basic code? (1) (I will be adding the ability to configure the parameters of the applet - more code lines. Possibly also converting the GAIN control from the mostly useless logarithmic ..whatever scale it uses, to linear.)
    1) Note that I had to use single spaces to indent - everything else blew the posting limit(2).
    2) Hence also, questions on 2nd post. ;)
    To compile and run as an applet/application (in a recent SDK).
    javac Beeper.java
    appletviewer Beeper.java
    java BeeperEdit 1:
    Latest source can be found at [http://pscode.org/test/eg/Beeper.java]. See also the [formatted version|http://pscode.org/fmt/sbx.html?url=%2Ftest%2Feg%2FBeeper.java&col=2&fnt=2&tab=2&ln=0].
    Edited by: AndrewThompson64 on Dec 19, 2009 1:50 PM

  • Browsers and applet

    Hi,
    I wrote a small applet that open a udp socket and listen to it, when some packet it's received a button it's enabled. I use netscape 6.2.3 and java VM 1.3.1_02 on Linux 2.4.18, but the buttom have a strange behaviour, in some pc's with the same configuration the button it's enabled but no action seem be taken except for a ugly beep. The java console of the browser show me no error, it seem locked, and his bottons have the same behaviour of my applet botton. I've also try with the new version of netscape 7.1 and java VM but the problem still remain.
    Can someone help me?
    Thanks a lot
    p.s.
    if someone 'd test my code I can send it

    Hi Will,
    I'll send you my code to your e-mail address on yahoo.
    Thanks
    M

  • Problem with threads within applet

    Hello,
    I got an applet, inside this applet I have a singleton, inside this singleton I have a thread.
    this thread is running in endless loop.
    he is doing something and go to sleep on and on.
    the problem is,
    when I refresh my IE6 browser I see more than 1 thread.
    for debug matter, I did the following things:
    inside the thread, sysout every time he goes to sleep.
    sysout in the singleton constructor.
    sysout in the singleton destructor.
    the output goes like this:
    when refresh the page, the singleton constructor loading but not every refresh, sometimes I see the constructor output and sometimes I dont.
    The thread inside the singleton is giving me the same output, sometime I see more than one thread at a time and sometimes I dont.
    The destructor never works (no output there).
    I don't understand what is going on.
    someone can please shed some light?
    thanks.
    btw. I am working with JRE 1.1
    this is very old and big applet and I can't convert it to something new.

    Ooops. sorry!
    I did.
         public void start() {
         public void stop() {
         public void destroy() {
              try {
                   resetAll();
                   Configuration.closeConnection();
                   QuoteItem.closeConnection();
              } finally {
                   try {
                        super.finalize();
                   } catch (Throwable e) {
                        e.printStackTrace();
         }

Maybe you are looking for

  • My mail app wont open so that i can view it but it wont let me 'quit' either so I cant just do a restart to do updates and troubleshoot?

    my mail app wont open so that i can view it but it wont let me 'quit' either so I cant just do a restart to do updates and troubleshoot?

  • FOR loop in console

    Hello guys! As you know, i'm new to VB. For my next challenge, i would like to create a program that goes through the numbers 1 to 100, and if they are divisible by 5, print them as well as the running total. If they can't be divided, then they're st

  • One Month Free Phone Calls.

    I have applied for free phone calls and have received confirmation that I have a free one month subscription. However when I dial a number it is rejected and I am requested to first pay a suscription . Why? My Skype name is warwick.krige.

  • Flash CS5 will not import mp3 files

    With the latest Flash program and the latest Quicktime version, I still can not import mp3 files to my Flash. No reason is given, it only tells me it can't be done. elliejo

  • Hi i want a help activating my iphone

    hi i have an iphone 4s serial number: C2******TD1 IMEI: ****** ios version : 7.1.1 I bought it second-hand and i can't activate it and i can't even reach the previous owner please help me please <Edited by Host>