AWT + Positon On Queue

Greetings,
I would like to share this script modified by me. My need was create a script where is displayed the position on queue and the average time waiting (AWT) if the person stay on queue. I found the AWT in a old post here (shared by another collaborator) in CSC and I added the position on queue.
It work fine. please if you have a suggestion to improve, let me know.
Some terms are in portuguese, but is easy to interpret.
Regards.

Hello Sam,
Your questions could be answered by the following documents:
http://java.sun.com/j2se/1.3/docs/guide/awt/designspec/events.html
http://download.java.net/jdk6/docs/api/java/awt/doc-files/AWTThreadIssues.html
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/doc-files/FocusSpec.html
Cheers,
Sam

Similar Messages

  • AWT System Event Queue

    Hello all,
    I'm interested in how the AWT system event queue works. I'm talking about the EventQueue we can all retrieve using Toolkit.getDefaultToolkit().getSystemEventQueue().
    My main questions are:
    1) What happens to events once they get on the queue?
    2) How do the AWT Components get notified of the events?
    3) How is the correct AWT Component to notify determined?
    I've done a little bit of Googling but haven't found anything explaining how the event queue actually works.
    In case you're wondering, I'd like to know all this because I'm in a position where I need to mimick the system event queue's behaviour without actually touching it.
    Any links to further reading, suggestions or comments are most welcome.
    Thanks in advance,
    Sam

    Hello Sam,
    Your questions could be answered by the following documents:
    http://java.sun.com/j2se/1.3/docs/guide/awt/designspec/events.html
    http://download.java.net/jdk6/docs/api/java/awt/doc-files/AWTThreadIssues.html
    http://java.sun.com/j2se/1.4.2/docs/api/java/awt/doc-files/FocusSpec.html
    Cheers,
    Sam

  • Help with game

    hi, im trying to make my first complex program involving applets, which is to be some take on pong. What ive been doing so far is messing with different types of input and movement in a test program called "RectRun"
    i decided that im going to use the mouse wheel as the input for the moving of the paddle up and down. what im attempting to do is have the paddle "drift" almost as if it is moving on ice, which i have accomplished, but the problem is that further input from the mouse wheel will not be executed until the loop that makes it drift has completed (i hope that makes sense). so basically what i need to do is break out of the loop when a new input is received from the mouse wheel being turned, but i dont know how to tell when a new input is recieved. here is my code for RectRun so you can run it yourselves and see how the rectangle behaves because it is hard to describe :p
    import java.awt.Graphics;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.MouseWheelEvent;
    import java.awt.event.MouseWheelListener;
    import java.applet.*;
    public class RectApp extends Applet implements MouseWheelListener
         private int x, y, prevy, pause, changeFactor;
         public final int WIDTH = 10, HEIGHT = 45;
         Graphics g;
        public void init()
            x = 10;
            y = 50;
            prevy = 0;
            changeFactor = 0;
            wait = new Thread();
            wait.start();
            addMouseWheelListener(this);
            setBackground(Color.BLACK);
            g = getGraphics();
         public void mouseWheelMoved(MouseWheelEvent e)
             int notches = e.getWheelRotation();
             if(notches < 0)
                  for(pause = 0; pause < 100; pause += 10)
                            try{ wait.sleep(pause);} catch( InterruptedException i ){}
                            prevy = y;
                            y -= 3;
                            paint(g);
             else
                  for(pause = 0; pause < 100; pause += 10)
                            try{ wait.sleep(pause);} catch( InterruptedException i ){}
                            prevy = y;
                            y += 3;
                            paint(g);
        public void paint(Graphics g)
            g.setColor(Color.GREEN);
            g.clearRect(x,prevy,WIDTH+1,HEIGHT+1);
             g.drawRect(x,y,WIDTH, HEIGHT);
             g.drawRect(0,0,499,299);
                g.drawRect(1,1,497,297);
                g.drawLine(250,0,250,300);
           public boolean isFocusTraversable() {return true;}
    }Edited by: adg12012 on May 8, 2008 1:20 PM

    adg12012 wrote:
    the reason i had to do the paint(g) as opposed to repaint is because inside the loop, repaint() wouldn't execute.[http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Component.html#repaint()]
    As this documentation states, repaint() simply tries to call paint() at the next possible opportunity. I believe this comes in adding an event to AWT's event queue to trigger the repaint.
    The trouble is, you are looping on the same thread as the event queue processing thread. Which means, the thread will only get back to processing events after your time-intensive loop has finished. In other words, the repaint event can't be processed until you give control back to the event queue processor, i.e. finish your actionListener code.
    If you ever want to do time-intensive operations in a GUI application, you pretty much always want to do them on a separate thread, or your GUI will not respond until the operation is complete. Take, for example, Windows' File Explorer window. You know how frustrating it is when you click on a Network share, or a Floppy drive, when the destination doesn't exist? How the window freezes for like 2 minutes trying to establish the connection? That's because that particular application tries to find the target (a time-intensive operation) on the same thread that is driving the GUI.

  • "DEADLOCK" when showing dialog from RMI-callback.

    Hi!
    Today is the 10th day (full time) that I've been searching for a solution in Java Forums and Internet, but I couldn't find anything that helps me. Help is extremely appreciated, otherwise I'll go crazy! :-)
    The problem is that RMI-callback thread "somehow blocks" the Event Dispatch Thread.
    I want to do following:
    1) I push the button in the client (btDoSomething)
    (MOUSE_RELEASED,(39,14),button=1,modifiers=Button1,clickCount=1 is automatically pushed onto EventQueue)
    2) btDoSomethingActionPerformed is invoked
    3) inside of it I make a call to RMI-server (server.doSomething())
    4) from this server method I invoke RMI-callback back to the client (client.askUser())
    5) in the callback I want to display a question to the user (JOptionPane.showConfirmDialog)
    6) user should answers the question
    7) callback returns to server
    8) client call to the server returns
    9) btDoSomethingActionPerformed returns and everybody is happy :-)
    This works normally in normal Client, that means, while a button is pushed, you can show Dialogs, but with RMI callback I get problems.
    I just made a small client-server sample to simulate real project. What I want to achieve is that client invokes server method, server method does something, but if server method doesn't have enough information to make the decision it needs to do call back to the client and wait for input, so the user gets an JOptionPane.
    Here is my callback method:
        /** this is the remote callback method, which is invoked from the sevrer */
        public synchronized String askUser() throws java.rmi.RemoteException {
            System.out.println("askUser() thread group: " + Thread.currentThread().getThreadGroup());
            System.out.println("callback started...");
            try {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        System.out.println("My event started...");
                        JOptionPane.showConfirmDialog(parentFrame, "Are you OK?", "Question", JOptionPane.YES_NO_OPTION);
                        System.out.println("My event finished.");
            }catch (Exception e) {
                e.printStackTrace();
            try {
                Thread.currentThread().sleep(10000);
            }catch (Exception e) {
                e.printStackTrace();
            System.out.println("callback finished.");
            return "Yo!"; // just return anything
        }Here in this sample I let the callback thread sleep for 10 seconds, but in real project I let it sleep infinitely and I want to wake it up after the user has answered JOptionPane. But I have the DEADLOCK, because event queue is waiting for callback to finish and doesn't schedule the "showing dialog" event which contains the command for waking up the callback thread.
    I looked very precisely when the event queue starts again to process events: it is precisely then when btDoSomethingActionPerformed is finished.
    When I'm not accessing GUI inside of the callback, this callback mechanism works perfectly, but as soon as I want to show the dialog from inside of the RMI-callback method, the "AWT Event Dispatch Queue" is somehow frozen until RMI-callback thread is finished (and in turn btDoSomethingActionPerformed terminates) . I cannot explain this weird behaviour!!!
    If I don't use SwingUtilities.invokeLater (I know this shoudn't be done outside of Event Dispatch Thread), but access the GUI directy, my JOptionPane is shown, but is not painted (it is blank gray) until callback thread returns.
    Why showing (or painting) of dialog is not done until btDoSomethingActionPerformed is finished?
    I also tried to spawn a new Thread inside of main RMI-callback thread, but nothing changed.
    I also tried the workaround from some older posting to use myInvokeLater:
        private final static ThreadGroup _applicationThreadGroup = Thread.currentThread().getThreadGroup();
        public void myInvokeLater(final Runnable code) {
            (new Thread(_applicationThreadGroup, new Runnable() {
                public void run() { SwingUtilities.invokeLater(code); }
            ).start();
        }but this didn't help either.
    Then I tried to spawn a new Thread directly from the Client's constructor, so that I'm sure that it belongs to the main appplication thread group. I even started that thread there in the constructor and made it wait for the callback. When callback came in, it would wake up that sleeping thread which should then show the dialog. But this did't help either.
    Now I think that it is IMPOSSIBLE to solve this problem this way.
    Spawning a new Process could work I think, but I'm not really sure if I want do to that.
    I know I could make a solution where server method is invoked and if some information is missing I can raise custom exception, provide the input on client side and call the same server mathod again with this additional data, but for that I need to change server RMI interfaces, etc... to fit in this concept. I thought callback would much easier, but after almost 10 days of trying the callback...I almost regreted it :-(
    Is anyone able to help?
    Thank you very much!
    Please scroll down for the complete sample (with build and run batch files), in case someone wants to try it. Or for the time being for your convenience you can download the whole sample from
    http://www.onlineloop.com/~tornado/download/rmi_callback_blocks_gui.zip
    ######### BEGIN CODE ####################################
    package callbackdialog;
    public interface ICallback extends java.rmi.Remote {
        public String askUser() throws java.rmi.RemoteException;
    package callbackdialog;
    public interface IServer extends java.rmi.Remote {
        public void doSomething() throws java.rmi.RemoteException;
    package callbackdialog;
    import java.rmi.Naming;
    public class Server {
        public Server() {
            try {
                IServer s = new ServerImpl();
                Naming.rebind("rmi://localhost:1099/ServerService", s);
            } catch (Exception e) {
                System.out.println("Trouble: " + e);
        public static void main(String args[]) {
            new Server();
    package callbackdialog;
    import java.rmi.Naming;
    public class ServerImpl extends java.rmi.server.UnicastRemoteObject implements IServer {
        // Implementations must have an explicit constructor
        // in order to declare the RemoteException exception
        public ServerImpl() throws java.rmi.RemoteException {
            super();
        public void doSomething() throws java.rmi.RemoteException {
            System.out.println("doSomething started...");
            try {
                // ask the client for the "missing" value via RMI callback
                ICallback client = (ICallback)Naming.lookup("rmi://localhost/ICallback");
                String clientValue = client.askUser();
                System.out.println("Got value from callback: " + clientValue);
            }catch (Exception e) {
                e.printStackTrace();
            System.out.println("doSomething finished.");
    package callbackdialog;
    import java.rmi.server.RemoteStub;
    import java.rmi.server.UnicastRemoteObject;
    import java.rmi.registry.Registry;
    import java.rmi.registry.LocateRegistry;
    import java.rmi.Naming;
    import javax.swing.JOptionPane;
    import javax.swing.SwingUtilities;
    import javax.swing.JFrame;
    public class Client extends javax.swing.JFrame implements ICallback {
        private final JFrame parentFrame = this;
        private Registry mRegistry = null;
        private RemoteStub remoteStub = null;
        private IServer server = null;
        private final static ThreadGroup _applicationThreadGroup = Thread.currentThread().getThreadGroup();
        /** Creates new form Client */
        public Client() {
            initComponents();
            System.out.println("Client constructor thread group: " + Thread.currentThread().getThreadGroup());
            try {
                server = (IServer)Naming.lookup("rmi://localhost/ServerService");
                // register client to the registry, so the server can invoke callback on it
                mRegistry = LocateRegistry.getRegistry("localhost", 1099);
                remoteStub = (RemoteStub)UnicastRemoteObject.exportObject((ICallback)this);
                Registry mRegistry = LocateRegistry.getRegistry("localhost", 1099);
                mRegistry.bind("ICallback", remoteStub);
            }catch (java.rmi.AlreadyBoundException e) {
                try {
                    mRegistry.unbind("ICallback");
                    mRegistry.bind("ICallback", remoteStub);
                }catch (Exception ex) {
                    // ignore it
            }catch (Exception e) {
                e.printStackTrace();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            java.awt.GridBagConstraints gridBagConstraints;
            secondTestPanel = new javax.swing.JPanel();
            btDoSomething = new javax.swing.JButton();
            getContentPane().setLayout(new java.awt.GridBagLayout());
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            setTitle("RMI-Callback-GUI-problem sample");
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    formWindowClosing(evt);
            secondTestPanel.setLayout(new java.awt.GridBagLayout());
            btDoSomething.setText("show dialog");
            btDoSomething.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btDoSomethingActionPerformed(evt);
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 0;
            gridBagConstraints.gridy = 3;
            gridBagConstraints.insets = new java.awt.Insets(10, 0, 0, 0);
            secondTestPanel.add(btDoSomething, gridBagConstraints);
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 0;
            gridBagConstraints.gridy = 1;
            gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
            gridBagConstraints.weightx = 1.0;
            gridBagConstraints.weighty = 1.0;
            getContentPane().add(secondTestPanel, gridBagConstraints);
            pack();
        private void btDoSomethingActionPerformed(java.awt.event.ActionEvent evt) {                                             
            System.out.println(java.awt.EventQueue.getCurrentEvent().paramString());
            try {
                server.doSomething(); // invoke server RMI method, which will do the client RMI-Callback
                                      // in order to show the dialog
            }catch (Exception e) {
                e.printStackTrace();
        private void formWindowClosing(java.awt.event.WindowEvent evt) {                                  
            try {
                mRegistry.unbind("ICallback");
            }catch (Exception e) {
                e.printStackTrace();
            setVisible(false);
            dispose();
            System.exit(0);
        /** this is the remote callback method, which is invoked from the sevrer */
        public synchronized String askUser() throws java.rmi.RemoteException {
            System.out.println("askUser() thread group: " + Thread.currentThread().getThreadGroup());
            System.out.println("callback started...");
            try {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        System.out.println("My event started...");
                        JOptionPane.showConfirmDialog(parentFrame, "Are you OK?", "Question", JOptionPane.YES_NO_OPTION);
                        System.out.println("My event finished.");
            }catch (Exception e) {
                e.printStackTrace();
            try {
                Thread.currentThread().sleep(10000);
            }catch (Exception e) {
                e.printStackTrace();
            System.out.println("callback finished.");
            return "Yo!"; // just return anything
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    Client client = new Client();
                    client.setSize(500,300);
                    client.setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JButton btDoSomething;
        private javax.swing.JPanel secondTestPanel;
        // End of variables declaration
    1_build.bat
    javac -cp . -d . *.java
    rmic callbackdialog.ServerImpl
    rmic callbackdialog.Client
    pause
    2_RunRmiRegistry.bat
    rmiregistry
    pause
    3_RunServer.bat
    rem java -classpath .\ Server
    java callbackdialog.Server
    pause
    4_RunClient.bat
    java callbackdialog.Client
    pause
    ######### END CODE ####################################

    I can understand that only partially, because SwingUtilities.invokeLater puts(redirects) my runnable object directly into AWT thread. The only conclusion I can draw from all things that I have tried until now , is that SwingUtilities.invokeLater(<showing the dialog>) invoked from a RMI thread somehow have lower "priority" than events coming directly from the AWT-thread and therefore it is held back until normal awt event completes (in this case BUTTON_RELEASED).
    But what I don't understand is the fact that the dialog is not shown even If I create and start a new thread from the client's constructor. This thread has nothing to do with RMI as it is in the main thread group:
        private BlockingObject dialogBlocker = new BlockingObject();
        private BlockingObject blocker = new BlockingObject();
        public Client() {
            initComponents();
            (new Thread() {
                public void run() {
                    try {
                        dialogBlocker.sleep(0);
                        System.out.println("My event started...");
                        JOptionPane.showConfirmDialog(parentFrame, "Are you OK?", "Question", JOptionPane.YES_NO_OPTION);
                        blocker.wake();
                        System.out.println("My event finished.");
                    }catch (Exception e) {
                        e.printStackTrace();
            }).start();
            ...Callback is then only used to wake up this thread which should display the dialog:
        public Object askUser() throws java.rmi.RemoteException {
            System.out.println("callback started...");
            dialogBlocker.wake();
            blocker.sleep(0);
            System.out.println("callback finished.");
            return userChoice; // return anything I don't care for now
    class BlockingObject {
        public void sleep(long timeout) {
            synchronized(this){
                try {
                    wait(timeout);
                }catch (InterruptedException e) {}
        public void wake() {
            synchronized(this){
                notifyAll();
        }In this case the dialog is shown, but it is NOT painted, so I have deadlock again. Why it is not painted?!?
    Haven't I uncouple it from RMI-Thread?
    But perhaps I'm looking at the wrong side of the whole thing.
    If I invoke server.doSomething (as ejp proposed) in a separate thread, then everything is fine (except that I cannot use this solution in my project :-( ).
    It seems that the whole problem is NOT AT ALL related to callback itself, but rather to the fact that if client invokes remote call, even dialogs can't be shown until the rmi call returns to the client.
    Thank you, Drindilica

  • Creating a gridlayout of jlabels and jbuttons in a JPanel

    The assignment:
    "Create a JPanel that contains an 8x8 checkerboard. Make all of the red squares JButtons and be sure to add them to the JPanel. Make all of the black squares JLabels and add them to the JPanel. Don't forget, you must use the add method to attach the JPanel to the JApplet's contentPane but that there is no contentPane for a JPanel. Be sure to set up any interfaces to handle the JButtons. Use a GridLayout to position and size each of the components instead of absolute locations and sizes."
    This assignment introduces the JPanel to me for the first time, I have not seen what the JDialog and JFrame are.
    What I have:
    import java.awt.*;
    import javax.swing.*;
    * Class CheckerBoard - write a description of the class here
    * @author (your name)
    * @version (a version number)
    public class CheckerBoard extends JPanel
        JButton redSquare;
        JLabel blackSquare;
         * Called by the browser or applet viewer to inform this JApplet that it
         * has been loaded into the system. It is always called before the first
         * time that the start method is called.
        public void init()
            JPanel p = new JPanel();
            setLayout(new GridLayout(8,8));
            setSize(512,512);
            ImageIcon red = new ImageIcon("GUI-006-RedButton.png");
            ImageIcon black = new ImageIcon("GUI-006-BlackSquare.png");
            blackSquare = new JLabel(black);
            blackSquare.setSize(64,64);
            redSquare = new JButton(red);
            redSquare.setSize(64,64);
            for (int i = 0; i < 64; i++) {
                if ((i % 2) == 1)
                    add(blackSquare);
                else
                   add(redSquare);
            // this is a workaround for a security conflict with some browsers
            // including some versions of Netscape & Internet Explorer which do
            // not allow access to the AWT system event queue which JApplets do
            // on startup to check access. May not be necessary with your browser.
            JRootPane rootPane = this.getRootPane();   
            rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
    }After successfully compiling it when I try to run it there appears to be nothing to run. I've tried messing around with content panes but I'm not sure if I need to add one for this assignment at all.

    Some suggestions:
    1) First and foremost, read about JPanels, JApplets, and JFrames. None of the help you can get here will substitute for your applying yourself towards this, absolutely none, and judging by your code, you have your work cut out for you.
    2) Don't have your JPanel initialize with an init method, that's what Applets and JApplets do. Instead have it initialize with a proper constructor.
    3) I'm wondering if your "workaround" code belongs in the JApplet that contains the JPanel and not in the JPanel. It has nothing to do with the JPanel's mission. For instance, what if you later decide to place this panel into a JFrame?
    4) Avoid "setSize", and if at all possible, use "setPreferredSize" instead. You are working with LayoutManagers who do the size setting. You are best served by suggesting the size to them.
    5) Please ask specific questions. Just dumping your code without a question is considered quite rude here. We are all volunteers. If you want our free advice, you really should be considerate enough to make it easy for us to help you.
    Good luck.
    Edited by: Encephalopathic on Dec 21, 2007 6:14 PM

  • IWeb consistantly crashes?

    I'm not sure what it is as of late but I can't even seem to work in iWeb anymore because of errors that force a crash before I can even start working.
    I'm using the latest version 3.0.4 or something like that and even tried to patch it as a fix but nothing.
    Any suggestions?

    Process:    
    iWeb [1068]
    Path:       
    /Applications/iWeb.app/Contents/MacOS/iWeb
    Identifier: 
    com.apple.iWeb
    Version:    
    3.0.4 (304)
    Build Info: 
    iWeb-6010000~1
    Code Type:  
    X86 (Native)
    Parent Process:  launchd [94]
    Date/Time:  
    2012-01-11 14:46:55.778 -0500
    OS Version: 
    Mac OS X 10.6.8 (10K549)
    Report Version:  6
    Sleep/Wake UUID: DCA663DD-E4A3-4C86-AF25-1524F6EBFD21
    Interval Since Last Report:     
    145850 sec
    Crashes Since Last Report:      
    11
    Per-App Interval Since Last Report:  3762 sec
    Per-App Crashes Since Last Report:   10
    Anonymous UUID:                 
    82C444C8-4440-4142-9200-B3412734D4C9
    Exception Type:  EXC_BAD_ACCESS (SIGBUS)
    Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000000000020
    Crashed Thread:  0  Java: AWT-AppKit  Dispatch queue: com.apple.main-thread
    Application Specific Information:
    objc_msgSend() selector name: forceRedraw
    Java information:
    Exception type: Bus Error (0xa) at pc=00000000968c9f87
    Java VM: Java HotSpot(TM) Client VM (20.4-b02-402 mixed mode, sharing macosx-x86)
    Current thread (000000001b802000):  JavaThread "AWT-AppKit" [_thread_in_native, id=-1608317632, stack(00000000bf800000,00000000c0000000)]
    Stack: [00000000bf800000,00000000c0000000]
    Java Threads: ( => current thread )
      000000001b893800 JavaThread "JVM[id=1]-Heartbeat" [_thread_blocked, id=-1309396992, stack(00000000b1e43000,00000000b1f43000)]
      000000001b8bb800 JavaThread "AWT-Shutdown" [_thread_blocked, id=-1316794368, stack(00000000b1735000,00000000b1835000)]
      000000001b8ba000 JavaThread "Poller SunPKCS11-Darwin" daemon [_thread_blocked, id=-1317851136, stack(00000000b1633000,00000000b1733000)]
      000000001b88c000 JavaThread "traceMsgQueueThread" daemon [_thread_blocked, id=-1318907904, stack(00000000b1531000,00000000b1631000)]
      000000001b821c00 JavaThread "Low Memory Detector" daemon [_thread_blocked, id=-1326936064, stack(00000000b0d89000,00000000b0e89000)]
      000000001b820c00 JavaThread "C1 CompilerThread0" daemon [_thread_blocked, id=-1327992832, stack(00000000b0c87000,00000000b0d87000)]
      000000001b81fc00 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=-1329049600, stack(00000000b0b85000,00000000b0c85000)]
      000000001b81dc00 JavaThread "Finalizer" daemon [_thread_blocked, id=-1331773440, stack(00000000b08ec000,00000000b09ec000)]
      000000001b81cc00 JavaThread "Reference Handler" daemon [_thread_blocked, id=-1332830208, stack(00000000b07ea000,00000000b08ea000)]
    =>000000001b802000 JavaThread "AWT-AppKit" [_thread_in_native, id=-1608317632, stack(00000000bf800000,00000000c0000000)]
    Other Threads:
      000000001b81c000 VMThread [stack: 00000000b0396000,00000000b0496000] [id=-1337368576]
      000000001b823400 WatcherThread [stack: 00000000b0e8b000,00000000b0f8b000] [id=-1325879296]
    VM state:not at safepoint (normal execution)
    VM Mutex/Monitor currently owned by a thread: None
    Heap
    def new generation   total 4928K, used 3824K [0000000034810000, 0000000034d60000, 0000000035d60000)
      eden space 4416K,  86% used [0000000034810000, 0000000034bcc1b8, 0000000034c60000)
      from space 512K,   0% used [0000000034c60000, 0000000034c60000, 0000000034ce0000)
      to   space 512K,   0% used [0000000034ce0000, 0000000034ce0000, 0000000034d60000)
    tenured generation   total 10944K, used 0K [0000000035d60000, 0000000036810000, 0000000038810000)
       the space 10944K,   0% used [0000000035d60000, 0000000035d60000, 0000000035d60200, 0000000036810000)
    compacting perm gen  total 12288K, used 1363K [0000000038810000, 0000000039410000, 000000003c810000)
       the space 12288K,  11% used [0000000038810000, 0000000038964fc8, 0000000038965000, 0000000039410000)
    ro space 20480K,  50% used [000000003c810000, 000000003d212490, 000000003d212600, 000000003dc10000)
    rw space 20480K,  61% used [000000003dc10000, 000000003e853838, 000000003e853a00, 000000003f010000)
    Code Cache  [000000001c001000, 000000001c09a000, 000000001e001000)
    total_blobs=253 nmethods=92 adapters=105 free_code_cache=32935552 largest_free_block=0
    Virtual Machine Arguments:
    JVM Args: -Xbootclasspath/a:/System/Library/Frameworks/JavaVM.framework/Resources/Deploy. bundle/Contents/Resources/Java/deploy.jar:/System/Library/Frameworks/JavaVM.fram ework/Resources/Deploy.bundle/Contents/Resources/Java/javaws.jar:/System/Library /Frameworks/JavaVM.framework/Resources/Deploy.bundle/Contents/Resources/Java/plu gin.jar -Xmx64m -Djava.awt.headless=true -XX:+UseSerialGC -XX:MaxDirectMemorySize=64m
    Java Command: <unknown>
    Launcher Type: generic
    Physical Memory: Page Size = 4k, Total = 3840M, Free = 17592186042646M

  • One Master Class Or Lots Of Dumb Classes

    Developers,
    I want to go about the best way to design a generic system. Lets say the app is a simple chart axis. You have 3 classes - ticks, labels and a axis.
    My question to you is theres a few ways to go about doing this.
    1) Draw all the ticks
    2) Draw the labels
    Finish.
    /*Second Approach*/
    1) Draw the tick then the label and repeat for all.
    What really pissed me off was this:
    Is it better to have lots of dumb classes and one clever class doing all the work to support RESUABILITY. For example should a label know where to draw or should it expect its coordinate system to have been set by its caller. Or should the label know its position on the page and therefore not rely on one class getting bogged down by doing do much.
    Think carefully about this. On the one hand lets say the axis now becomes a bezier path we'll have to reimplement the whole clever axis class - but the dumb classes stay as is. On the other hand it doesnt quite justify a new class to do what a Java Class already class is.
    Think about this as a layout manager. When adding a button to a layout manager, the layout manager does the placing. The button is essentially a dumb class in this case.
    Any help greatly appreciated

    Developers,
    I want to go about the best way to design a generic system. There's isn't a "best" way, and there is no such thing as a generic system.
    The most universal advice you'll hear is to use Model-View-Controller separation. Start with that and see if you can do it effectively in your little charting program. It'll be harder than you think, I'll bet.
    Lets say the app is a simple chart axis. You
    have 3 classes - ticks, labels and a axis.
    My question to you is theres a few ways to go about
    doing this.
    1) Draw all the ticks
    2) Draw the labels
    Finish.
    /*Second Approach*/
    1) Draw the tick then the label and repeat for all.
    What really pissed me off was this:You have a short fuse. Why does this piss you off? Who are you angry with?
    Is it better to have lots of dumb classes and one clever class doing all the work to support
    RESUABILITY. Gotta use it once to be able reuse it. I think the point should be to try to design something that you can use well once before you start worrying about that. You'll rewrite that system three times before you can start to see how to write something generic enough for all three.
    For example should a label know where to
    draw or should it expect its coordinate system to have
    been set by its caller. Or should the label know its
    position on the page and therefore not rely on one
    class getting bogged down by doing do much.
    I think it's more important to design to interfaces and use patterns well.
    Think carefully about this. I always try to think carefully before I answer.
    On the one hand lets say
    the axis now becomes a bezier path we'll have to
    reimplement the whole clever axis class - but the dumb
    classes stay as is. On the other hand it doesnt quite
    justify a new class to do what a Java Class already
    class is.I think the point is that if you design with an axis interface and factory method you'll be able to configure this part of the applicaiton in lots of ways that you didn't anticipate on the first day.
    But perhaps it's best to get your XY plotting package working with rectangular coordinate systems first. After all, I've never seen a curvilinear coordinate system based on Bezier curves or b-splines. However, I have seen those constructs used to approximate and plot data.
    Think about this as a layout manager. When adding a
    button to a layout manager, the layout manager does
    the placing. The button is essentially a dumb class
    in this case.A button isn't "dumb". It's doing what it was designed to do, and does it well. It generates events that are processed by the AWT/Swing event queue. There's a lot going on there that's hidden from you.
    Or maybe not so well-hidden. Go back to javax.swing.JButton and look at all the methods attached to your "dumb" button. There's a lot of design and thought there.
    Any help greatly appreciatedGo back and read some books about design patterns.

  • Newbie question - Drawing objects in applet

    Hi,
    I'm pretty new to java, and I have a small problem involving drawing a rectangle on a java applet.Firstly this is not a plea for someone to help me with this peice of work, I just need pointing in the right direction.
    Ok the problem.
    I am creating a program that ask the user to input a height value, the program will then do a calculation and create a golden ratio width. The type of both the height and the width are double.
    This is where the problem starts. The next thing I need to do is make the program draw the rectangle using the user inputted height and the calculated width.
    I have a feeling that the problem has occured because I haven't converted the type double into a int type.
    Here is my code
    import java.awt.*;
    import javax.swing.*;
    import java.applet.Applet;
    import java.awt.Graphics;
    * Class Test - write a description of the class here
    * @author (your name)
    * @version (a version number)
    public class Test extends JApplet
        // instance variables - replace the example below with your own
       double sum, number1;
       int height;
       int width;
         * Called by the browser or applet viewer to inform this JApplet that it
         * has been loaded into the system. It is always called before the first
         * time that the start method is called.
        public void init()
            String firstNumber;
            double sum1;
            firstNumber = JOptionPane.showInputDialog("Please enter the height" );
            number1 = Double.parseDouble( firstNumber );
            sum1 = (Math.sqrt(5) + 1) / 2;
            sum = number1 * sum1;
            int height = (int)number1;
            int width = (int)sum;
            // this is a workaround for a security conflict with some browsers
            // including some versions of Netscape & Internet Explorer which do
            // not allow access to the AWT system event queue which JApplets do
            // on startup to check access. May not be necessary with your browser.
            JRootPane rootPane = this.getRootPane();   
            rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
            // provide any initialisation necessary for your JApplet
         * Called by the browser or applet viewer to inform this JApplet that it
         * should start its execution. It is called after the init method and
         * each time the JApplet is revisited in a Web page.
        public void start()
            // provide any code requred to run each time
            // web page is visited
         * Called by the browser or applet viewer to inform this JApplet that
         * it should stop its execution. It is called when the Web page that
         * contains this JApplet has been replaced by another page, and also
         * just before the JApplet is to be destroyed.
        public void stop()
            // provide any code that needs to be run when page
            // is replaced by another page or before JApplet is destroyed
         * Paint method for applet.
         * @param  g   the Graphics object for this applet
        public void paint(Graphics g)
            // simple text displayed on applet
            g.drawRect( 15, 10, 270, 20 );
            g.drawString("The sum is " + number1, 25, 25 );
            g.drawRect( 100, 100, height, width);
         * Called by the browser or applet viewer to inform this JApplet that it
         * is being reclaimed and that it should destroy any resources that it
         * has allocated. The stop method will always be called before destroy.
        public void destroy()
            // provide code to be run when JApplet is about to be destroyed.
         * Returns information about this applet.
         * An applet should override this method to return a String containing
         * information about the author, version, and copyright of the JApplet.
         * @return a String representation of information about this JApplet
        public String getAppletInfo()
            // provide information about the applet
            return "Title:   \nAuthor:   \nA simple applet example description. ";
         * Returns parameter information about this JApplet.
         * Returns information about the parameters than are understood by this JApplet.
         * An applet should override this method to return an array of Strings
         * describing these parameters.
         * Each element of the array should be a set of three Strings containing
         * the name, the type, and a description.
         * @return a String[] representation of parameter information about this JApplet
        public String[][] getParameterInfo()
            // provide parameter information about the applet
            String paramInfo[][] = {
                     {"firstParameter",    "1-10",    "description of first parameter"},
                     {"status", "boolean", "description of second parameter"},
                     {"images",   "url",     "description of third parameter"}
            return paramInfo;
    }Thanks for any suggestions.

    Hey ProjectMoon, I had to re-register because it wouldn't let me log back in for some reason.Anyway thanks for the information, i'm trying to get my head around what you said, also I tried printing the height in the drawstring,and as you predicted I got a value of 0. I just wanted to know wjat you mean by:
    "You want to store your height and width in the instance variables you have declared."
    Because I thought I had declared them at the top of the page
    public class Test extends JApplet
        // instance variables - replace the example below with your own
       double sum, number1;
       int height;
       int width;One further question, is the method I used to convert double to int correct?
    int height = (int)number1;
    int width = (int)sum;Thanks again for the time you have spend answering the questions.

  • Creating breakout game. Need help with thread starting.

    Howdy. As the title says, I've got an assignment to make a breakout game. So far it's going alright, but I've run into a rather large snag...I can't get it to animate :P I've got my main applet, then I created a class heirarchy for the paddle, ball, and brick objects. For this question, lets just focus on the ball object.
    This is my applet code so far (it is not even close to being done, so don't laugh :P )
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    * Class BreakoutApplet - Plays a simple game of Breakout.
    * @author Kris Nelson
    * @version November 10, 2004
    public class BreakoutApplet extends JApplet implements Runnable
        protected Brick brick; // creates an object of class brick
        protected Ball ball; // creates an object of class ball
        protected Paddle paddle; // creates an object of class paddle
        protected boolean running; // tells the program whether or not the thread is running
        protected ArrayList brickArray = new ArrayList(); // stores all the bricks in the game
        protected Thread timer; // the thread which controls the animation for the applet
        * Called by the browser or applet viewer to inform this JApplet that it
        * has been loaded into the system. It is always called before the first
        * time that the start method is called.
        public void init()
            // this is a workaround for a security conflict with some browsers
            // including some versions of Netscape & Internet Explorer which do
            // not allow access to the AWT system event queue which JApplets do
            // on startup to check access. May not be necessary with your browser.
            JRootPane rootPane = this.getRootPane();   
            rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
            createBricks(); // creates the games array of bricks
            ball = new Ball(400, 400, 2, 2); // sets the values for the ball
            paddle = new Paddle(300, 660, 2); // sets the values for the paddle
            // !!!!!!! have tried placing ball.start() here
        * Paint method for applet.
        * @param  g   the Graphics object for this applet
        public void paint(Graphics g)
            // draws the background, border, and all the games objects
            g.setColor(Color.lightGray); // sets the drawing color to light gray
            g.fillRect(0, 0, 600, 700); // displays the game screens background
            displayBorder(g); // displays the game screens border
            displayBricks(g); // displays the array of bricks
            ball.display(g); // displays the ball
            paddle.display(g); // displays the paddle
        * Creates the games array of bricks
        public void createBricks()
            int colorNumber = 1; // starts the color of the bricks at orange
            double yPosition = 100; // starts the bricks y screen position at 100
            for(int i = 0; i < 4; i++)
                double xPosition = 12; // starts the bricks x screen position at 12
                for(int j = 0; j < 8; j++)
                    if(colorNumber == 0)
                        colorNumber = 1; // sets the color of the bricks to orange
                    else
                        colorNumber = 0; // sets the color of the bricks to green
                    brickArray.add(brick = new Brick(xPosition, yPosition, colorNumber)); // adds a brick to the current container in the brick array
                    xPosition = xPosition + brick.getWidth(); // move the bricks x screen position to the next column
                yPosition = yPosition + brick.getHeight(); // moves the bricks y screen position to the next row
                if(colorNumber == 0)
                    colorNumber = 1; // sets the color of the bricks to orange
                else
                    colorNumber = 0; // sets the color of the bricks to green
        * Displays the game screens border
        * @param  g   the Graphics object for this applet
        public void displayBorder(Graphics g)
            g.setColor(Color.black); // sets the drawing color to black
            g.fillRect(0, 0, 600, 24); // draws a border on the top of the screen
            g.fillRect(0, 0, 12, 700); // draws a border on the left of the screen
            g.fillRect(588, 0, 12, 700); // draws a border on the right of the screen
        * Displays the array of bricks on the screen
        * @param  g   the Graphics object for this applet
        public void displayBricks(Graphics g)
            Brick currentBrick; // holds the brick data from the current ArrayList container
            for(int i = 0; i < 32; i++)
                currentBrick = (Brick)(brickArray.get(i)); // grabs the brick data from the current ArrayList container
                currentBrick.display(g); // displays the current brick
        * Called by the browser or applet viewer to inform this JApplet that it
        * should start its execution. It is called after the init method and
        * each time the JApplet is revisited in a Web page.
         public void start()
             if(timer == null)
                 timer = new Thread(this); // creates a new object of type Thread
                 timer.start(); // starts the new thread
                 running = true; // tells the program that the new thread is running
        * Runs the code that controls the animation
        public void run()
            do{
                repaint(); // redraws the screen
                try{
                    timer.sleep(100); // puts the thread to sleep for 100 milliseconds
                } catch(InterruptedException e) {running = false;}
                // !!!!!!! have tried placing ball.start() here
            } while(running);
            timer = null; // destroys the timer thread
        * Called by the browser or applet viewer to inform this JApplet that
        * it should stop its execution. It is called when the Web page that
        * contains this JApplet has been replaced by another page, and also
        * just before the JApplet is to be destroyed.
        public void stop()
            running = false; // tells the program that the thread is now done
    }These are the bits of code for my class heirarchy, just to (hopefully) make it easier to follow.
    import java.awt.*;
    * The parent class of all the games objects.
    * @author Kris Nelson
    * @version November 9, 2004
    public class Sprite
        protected double screenX, screenY; // stores the x and y location of the object
        * Constructor for objects of class Sprite
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        public Sprite(double xPosition, double yPosition)
            screenX = xPosition; // sets the initial x screen position
            screenY = yPosition; // sets the initial y screen position
        * Sets new x and y screen locations for an object
        * @param  newX   the new x screen location
        * @param  newY   the new y screen location
        public void setScreenXY(double newX, double newY)
            screenX = newX; // sets the new x screen location
            screenY = newY; // sets the new y screen location
        * Sends back the current x screen location
        * @return     the current x screen location
        public double getScreenX()
            return screenX; // returns the current x screen location
        * Sends back the current y screen location
        * @return     the current y screen location
        public double getScreenY()
            return screenY; // returns the current y screen location
    import java.awt.*;
    * Parent class of any game object that moves.
    * @author Kris Nelson
    * @version November 9, 2004
    public class MovingSprite extends Sprite implements Runnable
         protected double speedX, speedY; // stores the speed of an object in the x and y directions
         protected Thread timer; // the thread which controls animation for all moving objects
         protected boolean running; // tells the program whether or not the thread is running
         * Constructor for objects of class MovingSprite
         * @param  xPosition   the initial x screen position
         * @param  yPosition   the initial y screen position
         * @param  xSpeedValue   the speed in the x direction
         * @param  ySpeedValue   the speed in the y direction
         public MovingSprite(double xPosition, double yPosition, double xSpeedValue, double ySpeedValue)
              super(xPosition, yPosition); // passes the initial screen positions to Sprite
              speedX = xSpeedValue; // sets the speed in the x direction
              speedY = ySpeedValue; // sets the speed in the y direction
         * Sends back the speed in the x direction
         * @return     the speed in the x direction
         public double getSpeedX()
             return speedX; // returns the speed in the x direction
         * Sends back the speed in the y direction
         * @return     the speed in the y direction
         public double getSpeedY()
             return speedY; // returns the speed in the y direction
         * Starts the thread in order to start animation
         public void start()
             if(timer == null)
                 timer = new Thread(this); // creates a new object of type Thread
                 timer.start(); // starts the new thread
                 running = true; // tells the program that the new thread is running
         * Empty since the child objects have their own run methods
         public void run()
         * Stops the thread from running
         public void stop()
             running = false; // tells the program that the thread is now done
    import java.awt.*;
    * Creates a single ball who's purpose is to bounce around and destroy the bricks.
    * @author Kris Nelson
    * @version November 10, 2004
    public class Ball extends MovingSprite
        protected static final double BALL_WIDTH = 15; // sets the width of the ball
        protected static final double BALL_HEIGHT = 15; // sets the height of the ball
        * Constructor for objects of class Ball
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        * @param  xSpeedValue   the speed in the x direction
        * @param  ySpeedValue   the speed in the y direction
        public Ball(double xPosition, double yPosition, double xSpeedValue, double ySpeedValue)
            super(xPosition, yPosition, xSpeedValue, ySpeedValue); // passes the initial screen positions and ball speeds to MovingSprite
            // !!!!!!!! have tried placing timer.start() here
        * Displays a ball onto the screen
        * @param  g   the Graphics object for this applet
        public void display(Graphics g)
            g.setColor(Color.blue); // sets the balls color
            g.fillOval((int)(screenX), (int)(screenY), (int)(BALL_WIDTH), (int)(BALL_HEIGHT)); // displays the ball
        * Runs the code that controls the balls animation
        public void run()
            do{
                try{
                    timer.sleep(100); // puts the thread to sleep for 100 milliseconds
                } catch(InterruptedException e) {running = false;}
                screenX = screenX + speedX;
                screenY = screenY + speedY;  // this is VERY SIMPLE BALL MOVEMENT FOR TESTING PURPOSES, WILL BE CHANGED LATER
            } while(running);
    }Sorry if that was too much code. I'm just trying to make this easier to follow.
    I placed a // !!!!!!!!!!!!! comment in the places where I have tried starting the ball thread.
    So basically, everything is running fine, except that I'm not at all sure of where to start the ball Thread, and thus can't start anything moving. If someone could tell me where I should be starting the thread, I would REALLY appriciate it. Thank you :D
    - Kris

    Some advice.
    1. the start method on the ball should be called from the start method on the applet and should in turn call the start method on the sprite's thread.
    2. the run method of the Moveable sprite should have been declare abstract
    3. don't implement borders manually. There's a java.awt.Border class for that.
    4. probably, you don't want to have the game invoke each sprite by name; just make a big list of all the sprites and invoke all of them every time
    5. do you really need provision for a non-circular ball? this isn't rugby.
    6. I don't think you ever had a threading problem, just a display problem.
    7. Don't write comments like this:     ball.display(g); // displays the ballHere's my (even more simplified version):import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    * Class BreakoutApplet - Plays a simple game of Breakout.
    * @author Kris Nelson, modified by Michael Lorton
    * @version November 10, 2004
    public class BreakoutApplet extends JApplet implements Runnable {  
        protected Ball ball;
        protected Paddle paddle;
        public boolean running; // tells the program whether or not the thread is running
        protected Thread timer; // the thread which controls the animation for the applet
        public void init() {
            // this is a workaround for a security conflict with some browsers
            // including some versions of Netscape & Internet Explorer which do
            // not allow access to the AWT system event queue which JApplets do
            // on startup to check access. May not be necessary with your browser.
            getRootPane().putClientProperty("defeatSystemEventQueueCheck",
                                            Boolean.TRUE);
             ball = new Ball(this, GAMEWIDTH / 2, GAMEHEIGHT / 2, 5, 5);
        public final static int GAMEWIDTH = 600;
        public final static int GAMEHEIGHT = 400;
        public void paint(Graphics g) {
            g.setColor(Color.lightGray);
            g.fillRect(0, 0,
                       GAMEWIDTH, GAMEHEIGHT);
            ball.display(g); // displays the ball
        * Called by the browser or applet viewer to inform this JApplet that it
        * should start its execution. It is called after the init method and
        * each time the JApplet is revisited in a Web page.
        public void start() {
            if(timer == null) {
                timer = new Thread(this); // creates a new object of type Thread
                timer.start(); // starts the new thread
                running = true; // tells the program that the new thread is running
            ball.start();
        * Runs the code that controls the animation
        public void run() {
            do{
                repaint(); // redraws the screen
                try{
                    Thread.sleep(100);
                } catch(InterruptedException e) {running = false;}
            } while(running);
        public void stop() {
            running = false;
    abstract class Sprite {
        protected double screenX, screenY; // stores the x and y location of the object
        protected final BreakoutApplet parent;
        * Constructor for objects of class Sprite
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        public Sprite(BreakoutApplet parent, double xPosition, double yPosition) {
            this.parent = parent;
            screenX = xPosition; // sets the initial x screen position
            screenY = yPosition; // sets the initial y screen position
        * Sets new x and y screen locations for an object
        * @param  newX   the new x screen location
        * @param  newY   the new y screen location
        public void setScreenXY(double newX, double newY) {
            screenX = newX; // sets the new x screen location
            screenY = newY; // sets the new y screen location
        * Sends back the current x screen location
        * @return     the current x screen location
        public double getScreenX() {
            return screenX; // returns the current x screen location
        * Sends back the current y screen location
        * @return     the current y screen location
        public double getScreenY() {
            return screenY; // returns the current y screen location
        abstract public void display(Graphics g);
    * Parent class of any game object that moves.
    * @author Kris Nelson
    * @version November 9, 2004
    abstract class MovingSprite extends Sprite implements Runnable {
        protected double speedX, speedY; // stores the speed of an object in the x and y directions
        protected Thread timer; // the thread which controls animation for all moving objects
        protected boolean running; // tells the program whether or not the thread is running
        * Constructor for objects of class MovingSprite
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        * @param  xSpeedValue   the speed in the x direction
        * @param  ySpeedValue   the speed in the y direction
        public MovingSprite(BreakoutApplet parent,
                            double xPosition, double yPosition,
                            double xSpeedValue, double ySpeedValue) {
            super(parent, xPosition, yPosition);
            speedX = xSpeedValue; // sets the speed in the x direction
            speedY = ySpeedValue; // sets the speed in the y direction
        * Starts the thread in order to start animation
        public void start() {
            if(timer == null) {
                timer = new Thread(this); // creates a new object of type Thread
                timer.start(); // starts the new thread
                running = true; // tells the program that the new thread is running
        * Runs the code that controls the balls animation
        public void run() {
            while (parent.running) {
                try{
                    Thread.sleep(100);
                } catch(InterruptedException e) {
                    System.err.println(e);
                step();
        abstract protected void step();
    * Creates a single ball whose purpose is to bounce around and destroy the bricks.
    * @author Kris Nelson
    * @version November 10, 2004
    class Ball extends MovingSprite {
        protected static final int BALL_DIAMETER = 15;
        * Constructor for objects of class Ball
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        * @param  xSpeedValue   the speed in the x direction
        * @param  ySpeedValue   the speed in the y direction
        public Ball(BreakoutApplet parent,
                    double xPosition, double yPosition,
                    double xSpeedValue, double ySpeedValue) {
            super(parent, xPosition, yPosition, xSpeedValue, ySpeedValue);
        * Displays a ball onto the screen
        * @param  g   the Graphics object for this applet
        public void display(Graphics g) {
            g.setColor(Color.blue);
            g.fillOval((int)(screenX),
                       (int)(screenY),
                       BALL_DIAMETER, BALL_DIAMETER);
        protected void step() {
                screenX = screenX + speedX;
                if (screenX < 0) {
                    screenX = -screenX;
                    speedX = -speedX;
                else if ((screenX + BALL_DIAMETER)> BreakoutApplet.GAMEWIDTH) {
                    screenX = 2*(BreakoutApplet.GAMEWIDTH  - BALL_DIAMETER) - screenX;
                    speedX = -speedX;
                screenY = screenY + speedY;
                if (screenY < 0) {
                    screenY = -screenY;
                    speedY = -speedY;
                else if ((screenY  + BALL_DIAMETER) > BreakoutApplet.GAMEHEIGHT) {
                    screenY = 2*(BreakoutApplet.GAMEHEIGHT - BALL_DIAMETER) - screenY;
                    speedY = -speedY;
    }

  • Fibonacchi/ return problems

    No matter how I try to rearrange things the output always comes to 0.0
    import java.awt.*;
    import javax.swing.*;
    * Class Fibonacchi - write a description of the class here
    * @author (your name)
    * @version (a version number)
    public class Fibonacchi extends JApplet
        // instance variables - replace the example below with your own
        double n, answer, equation;
         * Called by the browser or applet viewer to inform this JApplet that it
         * has been loaded into the system. It is always called before the first
         * time that the start method is called.
        public void init()
            // this is a workaround for a security conflict with some browsers
            // including some versions of Netscape & Internet Explorer which do
            // not allow access to the AWT system event queue which JApplets do
            // on startup to check access. May not be necessary with your browser.
            JRootPane rootPane = this.getRootPane();   
            rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
            // provide any initialisation necessary for your JApplet
        public double equation (double n) {
            n = 7;
            if (n < 1)
                return 0;
                else if (n == 1)
                    return 1;
                        else
                            return ((n-1) + (n-2));
         * Paint method for applet.
         * @param  g   the Graphics object for this applet
        public void paint(Graphics g)
            g.drawString("Sample Applet " + equation, 20, 20);  //Option 1 I was hoping would work with variable 'equation'
            g.drawString("Sample Applet2 " + n, 20, 40);    //Option 2 I was hoping would work with variable 'n'
    }

    I think I am having a problem understanding how the overall structure of this applet is supposed to be organized. I am trying to write a recursive function to calculate the Fibonacchi number from a number where if:
    f(n) = 0, if n < 1
    f(n) = 1, if n = 1
    f(n) = f(n-1) + f(n-2), if n > 1
    It seems like it should be a very simple process for me but I could use some pointing in the right direction. I've been going through the java tutorials looking for some clues, hopefully something in my mind starts clicking.

  • How to "kill" AWT Event Queue thread without using System.exit()?

    When I run my program and the first GUI window is displayed a new thread is created - "AWT-Event Queue". When my program finishes, this thread stays alive and I think it causes some problems I have experienced lately.
    Is there any possibility to "kill" this thread without using System.exit() (I can't use it for some specific reasons)

    All threads are kept alive by the JVM session. When you use System.exit(int) you kill the current session, thus killing all threads. I'm not sure, though...
    What you could do, to make sure all threads die, is to make ever thread you start member of a thread group. When you want to exit you app, you kill all the threads in the thread group before exit.
    A small example:
    //Should be declared somewhere
    static ThreadGroup threadGroup = new ThreadGroup("My ThreadGroup");
    class MyClass extends Thread {
    super(threadGroup, "MyThread");
    Thread thread = new Thread(threadGroup, "MySecondThread");
    void exit() {
    //Deprecated, seek alternative
    threadGroup.stop();
    System.exit(0);
    }

  • MACOS 10.4: Solve AWT Event queue hangup

    Hi,
    I'm having trouble with the AWT eventqueu. On MacOS 10.4, using Java 5 Runtime, my applet sometimes blocks. When looking at the threadstack, the deadlock always appears in the Event Loop, dispatching an AWT event, blocking in the CGlobalCursorManager._updateCursor call. In fact the CGlobalCursorManager.findHeavyweightUnderCursor Native call.
    I already tried some workarounds:
    - overwrite the validate method of my custom AWT components. Making sure that they do not block forever. This solves the problem for events coming through the overidden component, but it has to work for every event that might trigger the GlobalCursorManager.
    I had some possible solutions for which I would like some pro's and con's in this forum:
    1. I could try to kill the event loop. Is it possible to quit the event loop and restart it from within the applet ?
    2. Can I force each AWT container to use another implementation of the validate method ?
    3. Can I set another, customized, CGlogalCursorManager ?
    4. Other possibilities ?
    Thanks in advance for all those responding.

    I think you mean that I can override the validate method for each custom UI object separately.
    That's a possibility, but I was looking for a more general solution. If possible, I would to extends one
    class. E.g. can I set another event queue ? That way, I could make a custom event queue in case of a Mac OS browser.

  • JTable Awt -Event Queue problem

    Hi
    I've been looking everywhere for a solution to this, but can't seem to find one. I've got a JTable with an underlying model that is being continuously updated (every 100ms or so). Whenever I try to sort the JTable using TableRowSorter while the model is being added to I get
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.Vector.elementAt(Vector.java:430)
    at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277)
    I don't understand this as in my custom table model I've added the fireTableChanged etc. in a SwingUtilities.invokeLater( ...) thread.
    Has anyone else encountered this problem and found a solution? I'd be really grateful!
    Thanks

    Hi
    Thanks for responding, I'm still a little confused. I've posted the code below for both the JTable and the TableModel. The tablemodel simply gets values from a vector which is being dynamically updated from outside the table - but whenever the vector is added to
    The problem seems to only occur when I press the column header to sort the tables during the updates. My understanding is that the method refresh() should create a threadsafe update of the table - but somehow it refreshes the binding to the tablemodel and during this time the table returns a defaulttablemodel that doesn't correspond to the actual underlying data....I thought this kind of problem would be solved by invoking all updates on the swing event thread, but it seems to still produce the effect and I'm stumped!!
    (The data is in an array called turns, and the addElement() in another class calls the refresh() method)
    many thanks, in the hope that someone has the kindness and and benevolence to wade through the following code!
    public class JContiguousTurnsListTable extends JTable {
    private JContiguousTurnsListTableModel jctltm;
    public JContiguousTurnsListTable(Conversation c) {
    super();
    jctltm = new JContiguousTurnsListTableModel(this,c);
    this.setModel(jctltm);
    setSize();
    //this.setAutoResizeMode(AUTO_RESIZE_ALL_COLUMNS);
    //this.setAutoCreateRowSorter(true);
    TableRowSorter <TableModel> sorter = new TableRowSorter <TableModel>(jctltm);
    //sorter.setSortsOnUpdates(true);
    this.setRowSorter(sorter);
    System.err.println("Setting up ");
    private void setSize(){
    TableColumn column = null;
    for (int i = 0; i <11; i++) {
    column = this.getColumnModel().getColumn(i);
    if(i==1||i==2||i==3||i==4||i==8||i==9){
    column.setPreferredWidth(50);
    else if (i==0||i==5){
    column.setPreferredWidth(180);
    else if (i == 6) {
    column.setPreferredWidth(150);
    else if(i==10){
    column.setPreferredWidth(250);
    else
    column.setPreferredWidth(100);
    //column.setPreferredWidth(100);
    //column.setMinWidth(100);
    //column.setMaxWidth(100);
    public String getColumnName(int column){
    return jctltm.getColumnName(column);
    public void refresh(){
    this.jctltm.refresh();
    ----------------And the table model:
    public class JContiguousTurnsListTableModel extends AbstractTableModel {
    private Conversation c;
    public JContiguousTurnsListTableModel(JTable jt,Conversation c) {
    super();
    this.c=c;
    public void refresh(){
    //System.out.println("Refresh");
    SwingUtilities.invokeLater(new Runnable(){public void run(){fireTableDataChanged();fireTableStructureChanged();} });
    public boolean isCellEditable(int x, int y){
    return false;
    public String getColumnName(int column){
    if(column==0){
    return "Sender";
    else if(column==1){
    return "Onset";
    else if (column==2){
    return "Enter";
    else if(column ==3){
    return "E - O";
    else if(column ==4){
    return "Speed";
    else if(column ==5){
    return "Spoof Orig.";
    else if(column ==6){
    return "Text";
    else if(column ==7){
    return "Recipients";
    else if(column ==8){
    return "Blocked";
    else if(column ==9){
    return "Dels";
    else if(column ==10){
    return "TaggedText";
    else if(column ==11){
    return "ContgNo";
    else if(column ==12){
    return "Inconcistency";
    else{
    return " ";
    public Object getValueAt(int x, int y){
    try{ 
    //System.out.println("GET VALUE AT "+x+" "+y);
    Vector turns = c.getContiguousTurns();
    if(x>=turns.size())return " ";
    ContiguousTurn t = (ContiguousTurn)turns.elementAt(x);
    if(y==0){
    return t.getSender().getUsername();
    else if(y==1){
    return t.getTypingOnset();
    else if(y==2){
    return t.getTypingReturnPressed();
    else if(y==3){
    return t.getTypingReturnPressed()-t.getTypingOnset();
    else if(y==4){
    long typingtime = t.getTypingReturnPressed()-t.getTypingOnset();
    if(typingtime<=0)return 0;
    return ((long)t.getTextString().length())/typingtime;
    else if(y==5){
    return t.getApparentSender().getUsername();
    else if(y==6){
    return t.getTextString();
    else if(y==7){
    //System.out.println("GETTINGRECIP1");
    Vector v = t.getRecipients();
    String names ="";
    // System.out.println("GETTINGRECIP3");
    for(int i=0;i<v.size();i++){
    Conversant c = (Conversant)v.elementAt(i);
    // System.out.println("GETTINGRECIP4");
    names = names+", "+c.getUsername();
    // System.out.println("GETTINGRECIP5");
    return names;
    else if (y==8){
    if (t.getTypingWasBlockedDuringTyping())return "BLOCKED";
    return "OK";
    else if(y==9){
    return t.getNumberOfDeletes();
    else if(y==10){
    String returnText="";
    Vector v = t.getWordsAsLexicalEntries();
    for(int i=0;i<v.size();i++){
    LexiconEntry lxe= (LexiconEntry)v.elementAt(i);
    returnText = returnText+lxe.getWord()+" ("+lxe.getPartOfSpeech()+") ";
    return returnText;
    else if(y==11){
    return t.getNumberOfTurns();
    else if(y==12){
    // System.out.println("CONTIGUOUS1");
    String value ="";
    boolean hasSameRecipients = t.getTurnsHaveSameRecipients();
    boolean hasSameApparentOrigin = t.getTurnsHaveSameApparentOrigin();
    if (hasSameRecipients&hasSameApparentOrigin){
    value = "OK";
    else if (hasSameRecipients&!hasSameApparentOrigin){
    value = "Diff. O";
    else if(!hasSameRecipients&hasSameApparentOrigin){
    value = "Diff. Recip";
    else {
    value = "Diff O&R";
    //System.out.println("CONTIGUOUS2");
    return value;
    return " ";
    }catch (Exception e){
    return "UI ERROR";
    public Class getColumnClass(int column) {
    Class returnValue;
    if ((column >= 0) && (column < getColumnCount())) {
    returnValue = getValueAt(0, column).getClass();
    } else {
    returnValue = Object.class;
    return returnValue;
    public int getRowCount(){
    return this.c.getContiguousTurns().size();
    public int getColumnCount(){
    return 13;
    }

  • AWT-Event queue not responding

    Hi all! I have already posted a message with similar problem wich was solved but this now is a different one.
    I have following situation:
    I have a class that is called from somewhere (I don't know where from) and that displays a JFrame. After it calls setVisible(true) it calls function synchronized lock() which does wait(). After the JFrame is done it calls synchronized unlock() which does notifyAll().
    The purpose is that my JFrame should do some checking and then let the code that called it resume it's work normaly.
    Te problem is that this only works with JDK version 1.3. If I do it on 1.4 the frame doesn't respond to clicks and doesn't repaint. If I remove lock() and unlock() the frame works ok but the main program is not suspended.
    I suppose that the frame needs to make new threads for user clicks or repainting (I have noticed a Timer thread) but it can't do it for some reason.
    Any help?

    Yeah, as the doctor said to the patient who said "Doctor, it hurts when I do this" .. "So don't do that" ... don't do that. That is, it sounds as if your application is posting huge numbers of events? So if your application didn't post so many events, would the event queue not be filled up?
    - David

  • Exception in thread "AWT-Event Queue 0" Mem Out of Bounds. Java Heap Space

    Hello,
    I'm not sure how to resolve this Java Heap Space Memory Out of Bounds error. Could someone please assist me with this error?
    A SCENARIO:
    I am reading in tons of data from 5 separate text files. The files have tons of rows (up to 64,220 in one). The data must be read into the program and assembled. When I have all of the files populated, I receive the OOM Error. If I remove the data from one of the 5 files the program runs successfully. If I add the data back into the file and then remove the data from some other file, the program runs successfully.
    Thanks
    RodneyM

    ff.skip(18);
    i = ff.read();
    i = ((ff.read() << 8) | i);
    i = ((ff.read() << 16) | i);
    i = ((ff.read() << 24) | i);
    xsize = i;
    System.out.println("width=" + xsize);
    i = 0;
    i = ff.read();
    i = ((ff.read() << 8) | i);
    i = ((ff.read() << 16) | i);
    i = ((ff.read() << 24) | i);
    ysize = i;
    System.out.println("Height=" + ysize);
    ff.skip(38);//62-(2+16+4+4=26)=36, actually total=62 Bytes header This is completely wrong. First an foremost you should not have this code in the paint(Graphics g) method. This is a GUI thing. The paint method may be called for any reason and you do not+ want to open a file stream, read it, and do the distance transformation every single time the method is called. There's also the issue that you have overridden the paint method as opposed to subclassing a component, overriding the paintComponent method, and adding it to the frame. But that can be ignored for right now (it will come back later and cause complications).
    Next, you've said that the header is 62 bytes. This is incorrect for a png file. The code you have posted assumes (very specifically) that you have inputted a BMP version 3 with 2-color entry palette. In other words you can only open a very specific type of image with that code. Definitely not a png. This is what was causing the out of memory error since it interprets the width and height wrong when reading the bytes and you end up trying to create a 2-D int array that will take up several hundred megabytes in size
    //xsize and ysize are interpreted wrongly
    pix=new int[xsize][ysize];
    mat1=new int[xsize][ysize]; Now granted, BMP v3 is the most common type you will encounter but you must admit that the code is not very robust at all (since it requires a very specific input).

Maybe you are looking for

  • How do I get rid of the second safari icon on my dock

    I have a macbook pro and somehow I ended up having two safari icons on the dock, and I want oe gone, I tried clicking and dragging, but that didnt work

  • Mac mini won't boot, shows no video, no startup chime, startup light is on

    Hello everybody, I have a strange boot up problem with my Intel Mac mini. I think, the problem appeared after the 10.4.7 update and I believe I installed the first installer, which has some missing graphics drivers. Anyway, the problem is that when I

  • How to divide a grid (an 2D array) into subgrids? [Suduko]

    Hey guys I've been struggling with a problem with my Suduko program for a few days now and thought I could get some help here. The problem is that I have no idea how to divide a Suduko grid and stuff them into subgrids. My current plan is to go throu

  • Nikon D1x - raw file size and sharpening in Aperture

    Good day all: I have looked for several hours but can't find the answer to two questions: 1) How to set Aperture to use the full file size for the D1x, approx. 10.7 MB, vs the smaller Raw file size of 7.7 MB. The Nikon software all allows this functi

  • DO NOT ENTER sign on boot up

    I was organizing some audio files when Finder froze up. I had no option but to reboot, but then when I rebooted an internal drive wouldn't appear... as though it's vanished. And now I can't even boot up because I get a DO NOT ENTER symbol on start up