JMenuItem.setEnabled()  not working

Hello,
How can I force JMenuItem object to be disabled?
I've tried the following:
package forum;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class ForumFrame extends javax.swing.JFrame {
    public ForumFrame() {
        initComponents();
    public Dimension getMinimumSize() {
        return new Dimension(600,600);
    public Dimension getPreferredSize() {
        return getMinimumSize();
    private void initComponents(){
        setJMenuBar(menuBar);
        menuBar.add(menuItem);
        menuItem.setEnabled(false);
        menuItem.addMouseListener(new MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                System.out.println("Menu Item enabled: " +menuItem.isEnabled());
                System.out.println("Menu Item clicked!");
        pack();
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ForumFrame().setVisible(true);
    private  JMenuBar menuBar=new JMenuBar();
    private  JMenuItem menuItem=new JMenuItem("Click me gently");
}Run gives the following output:
Menu Item enabled: false
Menu Item clicked!
Thanks.

The mouse listener will always be invoked. Attach action listener to the menu item (like you do to any AbstractButton) - it will not get called on a disabled control.

Similar Messages

  • Web Cam applet is not working in great consistency

    Hi... My video capturing applet is not working very well.
    The image stream is displayed on the web page in JPEG format with 0.5 quality. However, it crashes after a while and the it does not release the vfw resource.
    I have to restart my machine in order to execute it again.
    Can anyone please help?
    Thanks.
    Carter

    Ok. Thanks.
    Sender Applet
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    /*<applet code="myGUIApplet.class" width="300" height="300"></applet>*/
    public class myGUIApplet extends JApplet implements ActionListener
         private JPanel bottom=new JPanel();
         private JPanel centVisual=new JPanel();
         private JPanel connectionAddress=new JPanel();
         private JButton capture=new JButton("Start Capturing");
         private JButton stops=new JButton("Stop");
         private JMenuBar menubar=new JMenuBar();
         private JMenu file=new JMenu("file");     
         private JMenuItem fileItem1=new JMenuItem("Exit");
         private JLabel serverip=new JLabel("Server IP");
         private JTextField setIP=new JTextField();
         public static JTextField ServerInfo=new JTextField();
         private MyTransmitter mytrans;
         private String ip;
         public static final String DEFAULT_MULTICAST_IP="226.10.10.20";
         public static final String DEFAULT_PORT="80";
         public void init()
              //setSize(400,400);               
              setLayout(new BorderLayout());
              menubar.add(file);
              file.add(fileItem1);
              bottom.setLayout(new BorderLayout());
              bottom.setBackground(Color.black);
              bottom.add("West",capture);
              bottom.add("East",stops);
              connectionAddress.setLayout(new BorderLayout());
              connectionAddress.add("North",serverip);
              connectionAddress.add("South",setIP);
              ServerInfo.setEditable(false);
              connectionAddress.add("Center",ServerInfo);
              setIP.addActionListener(this);
              setIP.setText("");
              capture.setBackground(Color.lightGray);
              capture.addActionListener(this);
              stops.addActionListener(this);
              fileItem1.addActionListener(this);
              add("South",bottom);
              add("North",menubar);     
              add("Center",connectionAddress);          
         public void actionPerformed(ActionEvent ae){
              Object source=ae.getSource();
              if(source==capture){
              if(setIP.getText().equals(""))
                        ip=DEFAULT_MULTICAST_IP;
              else{
                   ip=setIP.getText();
                   if(mytrans!=null){
                        mytrans.stopTransmitter();
                        mytrans=null;                         
                   System.out.println(" - Connecting to "+ip+" port: "+DEFAULT_PORT);
                   ServerInfo.setText(" - Connecting to "+ip+" port: "+DEFAULT_PORT);
                   mytrans=new MyTransmitter(ip,DEFAULT_PORT,ServerInfo);
                   mytrans.start();               
              if(source==stops){
                   if(mytrans!=null)
                        mytrans.stopTransmitter();
                   System.exit(0);
              if(source==fileItem1){
                   if(mytrans!=null)
                        mytrans.stopTransmitter();     
                   System.exit(0);
         public void destroy(){
              if(mytrans!=null){
                   mytrans.stopTransmitter();
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
    import java.net.InetAddress;
    import javax.media.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.media.format.*;
    import javax.media.control.TrackControl;
    import javax.media.control.QualityControl;
    import javax.media.rtp.*;
    import javax.media.rtp.rtcp.*;
    import javax.media.rtp.*;
    import java.io.InputStream;
    import javax.media.rtp.RTPManager;
    public class MyTransmitter extends Thread
         private MediaLocator videoLocator;
         private String ipAddress;
         private int basePort;
         private Integer stateLock=new Integer(0);
         private boolean failure;
         private Processor processor;
         private DataSource videoDataInput,videoDataOutput;
         private RTPManager rtpMgrs[];
         private VideoFormat JPEG_VIDEO=new VideoFormat(VideoFormat.JPEG_RTP);
         private SendStream sendStream;
         private SourceDescription descriptionList[];
         private JTextField infoField;
         public MyTransmitter(String ips,String ports,JTextField ServerInfo){
              infoField=ServerInfo;
              ipAddress=ips;
              Integer bPort=Integer.valueOf(ports);
              if(bPort!=null)
                   basePort=bPort.intValue();
         public void run()
              initializeVideo();
              if(videoLocator!=null){
                   createMyProcessor();
                   createMyManager();
              // May be should put inside the if..else statements
              //createMyTransmitter();
         // Initailize the video
         public void initializeVideo()
              // Stre the devices in a vector
              VideoFormat format=new VideoFormat(VideoFormat.RGB);
              Vector deviceList=CaptureDeviceManager.getDeviceList(format);
              CaptureDeviceInfo deviceInfo=null;
              // If there is more than one device detected
              if(deviceList.size()>0){
                   // Set the first device to device Info
                   // GEt the media locator of the devie
                   deviceInfo=(CaptureDeviceInfo)deviceList.elementAt(0);
                   videoLocator=deviceInfo.getLocator();
              }else{
                   System.out.println(" --X No device found...");
                   infoField.setText(" --X No device found...");
         public void createMyProcessor()
              boolean result=false;
              DataSource ds=null;
              // Check if the media locator is null
              if(videoLocator==null){
                   System.out.println(" --X No video locator..");
                   infoField.setText(" --X No video locator...");
              System.out.println(" - Trying to create a Processor..");
              infoField.setText(" - Trying to create a Processor..");
              // Attempt to create DataSource from media locator
              try{
                   ds=Manager.createDataSource(videoLocator);
              }catch(Exception ex){
                   System.out.println(" --X Unable to create dataSource : "+ex.getMessage());
              System.out.println(" - Video data source is created..");
              infoField.setText(" - Video data source is created..");
              // Try to create Processor from DataSource
              try{
                   processor=Manager.createProcessor(ds);
              }catch(NoProcessorException npe){
                   System.out.println(" --X Unable to create Processor: "+npe.getMessage());
                   infoField.setText(" --X Unable to create Processor: "+npe.getMessage());
              catch(IOException ioe){
                   System.out.println(" --X IOException creating Processor..");
                   infoField.setText(" --X IOException creating Processor..");
              // Wait for the processor to be configured
              result=waitForState(processor,Processor.Configured);
              if(result==false){
                   System.out.println(" --X Could not configure processor..");
                   infoField.setText(" --X Could not configure processor..");
              // Set the track controls for processor
              TrackControl []tracks=processor.getTrackControls();
              if(tracks==null || tracks.length<1){
                   System.err.println(" --X No track is found..");
                   infoField.setText(" --X No track is found..");
              // Set the content description of processor to RAW_RTP format
              // This will limit the supported formats to reported from
              // Track.getSupportedFormats() to valid RTP format
              ContentDescriptor cdes=new ContentDescriptor(ContentDescriptor.RAW_RTP);
              processor.setContentDescriptor(cdes);
              Format []supported;
              Format chosen=null;
              boolean atLeastOneTrack=false;
              for(int i=0;i<tracks.length;i++){
                   Format format=tracks.getFormat();
                   if(tracks[i].isEnabled()){
                        supported=tracks[i].getSupportedFormats();
                        // WE've set the output content to RAW_RTP.
                        // So, all the supporte formats should work with RAW_RTP.
                        // We will pick the first one.
                        if(supported.length>0){
                             if(supported[0] instanceof VideoFormat){                              
                                  chosen=checkVideoSize(tracks[i].getFormat(),supported[0]);
                             }else
                                  chosen=supported[0];
                             tracks[i].setFormat(chosen);
                             System.out.println(" Track "+i+" is transmitted in "+chosen+" format.. ");
                             infoField.setText(" Track "+i+" is transmitted in "+chosen+" format.. ");
                             atLeastOneTrack=true;
                        }else{
                             // If no format is suitable, track is disabled
                             tracks[i].setEnabled(false);
                   }else
                        tracks[i].setEnabled(false);          
              if(!atLeastOneTrack)
                   System.out.println("atLeastOneTrack: "+atLeastOneTrack);
                   System.out.println(" --X Could Not find track to RTP format..");
                   infoField.setText("atLeastOneTrack: "+atLeastOneTrack);
                   infoField.setText(" --X Could Not find track to RTP format..");
              result=waitForState(processor,Controller.Realized);
              if(result==false){
                   System.out.println(" --X Could NOT realize processor...");
                   infoField.setText(" --X Could NOT realize processor...");
              // Set the JPEG Quality to value 0.5
              setJPEGQuality(processor,0.5f);
              // Set the output Data Source
              videoDataOutput=processor.getDataOutput();
              //Start the processor
              processor.start();          
         public void setJPEGQuality(Processor p,float values)
              Control []cs=p.getControls();
              QualityControl qc=null;
              VideoFormat JPEGFmt=new VideoFormat(VideoFormat.JPEG);
              // Loop through the ocntrols to find the Quality control for the JPEG encoder
              for(int i=0;i<cs.length;i++){
                   if(cs[i] instanceof QualityControl && cs[i] instanceof Owned){
                        Object owner=((Owned)cs[i]).getOwner();
                        // Check if the owner is the Codec
                        // Check the format of output as well
                        if(owner instanceof Codec){
                             Format fmts[]=((Codec)owner).getSupportedOutputFormats(null);
                             // Loop through the supported format and set the quality to 0.5
                             for(int j=0;j<fmts.length;j++){
                                  qc=(QualityControl)cs[i];
                                  qc.setQuality(values);
                                  System.out.println(" - Quality is set to "+values+" on "+qc);
                                  infoField.setText(" - Quality is set to "+values+" on "+qc);
                                  break;
                   if(qc!=null)
                        break;
         public Format checkVideoSize(Format originalFormat,Format supported)
              int width,height;
              Dimension size=((VideoFormat)originalFormat).getSize();     
              Format jpegFormat=new Format(VideoFormat.JPEG_RTP);
              Format h263fmt=new Format(VideoFormat.H263_RTP);
              if(supported.matches(jpegFormat)){
                   width=(size.width%8 == 0 ? size.width:(int)(size.width%8)*8);
                   height=(size.height%8 == 0 ? size.height:(int)(size.height%8)*8);
              }else if(supported.matches(h263fmt)){
                   if(size.width<128){
                        width=128;
                        height=96;
                   }else if(size.width<176){
                        width=176;
                        height=144;
                   }else{
                        width=352;
                        height=288;
              }else{
                   // Unknown format, just return it.
                   return supported;
              return (new VideoFormat(null,new Dimension(width,height),Format.NOT_SPECIFIED,null,Format.NOT_SPECIFIED)).intersects(supported);
         public boolean waitForState(Processor p,Integer status)
              p.addControllerListener(new StateListener());
              failure=false;
              if(status==Processor.Configured){
                   p.configure();               
              }else if(status==Processor.Realized){
                   p.realize();
              //Wait until an event that confirms the success of the method, or failure of an event
              while(p.getState()<status && !failure){
                   synchronized(getStateLock()){
                        try{
                             // Wait
                             getStateLock().wait();
                        }catch(InterruptedException ie){
                             return false;
              if(failure)
                   return false;
              else
                   return true;
         public Integer getStateLock(){
              return stateLock;
         public void setFailure(){
              failure=true;
         public void createMyManager()
              SessionAddress destAddress;
              InetAddress ipAddr;
              int port;
              SourceDescription srcDesList[];
              PushBufferDataSource pbds=(PushBufferDataSource)videoDataOutput;
              PushBufferStream pbss[]=pbds.getStreams();          
              rtpMgrs=new RTPManager[pbss.length];          
              for(int a=0;a<pbss.length;a++){
              try{
                   // RTP Managers or RTP Manager?????
                   rtpMgrs[a]=RTPManager.newInstance();
                   port=basePort;
                   ipAddr=InetAddress.getByName(ipAddress);
                   SessionAddress localAddr=new SessionAddress(InetAddress.getLocalHost(),port+20);
                   destAddress=new SessionAddress(ipAddr,port,1);
                   Integer myipprefix=Integer.valueOf(ipAddress.substring(0,3));
                   if((myipprefix.intValue()>223) && (myipprefix.intValue()<240)){
                        rtpMgrs[a].initialize(destAddress);
                   }else{
                        rtpMgrs[a].initialize(localAddr);
                   rtpMgrs[a].addTarget(destAddress);
                   System.out.println(" Created RTP session: "+ipAddress+" "+port+" to "+destAddress);
                   infoField.setText(" Created RTP session: "+ipAddress+" "+port+" to "+destAddress);
                   if(videoDataOutput!=null){
                        sendStream=rtpMgrs[a].createSendStream(videoDataOutput,0);
                        sendStream.start();
                        System.out.println(" RTP stream is started..");
                        infoField.setText(" RTP stream is started..");
              }catch(UnsupportedFormatException ex){
                   System.out.println(" --X Unsupported Format : "+ex);
                   infoField.setText(" --X Unsupported Format : "+ex);
              catch(IOException ioe){
                   System.out.println(" --X IOException : "+ioe.getMessage());
                   infoField.setText(" --X IOException : "+ioe.getMessage());
              catch(Exception ex){
                   System.out.println(" --X Unable to create RTP Manager...");
                   System.out.println(ex.getMessage());
                   infoField.setText(" --X Unable to create RTP Manager..."+ex.getMessage());
         /*public void createMyTransmitter()
         try{
              if(videoDataOutput!=null){
                   sendStream=rtpMgrs[i].createSendStream(videoDataOutput,0);
                   sendStream.start();
         }catch(UnsupportedFormatException ex){
                   System.out.println(" --X Unsupported Format : "+ex);
                   infoField.setText(" --X Unsupported Format : "+ex);
         catch(IOException ioe){
                   System.out.println(" --X IOException : "+ioe.getMessage());
                   infoField.setText(" --X IOException : "+ioe.getMessage());
         public void stopTransmitter(){
              if(processor!=null){
                   processor.stop();
                   processor.close();
                   processor=null;
                   // Loop through RTP Managers and close all managers..
                   // Dispose them for garbage collection
                   for(int i=0;i<rtpMgrs.length;i++){
                        rtpmgrs[i].removeSendStream(this);
                        rtpMgrs[i].removeTargets("Session ended..");
                        rtpMgrs[i].dispose();
                   //rtpMgrs.removeTargets("Session ended..");
                   //rtpMgrs.dispose();
         * StateListener class to handle Controller events
         class StateListener implements ControllerListener{
              public void controllerUpdate(ControllerEvent ce){
                   if(ce instanceof ControllerClosedEvent){
                        processor.close();
                   /* Handle all controller events and notify all
                   waiting thread in waitForState method */
                   if(ce instanceof ControllerEvent){
                        synchronized(getStateLock()){
                             getStateLock().notifyAll();
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    Client Applet
    import javax.media.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.media.control.BufferControl;
    import javax.media.control.*;
    import javax.media.format.*;
    import javax.media.rtp.*;
    import javax.media.rtp.rtcp.*;
    import javax.media.rtp.event.*;
    import com.sun.media.rtp.RTPSessionMgr;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    import java.net.*;
    import java.net.URL;
    import java.net.Socket;
    /*<applet code="clientPlayerApplet.class" width="400" height="300">
         <param name=ServerIPS value="192.168.0.9">
         <param name=ServerPort value="80">
         <param name=TimeToLive value="1">
         <param name=archive value="clientPlayerApplet.jar">
    </applet> */
    public class clientPlayerApplet extends JApplet implements ControllerListener, ReceiveStreamListener,SessionListener
         String sessions[]=null;
         RTPManager rtpmgrs[]=null;     
         boolean dataReceived=false;
         Object myDataSync=new Object();
         private Player player;
         //private String serveripadd="226.10.10.20";
         //private int serverPort=2020;
         //private int timeToLive=1;
         private JPanel panel;
         private Vector currentParticipant;
         public void init()
              panel=new JPanel();
              setLayout(new BorderLayout());
              add("Center",panel);
              //String[] urls;
              /*urls[0]=getParameter("ServerIPS");
              urls[1]="/";
              urls[2]=getParameter("ServerPort");*/
              String []urls={new String(getParameter("ServerIPS")+"/"+getParameter("ServerPort")+"/"+getParameter("TimeToLive"))};
              sessions=urls;          
              initializePlayer();
         public void initializePlayer(){
              try{
                   InetAddress ipAddr;
                   SessionAddress localAddr=new SessionAddress();
                   SessionAddress destAddr;
                   rtpmgrs=new RTPManager[sessions.length];
                   currentParticipant=new Vector();
                   //rtpmgrs=new RTPManager();
                   SessionLabel session=null;
                   //Open RTP session
                   for(int i=0;i<sessions.length;i++){
                        try{
                             session=new SessionLabel(sessions[i]);
                             //session=new SessionLabel(sessions);
                        }catch(IllegalArgumentException iae){
                             System.out.println(" --X Unable to parse the sesion address given");     
                        System.out.println(" - Open RTP session for "+session.port);
                        rtpmgrs[i]=(RTPManager) RTPManager.newInstance();               
                        rtpmgrs[i].addSessionListener(this);
                        rtpmgrs[i].addReceiveStreamListener(this);
                        ipAddr=InetAddress.getByName(session.addr);
                        if(ipAddr.isMulticastAddress()){
                             localAddr=new SessionAddress(ipAddr,session.port,session.ttl);
                             destAddr=new SessionAddress(ipAddr,session.port,session.ttl);
                        }else{
                             localAddr=new SessionAddress(InetAddress.getLocalHost(),session.port);     
                             destAddr=new SessionAddress(ipAddr,session.port);
                        rtpmgrs[i].initialize(localAddr);
                        BufferControl bc=(BufferControl)rtpmgrs[i].getControl("javax.media.control.BufferControl");
                        if(bc!=null)
                             bc.setBufferLength(600);
                        rtpmgrs[i].addTarget(destAddr);
              }catch(Exception ex){
                   System.out.println(" --X Cannot create RTP Session "+ex.getMessage());
              long currentTime=System.currentTimeMillis();
              long waitingDuration=10000;
              try{
                   synchronized(myDataSync){
                        while(!dataReceived && (System.currentTimeMillis() - currentTime < waitingDuration)){
                             if(!dataReceived){
                                  myDataSync.wait(1000);
              }catch(Exception ex){
                   System.out.println(" --X myDataSync interrupted...");
              if(!dataReceived){
                   System.out.println(" No RTP Stream Data is received.." );               
         public void destroy()
              for(int i=0;i<currentParticipant.size();i++){
                   //if(player!=null)
                        ((MyPlayList)currentParticipant.elementAt(i)).close();
              // Loop through the RTP Managers
              // -> Remove the stream listener
              // -> Remove the target address
              // -> Dispose the RTP Manager for garbage collection
              currentParticipant.removeAllElements();
              for(int i=0;i<rtpmgrs.length;i++){
                   if(rtpmgrs[i]!=null){
                        rtpmgrs[i].removeReceiveStreamListener(this);
                        rtpmgrs[i].removeTargets(" Closing session..");
                        rtpmgrs[i].dispose();
                        rtpmgrs[i]=null;
         MyPlayList find(Player pl){
              for(int i=0;i<currentParticipant.size();i++){
                   MyPlayList mpl=(MyPlayList)currentParticipant.elementAt(i);
                   if(mpl.clientPlay==pl)
                        return mpl;
              return null;
         MyPlayList find(ReceiveStream rs){
              for(int i=0;i<currentParticipant.size();i++){
                   MyPlayList mpl=(MyPlayList)currentParticipant.elementAt(i);
                   if(mpl.stream==rs)
                        return mpl;
              return null;
         *     ReceiveStream Listener function                    *
         public synchronized void update(ReceiveStreamEvent rse)
              RTPManager mgr=(RTPManager)rse.getSource();
              ReceiveStream stream=rse.getReceiveStream();
              Participant participant=rse.getParticipant();
              if(rse instanceof RemotePayloadChangeEvent){
                   System.out.println(" -- Received Payload Change Event..");
                   System.out.println(" Sorry, no payload change is allowed.");               
              }else if(rse instanceof NewReceiveStreamEvent){
                   try{
                        // Once the new stream is detected, create the datasource
                        stream=((NewReceiveStreamEvent)rse).getReceiveStream();
                        DataSource outputDS=stream.getDataSource();
                        // Get RTP Controller to find the format
                        RTPControl rtpctl=(RTPControl)outputDS.getControl("javax.media.rtp.RTPControl");
                        if(rtpctl!=null){
                             System.out.println(" -> Received new rtP stream: "+rtpctl.getFormat());
                        }else
                             System.out.println(" -> Received new RTP stream");
                        if(participant!=null){
                             System.out.println(" -> New stream received from: "+participant.getCNAME());
                        }else{
                             System.out.println(" -> New stream detected... ");
                        player=Manager.createPlayer(outputDS);
                        if(player==null)
                             return;
                        System.out.println(" - Player is created...");
                        player.addControllerListener(this);
                        player.realize();
                        // Helper class to identify the player and stream
                        MyPlayList mpl=new MyPlayList(player,stream);
                        // Add the helper class object to Vector
                        currentParticipant.addElement(mpl);
                        // Notify initializePlayer() that a new stream has arrived
                        synchronized(myDataSync){
                             dataReceived=true;
                             myDataSync.notifyAll();
                   }catch(Exception ex){
                        System.out.println(" --X NewReceiveStream Exception: "+ex.getMessage());
                        return;
              }else if(rse instanceof ByeEvent){
                   System.out.println(" - BYE packet received from "+participant.getCNAME());
                   MyPlayList mpls=find(stream);
                   if(player!=mpls){
                        mpls.close();
                        currentParticipant.removeElement(mpls);
                   if(mgr!=null){
                        mgr.removeReceiveStreamListener(this);
                        mgr.removeTargets(" Closing session..");
                        mgr.dispose();
                        mgr=null;
              }else if(rse instanceof StreamMappedEvent){
                   if(stream!=null && stream.getDataSource()!=null){
                        DataSource myds=stream.getDataSource();
                        RTPControl rtpctrl=(RTPControl)myds.getControl("javax.media.rtp.RTPControl");
                        System.out.println(" -> The previously unidentified stream ");
                        if(rtpctrl!=null)
                             System.out.println(" "+rtpctrl.getFormat());
                        System.out.println(" has been identified as sent by :"+participant.getCNAME());
         *           Session Listener
         public void update(SessionEvent sesevt)
              if(sesevt instanceof NewParticipantEvent){
                   Participant part=((NewParticipantEvent)sesevt).getParticipant();
                   System.out.println(" -> A new partcipant has joined :"+part.getCNAME());
         *     ControllerListener for Players          
         public synchronized void controllerUpdate(ControllerEvent ce)
              Player p=(Player)ce.getSource();
              if(p==null)
                   return;
              if(ce instanceof RealizeCompleteEvent){
                   MyPlayList mpls=find(p);
                   if(mpls!=null){
                        p.start();
                        if(p.getVisualComponent()!=null){
                             panel.add(player.getVisualComponent());
                             panel.validate();
              if(ce instanceof ControllerErrorEvent){
                   p.removeControllerListener(this);
                   MyPlayList mpls=find(p);
                   if(mpls!=null){
                        // Close the player
                        // Remove the player helper class object from the list
                        p.close();
                        currentParticipant.removeElement(mpls);
                   System.out.println("Receiver internal error: "+ce);
         class SessionLabel{
              public String addr=null;
              public int port;
              public int ttl;
              SessionLabel(String session) throws IllegalArgumentException
                   int off;
                   String portStr=null;
                   String ttlStr=null;
                   if(session!=null && session.length() >0){
                        while(session.length()>1 && session.charAt(0)=='/')
                             session=session.substring(1);
                        off=session.indexOf('/');
                        if(off==-1){
                             if(!session.equals(""))
                                  addr=session;
                        }else{
                             addr=session.substring(0,off);
                             session=session.substring(off+1);
                             off=session.indexOf('/');
                             if(off==-1){
                                  if(!session.equals(""))
                                       portStr=session;
                             }else{
                                  portStr=session.substring(0,off);
                                  session=session.substring(off+1);
                                  off=session.indexOf('/');
                                  if(off==-1){
                                       if(!session.equals(""))
                                            ttlStr=session;
                                  }else{
                                       ttlStr=session.substring(0,off);
                   if(addr==null)
                        throw new IllegalArgumentException();
                   if(portStr!=null)
                        try{
                             Integer ints=Integer.valueOf(portStr);
                             if(ints!=null)
                                  port=ints.intValue();
                        }catch(Throwable t){
                             System.out.println(" --X PortStr Error..");
                             throw new IllegalArgumentException();
                   }else
                        throw new IllegalArgumentException();
                   if(ttlStr!=null){
                   try{
                        Integer intsttl=Integer.valueOf(ttlStr);
                        if(intsttl!=null)
                             ttl=intsttl.intValue();
                   }catch(Throwable t){
                             System.out.println(" --X PortStr Error..");
                             throw new IllegalArgumentException();
         class MyPlayList{
              Player clientPlay;
              ReceiveStream stream;
              MyPlayList(Player p,ReceiveStream rs){
                   clientPlay=p;
                   stream=rs;
              public void close()
                   clientPlay.close();

  • Writing to file not working, might be 1.4 problem

    Hi:
    I am trying to writing the content of a JTextArea onto a file. The content is pretty big, has newlines. I have been struggling with this in 1.4 and it just doesn't write to the file I specified. In 1.3, it works great. Here is the rough code:
    public void loadDisplayFrame()
         JMenuItem save = new JMenuItem("Save");
         //Save Action Listener
         save.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent ae)
               String filePath;
               //Save the  gsgl sample file
               if(filePath!=null && filePath.length()>0)
                  try
                  int state = saveChooser.showSaveDialog(null);
                  File f;
                  f = saveChooser.getSelectedFile();
                  if(f!=null && state==JFileChooser.APPROVE_OPTION)
                        savedName = f.getPath();
                        if(!savedName.endsWith(".gsgl"))
                           JOptionPane.showMessageDialog(null, "Invalid file name", "error", JOptionPane.ERROR_MESSAGE);
                        }else
                           processSaving();
                        }catch(Exception e)
                            e.printStackTrace();
                    }else
                        JOptionPane.showMessageDialog(null, "Please load a file first", "error",
                            JOptionPane.ERROR_MESSAGE);
              myMenu.add(save);
              JMenuBar displayMenu = new JMenuBar();
              displayMenu.add(myMenu);
      public void processSaving()
             try
                 System.out.println("Saved Name is " + savedName);
               PrintWriter out
               = new PrintWriter(new BufferedWriter(new FileWriter(savedName)));
               //name of TextArea is <display>
               String saveCode = display.getText();
              System.out.println(saveCode);                 
                 out.print(saveCode);
              out.close();
            }catch(Exception e)
              System.out.println("Exception in writing" + e.toString());
         Anyone knows what is going on? I am hoping to use 1.4 for my project. But this thing is not working. Any way around it? Thanx

    Try putting in this line before your close:
    out.flush();
    PrintWriter buffers the data and won't send it until you exit or enough data gets into the buffer to cause a flush. I assume that you are getting a zero byte file. You can also construct a PrintWriter with a boolean to indicate if it should auto flush the buffer.
    Hope that it helps.
    Paul

  • GUI JAVA 7.20 rev.2 (on Mac OSX 10.6.3): Print preview does not work!

    I've just started using rev 2 of java sapgui and print preview is not working anymore.
    Client: OSX 10.6.3
    SAP: ERP5.0 on WAS 640
    Has anyone experienced the same problem?

    This is the output in console when print-previewing:
    I'm going to open a support message as adviced.
    <code>
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]     Exception in thread "Loader for htmlViewer8_XZ_7" java.lang.NullPointerException
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at com.sap.plaf.frog.FrogListUI.updateColors(FrogListUI.java:63)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at com.sap.plaf.frog.FrogListUI.propertyChange(FrogListUI.java:48)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:339)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:276)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:318)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at java.awt.Component.firePropertyChange(Component.java:8233)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at javax.swing.JComponent.firePropertyChange(JComponent.java:4428)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at javax.swing.JComponent.setEnabled(JComponent.java:2638)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at org.icepdf.ri.common.annotation.ActionsPanel.setEnabled(ActionsPanel.java:418)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at org.icepdf.ri.common.annotation.ActionsPanel.<init>(ActionsPanel.java:106)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at org.icepdf.ri.common.annotation.AnnotationPanel.setGUI(AnnotationPanel.java:128)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at org.icepdf.ri.common.annotation.AnnotationPanel.<init>(AnnotationPanel.java:73)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at org.icepdf.ri.common.SwingViewBuilder.buildAnnotationPanel(SwingViewBuilder.java:1574)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at org.icepdf.ri.common.SwingViewBuilder.buildUtilityTabbedPane(SwingViewBuilder.java:1541)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at org.icepdf.ri.common.SwingViewBuilder.buildUtilityAndDocumentSplitPane(SwingViewBuilder.java:1501)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at org.icepdf.ri.common.SwingViewBuilder.buildContents(SwingViewBuilder.java:499)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at org.icepdf.ri.common.SwingViewBuilder.buildViewerPanel(SwingViewBuilder.java:482)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at ice.pilots.pdf.ThePilot.createComponent(ThePilot.java:149)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at ice.storm.Viewport.setPilot(VCDO)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at ice.storm.StormBase.append(VCDO)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at ice.storm.StormBase.do_clear_content(VCDO)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at ice.storm.StormBase.do_render_content(VCDO)
    04/05/10 10.45.41     [0x0-0x3e63e6].com.sap.platin[6491]          at ice.storm.Viewport.runAsynchronousLoad(VCDO)
    </code>
    Edited by: Lorenzo Nicora on May 4, 2010 10:52 AM

  • JMenu Mnemonic in  JApplet not working

    Hi,
    Here is a code in my JApplet, but some how the Mnemonic is not working,
    why??
    I m using jdk1.4.1
    Ashish
    import javax.swing.text.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
    import java.awt.*;
    import java.math.*;
    import javax.accessibility.*;
    public class TestMenuApplet extends JApplet
         public void init()
    buildMenu();
         private void buildMenu()
         JMenuBar menuBar = new JMenuBar();
    JMenu file = new JMenu("File", true);
    JMenu format = new JMenu("Format", true);     
    file.setMnemonic(KeyEvent.VK_F);
    format.setMnemonic(KeyEvent.VK_O);
    JMenuItem back = new JMenuItem("Back");
    JMenuItem close = new JMenuItem("Close");
    JRadioButtonMenuItem single =
    new JRadioButtonMenuItem("Single");
    JRadioButtonMenuItem multi =
    new JRadioButtonMenuItem("Multiple", true);
         ButtonGroup row = new ButtonGroup();
         row.add(single);
         row.add(multi);
    JMenu monthly = new JMenu("Monthly");
    JMenuItem one = new JMenuItem("One", KeyEvent.VK_O);
    JMenuItem two = new JMenuItem("Two");
    JMenuItem test = new JMenuItem("Test");
    menuBar.add(file);
    menuBar.add(format);
    file.add(back);
    file.add(close);
    format.add(single);
    format.add(multi);
    format.addSeparator();
    format.add(monthly);
    format.add(test);
    monthly.add(one);
    monthly.add(two);
    this.setJMenuBar(menuBar);
    My HTML
    <html>
    <HEAD>
    <TITLE>test</title>
    <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-Control" content="no-cache">
    <meta http-equiv="Expires" content="-1">
    </HEAD>
    <BODY >
    This is testing of applet
    <br>
    <!--"CONVERTED_APPLET"-->
    <!-- HTML CONVERTER -->
    <OBJECT
    classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    WIDTH = "300" HEIGHT = "300"
    codebase="http://java.sun.com/products/plugin/autodl/jinstall-1_4-win.cab#Version=1,4,0,0">
    <PARAM NAME = CODE VALUE = "TestMenuApplet.class" >
    <PARAM NAME="type" VALUE="application/x-java-applet;version=1.4">
    <PARAM NAME="scriptable" VALUE="false">
    <COMMENT>
         <EMBED
    type="application/x-java-applet;version=1.4"
    CODE = "TestMenuApplet.class"
    WIDTH = "300"
    HEIGHT = "300"
    scriptable=false
         pluginspage="http://java.sun.com/products/plugin/index.html#download">
         <NOEMBED>
              </NOEMBED>
         </EMBED>
    </COMMENT>
    </OBJECT>
    <!--
    <APPLET CODE = "TestMenuApplet.class"
    WIDTH = "300"
    HEIGHT = "300"
    </APPLET>
    -->
    <!--"END_CONVERTED_APPLET"-->
    </BODY>
    </html>

    Did you convert your html code to call the sun VM instead of the default browser VM ?
    Use the HtmlConverter.exe to do this passing the html file in argument.
    Denis

  • Can not fine symbol... class SwingWorker is not working...

    Hi ,
    my code is like this. I am using netbeans ide 5.5.
    package concurrency;
    import java.util.List;
    import java.util.Random;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.GridBagLayout;
    import java.awt.GridBagConstraints;
    import java.awt.Insets;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.border.Border;
    import javax.swing.BorderFactory;
    import javax.swing.*;
    public class Flipper extends JFrame
    implements ActionListener {
    private final GridBagConstraints constraints;
    private final JTextField headsText, totalText, devText;
    private final Border border =
    BorderFactory.createLoweredBevelBorder();
    private final JButton startButton, stopButton;
    private FlipTask flipTask;
    private JTextField makeText() {
    JTextField t = new JTextField(20);
    t.setEditable(false);
    t.setHorizontalAlignment(JTextField.RIGHT);
    t.setBorder(border);
    getContentPane().add(t, constraints);
    return t;
    private JButton makeButton(String caption) {
    JButton b = new JButton(caption);
    b.setActionCommand(caption);
    b.addActionListener(this);
    getContentPane().add(b, constraints);
    return b;
    public Flipper() {
    super("Flipper");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Make text boxes
    getContentPane().setLayout(new GridBagLayout());
    constraints = new GridBagConstraints();
    constraints.insets = new Insets(3, 10, 3, 10);
    headsText = makeText();
    totalText = makeText();
    devText = makeText();
    //Make buttons
    startButton = makeButton("Start");
    stopButton = makeButton("Stop");
    stopButton.setEnabled(false);
    //Display the window.
    pack();
    setVisible(true);
    private static class FlipPair {
    private final long heads, total;
    FlipPair(long heads, long total) {
    this.heads = heads;
    this.total = total;
    private class FlipTask extends SwingWorker<Void, FlipPair> {
    @Override
    protected Void doInBackground() {
    long heads = 0;
    long total = 0;
    Random random = new Random();
    while (!isCancelled()) {
    total++;
    if (random.nextBoolean()) {
    heads++;
    publish(new FlipPair(heads, total));
    return null;
    @Override
    protected void process(List<FlipPair> pairs) {
    FlipPair pair = pairs.get(pairs.size() - 1);
    headsText.setText(String.format("%d", pair.heads));
    totalText.setText(String.format("%d", pair.total));
    devText.setText(String.format("%.10g",
    ((double) pair.heads)/((double) pair.total) - 0.5));
    public void actionPerformed(ActionEvent e) {
    if ("Start" == e.getActionCommand()) {
    startButton.setEnabled(false);
    stopButton.setEnabled(true);
    (flipTask = new FlipTask()).execute();
    } else if ("Stop" == e.getActionCommand()) {
    startButton.setEnabled(true);
    stopButton.setEnabled(false);
    flipTask.cancel(true);
    flipTask = null;
    public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    new Flipper();
    Though this code is taken from java.sun.com.
    but this code is not working.. It shows :
    Compiling 1 source file to F:\ ...\FlipperProject\build\classes
    F:\....\FlipperProject\src\concurrency\Flipper.java:73: cannot find symbol
    symbol : class SwingWorker
    location: class concurrency.Flipper
    private class FlipTask extends SwingWorker<Void, FlipPair> {
    F:\.......\FlipperProject\src\concurrency\Flipper.java:79: cannot find symbol
    symbol : method isCancelled()
    location: class concurrency.Flipper.FlipTask
    while (!isCancelled()) {
    F:\.....\FlipperProject\src\concurrency\Flipper.java:84: cannot find symbol
    symbol : method publish(concurrency.Flipper.FlipPair)
    location: class concurrency.Flipper.FlipTask
    publish(new FlipPair(heads, total));
    F:\.......\FlipperProject\src\concurrency\Flipper.java:74: method does not override a method from its superclass
    @Override
    F:\.......\FlipperProject\src\concurrency\Flipper.java:89: method does not override a method from its superclass
    @Override
    F:\......1\FlipperProject\src\concurrency\Flipper.java:105: cannot find symbol
    symbol : method execute()
    location: class concurrency.Flipper.FlipTask
    (flipTask = new FlipTask()).execute();
    F:\............\FlipperProject\src\concurrency\Flipper.java:109: cannot find symbol
    symbol : method cancel(boolean)
    location: class concurrency.Flipper.FlipTask
    flipTask.cancel(true);
    7 errors
    BUILD FAILED (total time: 4 seconds)
    please help...

    try right-clicking on the source and select fix imports.

  • When my thread starts running, at that time keylistener is not working.

    when my thread starts running, at that time keylistener is not working.
    plz reply me.

    //FrameShow.java
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import java.awt.Dimension;
    import java.awt.geom.Dimension2D;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.util.logging.Level;
    import java.awt.event.*;
    import java.util.*;
    public class FrameShow extends JFrame implements ActionListener,KeyListener
         boolean paused=false;
         JButton stop;
         JButton start;
         JButton exit;
         public IncludePanel CenterPanel;
         public FrameShow()
    CenterPanel= new IncludePanel();
              Functions fn=new Functions();
              int height=fn.getScreenHeight();
              int width=fn.getScreenWidth();
              setTitle("Game Assignment--Santanu Tripathy--MCA");
              setSize(width,height);
              setResizable(false);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              show();
              initComponents();
              DefaultColorSet();
              this.addKeyListener(this);
         this.setFocusable(true);
         public void initComponents()
              Container contentpane=getContentPane();
              //Creating Panel For Different Side
              JPanel EastPanel= new JPanel();
              JPanel WestPanel= new JPanel();
              JPanel NorthPanel= new JPanel();
              JPanel SouthPanel= new JPanel();
              //CenterPanel = new IncludePanel();
              //IncludePanel CenterPanel= new IncludePanel();
              EastPanel.setPreferredSize(new Dimension(100,10));
              WestPanel.setPreferredSize(new Dimension(100,10));
              NorthPanel.setPreferredSize(new Dimension(10,100));
              SouthPanel.setPreferredSize(new Dimension(10,100));
              //CenterPanel.setPreferredSize(new Dimension(200,200));
              //Adding Color to the Panels
              NorthPanel.setBackground(Color.green);
              SouthPanel.setBackground(Color.orange);
              CenterPanel.setBackground(Color.black);
              //Creating Border For Different Side
              Border EastBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border WestBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border NorthBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border SouthBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border CenterBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              //Creating Components For East Panel
              JLabel left= new JLabel("LEFT");
              JLabel right= new JLabel("RIGHT");
              JLabel rotate= new JLabel("ROTATE");
              left.setForeground(Color.blue);
              right.setForeground(Color.blue);
              rotate.setForeground(Color.blue);
              //Creating Components For West Panel
              ButtonGroup group = new ButtonGroup();
              JRadioButton rb1 = new JRadioButton("Pink",false);
              JRadioButton rb2 = new JRadioButton("Cyan",false);
              JRadioButton rb3 = new JRadioButton("Orange",false);
              JRadioButton _default = new JRadioButton("Black",true);
              rb1.setForeground(Color.pink);
              rb2.setForeground(Color.cyan);
              rb3.setForeground(Color.orange);
              _default.setForeground(Color.black);
              //Creating Components For North Panel
              JLabel name= new JLabel("Santanu Tripathy");
              name.setForeground(Color.blue);
              name.setFont(new Font("Serif",Font.BOLD,30));
              //Creating Components For South Panel
              start = new JButton();
              stop = new JButton();
              exit = new JButton();
              start.setToolTipText("Click this button to start the game");
              start.setFont(new java.awt.Font("Trebuchet MS", 0, 12));
              start.setText("START");
              start.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(3, 5, 3, 5), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
              start.setMaximumSize(new java.awt.Dimension(90, 35));
              start.setMinimumSize(new java.awt.Dimension(90, 35));
              start.setPreferredSize(new java.awt.Dimension(95, 35));
              if(paused)
                   stop.setToolTipText("Click this button to pause the game");
              else
                   stop.setToolTipText("Click this button to resume the game");
              stop.setFont(new java.awt.Font("Trebuchet MS", 0, 12));
              stop.setText("PAUSE");
              stop.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(3, 5, 3, 5), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
              stop.setMaximumSize(new java.awt.Dimension(90, 35));
              stop.setMinimumSize(new java.awt.Dimension(90, 35));
              stop.setPreferredSize(new java.awt.Dimension(95, 35));
              exit.setToolTipText("Click this button to exit from the game");
              exit.setFont(new java.awt.Font("Trebuchet MS", 0, 12));
              exit.setText("EXIT");
              exit.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(3, 5, 3, 5), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
              exit.setMaximumSize(new java.awt.Dimension(90, 35));
              exit.setMinimumSize(new java.awt.Dimension(90, 35));
              exit.setPreferredSize(new java.awt.Dimension(95, 35));
              //Adding some extra things to the Panels
              group.add(rb1);
              group.add(rb2);
              group.add(rb3);
              group.add(_default);
              //Adding Component into the Panels
              EastPanel.add(left);
              EastPanel.add(right);
              EastPanel.add(rotate);
              WestPanel.add(rb1);
              WestPanel.add(rb2);
              WestPanel.add(rb3);
              WestPanel.add(_default);
              NorthPanel.add(name);
              SouthPanel.add(start);
              SouthPanel.add(stop);
              SouthPanel.add(exit);
              //Adding Border Into the Panels
              EastPanel.setBorder(EastBr);
              WestPanel.setBorder(WestBr);
              NorthPanel.setBorder(NorthBr);
              SouthPanel.setBorder(SouthBr);
              CenterPanel.setBorder(CenterBr);
              //Adding Panels into the Container
              EastPanel.setLayout(new GridLayout(0,1));
              contentpane.add(EastPanel,BorderLayout.EAST);
              WestPanel.setLayout(new GridLayout(0,1));
              contentpane.add(WestPanel,BorderLayout.WEST);
              contentpane.add(NorthPanel,BorderLayout.NORTH);
              contentpane.add(SouthPanel,BorderLayout.SOUTH);
              contentpane.add(CenterPanel,BorderLayout.CENTER);
              //Adding Action Listeners
              rb1.addActionListener(this);
              rb2.addActionListener(this);
              rb3.addActionListener(this);
              _default.addActionListener(this);
              exit.addActionListener(this);
              start.addActionListener(this);
    try
              start.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent e )
                        start.setEnabled(false);
    CenterPanel.drawCircle();
    catch(Exception e)
    {System.out.println("Exception is attached with sart button exp = "+e);}
    try
              stop.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent e )
                        paused=!paused;
                        if(paused)
                             start.setToolTipText("Click this button to resume the game");
                             stop.setText("RESUME");
                        else
                             start.setToolTipText("Click this button to pause the game");
                             stop.setText("PAUSE");
    CenterPanel.pause();
    catch(Exception e)
    {System.out.println("Exception is attached with sart button exp = "+e);}
         public void DefaultColorSet()
              getContentPane().setBackground(Color.white);
         public void actionPerformed(ActionEvent AE)
              String str=(String)AE.getActionCommand();
              if(str.equalsIgnoreCase("pink"))
                   CenterPanel.setBackground(Color.pink);
              if(str.equalsIgnoreCase("cyan"))
                   CenterPanel.setBackground(Color.cyan);
              if(str.equalsIgnoreCase("orange"))
                   CenterPanel.setBackground(Color.orange);
              if(str.equalsIgnoreCase("black"))
                   CenterPanel.setBackground(Color.black);
              if(str.equalsIgnoreCase("exit"))
                   System.exit(0);
         public void keyTyped(KeyEvent kevt)
    //repaint();
    public void keyPressed(KeyEvent e)
              System.out.println("here key pressed");
              //CenterPanel.dec();
         public void keyReleased(KeyEvent ke) {}
    }//End of FrameShow.ja
    //IncludePanel.java
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.Graphics.*;
    import java.awt.Dimension;
    import java.awt.geom.Dimension2D;
    import java.util.*;
    import java.util.logging.Level;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    public class IncludePanel extends JPanel implements Runnable
    int x=0,y=0;
    int color_1=0;
    int color_2=1;
    int start=0;
    Thread th;
    Image red,blue,green,yellow;
    java.util.List image;
    static boolean PAUSE=false;
         public IncludePanel()
         red= Toolkit.getDefaultToolkit().getImage("red.png");
         blue= Toolkit.getDefaultToolkit().getImage("blue.png");
         green= Toolkit.getDefaultToolkit().getImage("green.png");
         yellow= Toolkit.getDefaultToolkit().getImage("yellow.png");
    public void paintComponent(Graphics g)
              super.paintComponent(g);
              draw(g);
    public void dec()
         System.out.println("in dec method");
         x=x+30;
    public void draw(Graphics g)
              g.setColor(Color.red);
              int xx=0,yy=0;
              for (int row=0;row<=12;row++)
                   g.drawLine(xx,yy,180,yy);
                   yy=yy+30;
              xx=0;
              yy=0;
              for (int col=0;col<=6;col++)
                   g.drawLine(xx,yy,xx,360);
                   xx=xx+30;
              if(color_1==0)
                   g.drawImage(red, x, y, this);
              else if(color_1==1)
                   g.drawImage(blue,x, y, this);
              else if(color_1==2)
                   g.drawImage(green,x,y, this);
              else if(color_1==3)
                   g.drawImage(yellow,x,y, this);
    x=x+30;
              if(color_2==0)
                   g.drawImage(red, x, y, this);
              else if(color_2==1)
                   g.drawImage(blue,x,y, this);
              else if(color_2==2)
                   g.drawImage(green,x,y, this);
              else if(color_2==3)
                   g.drawImage(yellow,x,y, this);
    x=0;
    public void drawCircle( )
         th=new Thread(this);
         th.start();
         public void pause()
              if(PAUSE)
                   th.resume();
                   PAUSE=false;
                   return;
              if(!PAUSE)
              PAUSE=true;
         public synchronized void run()
              Random rand = new Random();
              Thread ani=Thread.currentThread();
              while(ani==th)
                   if(PAUSE)
                        th.suspend();
                   if(y==330)
                        color_1 = Math.abs(rand.nextInt())%4;
                        color_2 = Math.abs(rand.nextInt())%4;
                        if(color_1==color_2)
                             color_2=(color_2+1)%4;
                        y=0;
                   else
                        y=y+30;
                   repaint();
                   try
                        Thread.sleep(700);
                   catch(Exception e)
         }//End of run
    i sent two entire program

  • Transferred code from PC to MAC - PrintWriter NOT working

    Hey guys,
    I wrote a script which created a JFrame with a few buttons on my PC and had everything working nicely. The toggle button (after it's released) is supposed to output a .txt file with a few lines of data on it, but no longer works on my MAC. It's also interesting that the .setBackground() function (where I change their displayed color) no longer works either yet the setEnabled() command still does (both are under ActionListener instances).. There are no errors on my script and I'm curious to know what is going on.
    Here is my code:
    import javax.swing.*;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.lang.Long;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    public class Button  {
         protected JToggleButton jtb;
         protected JButton jbL;
         protected JButton jbR;
         protected JTextField jtext;
         public static ArrayList<Integer> goodSegments = new ArrayList<Integer>();
         public static ArrayList<Integer> badSegments = new ArrayList<Integer>();
         public static Integer initSpeech,endSpeech;
         public Integer timeStart,timeEnd;
         public String badgeNumber;
         ActionListener toggle = new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   if (jtb.isSelected()) {
                        jbL.setEnabled(true);
                        jbR.setEnabled(true);
                        initSpeech = toInteger(System.currentTimeMillis());     
                        jtb.setLabel("Processing...");
                        jtb.setBackground(Color.white);
                   else {
                        jbL.setEnabled(false);
                        jbR.setEnabled(false);
                        endSpeech = toInteger(System.currentTimeMillis());
                        try {
                             outputTXT();
                        } catch (IOException e1) {
                             e1.printStackTrace();
                        jtb.setFont(new Font("Sanserif", Font.BOLD,12));
                        jtb.setLabel("SPEECH OVER");
         ActionListener left = new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   if (jtb.isSelected()) {
                        if ("recording good".equals(e.getActionCommand()) && jbR.isEnabled()) {
                             jbR.setEnabled(false);
                             timeStart = toInteger(System.currentTimeMillis());
                             jbL.setBackground(Color.GREEN);
                        else if ("recording good".equals(e.getActionCommand()) && !jbR.isEnabled()) {
                             jbR.setEnabled(true);
                             timeEnd = toInteger(System.currentTimeMillis());
                             goodSegments.add(timeStart);
                             goodSegments.add(timeEnd);
                             jbL.setBackground(null);
         ActionListener right = new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   if (jtb.isSelected()) {
                        if ("recording bad".equals(e.getActionCommand()) && jbL.isEnabled()) {
                             jbL.setEnabled(false);
                             timeStart = toInteger(System.currentTimeMillis());
                             jbR.setBackground(Color.RED);
                        else if ("recording bad".equals(e.getActionCommand()) && !jbL.isEnabled()) {
                             jbL.setEnabled(true);
                             timeEnd = toInteger(System.currentTimeMillis());
                             badSegments.add(timeStart);
                             badSegments.add(timeEnd);
                             jbR.setBackground(null);
         ActionListener text = new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   jtext.selectAll();
                   badgeNumber = jtext.getText();
         public Button() {
              /// Setting left (good) button properties
              jbL = new JButton("Good Segment");
              jbL.setHorizontalTextPosition(AbstractButton.LEADING);
              jbL.setActionCommand("recording good");
              jbL.setEnabled(false);
              jbL.addActionListener(left);
              /// Setting right (bad) button properties
              jbR = new JButton("Bad Segment");
              jbR.setHorizontalTextPosition(AbstractButton.LEADING);
              jbR.setActionCommand("recording bad");
              jbR.setEnabled(false);
              jbR.addActionListener(right);
              /// Setting Middle (toggle) button properties
              jtb = new JToggleButton("Begin Recording");
              jtb.setEnabled(true);
              jtb.addActionListener(toggle);
              /// Setting Text Field properties
              jtext = new JTextField("Please Enter Badge Number");
              jtext.setEditable(true);
              jtext.addActionListener(text);
         public Integer toInteger(long l) {
              Long a = new Long(l);
              Integer i = new Integer(a.intValue());
              return i;
         public void outputTXT() throws IOException {
              PrintWriter file = new PrintWriter(new BufferedWriter(new FileWriter("badge-"+badgeNumber+".txt")));
              file.write(badgeNumber.toString());
              file.println();          
              file.write(initSpeech.toString());
              file.println();
              file.write(endSpeech.toString());
              file.println();
              if (goodSegments.size() != 0)
              for (int i=0;i<goodSegments.size();i++) {
                   file.write(goodSegments.get(i).toString());
                   file.println();
              file.write(new Integer(0000).toString());
              file.println();
              for (int i=0;i<badSegments.size();i++) {
                   file.write(badSegments.get(i).toString());
                   file.println();
              file.close();
        public static void main(String[] args) {
             JFrame jframe = new JFrame();
             Button b = new Button();
            Container cp = jframe.getContentPane();
            cp.setLayout(new FlowLayout());
            cp.add(b.jbL);
            cp.add(b.jbR);
            cp.add(b.jtb);
            cp.add(b.jtext);
            jframe.pack();
            jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            jframe.setVisible(true);
    }Thanks Guys!

    You might consider explaining what "not working" means.

  • Not work tablet UI on Prestigio 5080 PRO tablet

    I read that browser.ui.layout.tablet = "1" can fix this problem. But it not works. I can work only in pnone interface that is not good for my 8'' tablet.

    Would it be possible for you to share the problematic pdf and OS information  with us at [email protected] so that we may investigate?
    Thanks,
    Adobe Reader Team

  • Why self-defined access sequences of free goods can not work?

    Hi gurus,
    I have maintained access sequences of free goods self-defined.but when i creat the SO it does not work!
    when i used the standard access sequences ,it is OK .
    Can anybody tell me why?
    thanks in advance

    Dear Sandy,
    Go to V/N1 transaction select your self defined access sequence then go in to the accesses and fields and check all fields are activated.
    Make sure that these fields are flowing in your sales order.
    I hope this will help you,
    Regards,
    Murali.

  • Adobe bridge raw not working with windows vista in photoshop cc, why?

    adobe bridge raw not working in photoshop cc, is there a fix?

    Your sure your using photoshop cc on windows vista?
    I was under the impression that photoshop cc would not even install on windows vista.
    What version of camera raw do you have?
    In photoshop under Help>About Plugin does it list Camera Raw and if so which version is it?
    (click on the words Camera Raw to see the version)
    Camera raw doesn't work if it's a camera raw file or some other file type such as jpeg or tif?
    What camera are the camera raw files from?
    Officially camera raw 8.3 is the latest version of camera raw that will work on windows vista.

  • Adobe Bridge CS5 in windows 7 not working?

    Adobe Bridge CS5 in windows 7 not working. I was using bridge perfectly for last 2 years. It stops working since 3 days. I tried to install updates. Showing some error to install.
    Tried to install creative cloud..again some error. Error code : 82
    Could you please advice how I can fix my adobe bridge.

    https://www.youtube.com/watch?v=xDYpTOoV81Q&feature=youtu.be
    please check this video I uploaded..this is what happens when I click adobe bridge.. just blinks and go off. bridge not working on task manager

  • ADOBE CLOUD ON MY DESKTOP WILL NOT WORK. IT LOADS UP BUT NOTHING FILLS THE WINDOW

    ADOBE CLOUD ON MY DESKTOP WILL NOT WORK. IT LOADS UP BUT NOTHING FILLS THE WINDOW

    BLANK Cloud Screen http://forums.adobe.com/message/5484303 may help
    -and step by step http://forums.adobe.com/thread/1440508?tstart=0
    -and http://helpx.adobe.com/creative-cloud/kb/blank-white-screen-ccp.html

  • Partner application logoff not working

    We have a partner application registered with sso with custom login screen. The login works fine. We use the following code to logoff the partner application in logoff.jsp
    response.setHeader("Osso-Return-Url", "http://my.oracle.com" );
    response.sendError(470, "Oracle SSO");
    session.invalidate();
    but the logoff is not working properly. It is not invalidating the session and the logout http request is not going from the application server to the sso server.
    Are there any additional configurations for SSO logoff.Any help is appreciated.
    Thanks

    Hi
    The WF should also trigger if i add the Partner function in UI.If i change any Attribute the WF triggers but i dont want to change the attribute when i add the partner function.
    If i have only one event for WF that is Partner Change the WF will not trigger it for the 1st time when i save the UI. But next i come to the same saved doc and add a partner function then the Wf triggers.
    So this means that Partner change is active.
    the issue here is i need to trigger the WF on , the 1st time i save the UI, for which i wil be using Attribute Change and next time when i come back to saved doc the and add only the partner function and no changes are made to attributes the WF should again trigger.
    Thanks
    Tarmeem

  • IPhone 4 Voice Memos not working/saving

    Hi there,
    I'm having trouble with my voice memos too. Up until yesterday they were working fine and now, even though the record button works, the stop button does not and I can only pause them. Worse again is that the button to go into the menu to view all voice memos is not working so I can't play them from my iPhone and nothing new is saving to my iTunes. Please help!

    I've always had the "Include Voice Memos" option selected. I think that only pertains to syncing voice memos from iTunes to the iPhone after it has been copied to iTunes. It has to be the new OS/iTunes not communicating that new memos have been recorded. For some reason they won't sync when I want them to, and then a few syncs later they magically appear.
    By the way, I'm VERY comfortable with the iTunes and iPhone systems. I've been using iTunes for 5 years, and I've been recording class lectures with the iPhone voice memo app (and another app) for a couple years. It's not an error of not seeing that the memos were added; they don't exist in my library or music folders.
    JUST OUT OF CURIOSITY, POST WHICH FIRMWARE YOU ARE RUNNING EXACTLY!!!
    I'm on an iPhone 4, running firmware 4.0.1

Maybe you are looking for

  • File to BPM Scenario?

    Hi Friends, Can anybody send me File to BPM Scenario with screen shots. Regards, Naidu.

  • Can't see why this won't work

    I have a table customer that I am trying to update with some details from another table: update customer set credit_limit = (select cr.credit_limit                     from credit_limits cr) where customer.state = cr.state and customer.credit_limit i

  • Need additional ports - best way to expand?

    I have a 10/100 WRT54GP2 supporting 2 attached PCs, a print server, Vonage VOIP, and wireless access. I have a new computer that I need to add to my home network, but I'm out of ports. Also, my new computer supports gigabit ethernet, which I may want

  • App keeps asking for admin name and password

    I just upgraded to 10.5 and am in the process of installing third party apps. One app was downloaded from the internet and installed. Each time I launch it a window opens with the following: ""Meteorologist" is an application which was downloaded fro

  • Photoshop Elements Organizer Won't Install

    I just purchased Photoshop Elements 10 and have installed it but the organizer isn't installed.  I have tried installing from the DVD and also copied all install files to a directory and installed from there with the same result--no organizer! I'm ru