Sound break every 30 secs using handbrake

On my Powerbook G4 running OSX Panther, I just encoded a peice of video taken from a DVD -r I burned using my Panasonic DVD recording deck. Handbreak did the job, but I have noticed that during playback on my iPod there is a split second break in sound approximately every 30 secs. I'm not a genious when it comes to sound, but I know a little and think it may be to do with the sample rate on the DVD being different to the re-encoded sample rate of Handbreak thus becoming out of sync and cross phasing at 30 second intervals. The DVD plays fine, its just the encoded H.264 file that doesn't. Video remains fine. Any feed back would be great.
Thanks

I just played the file in quicktime on my computer and it does the same thing in the same place so its definately the file not the iPod or iTunes. There is something up with the way handbreak is encoding, I'm pretty sure its to do with sample rates or icompatibility of the mpeg 2 file on the dvd with the software.

Similar Messages

  • Snick sound plays every 30 sec or so

    I just instaled Mavericks on my MBP, 2009, 8GB RAM. (yay) But now I'm getting this weird (and annoying) "snick" sound playing every few seconds (from 0:30 to 1:40). I'm not sure where it's coming from (which app/utility is causing this), or how to turn it off.
    As a first step, it might be useful to record it so I can play it for others, who might recognize it. How do I record what's playing on the audio?
    Thanks for your help,
    - AAA

    I just timed the last two beeps - exactly 5 min apart.

  • Sound distortion every 20 sec on Satellite C

    When listening to audio both with and without headphones, every 20 seconds or so the sound output becomes distorted for several seconds and in some cases this sound distortion also causes the computer display to freeze completely.
    My PC is a Toshiba Satellite series C running Windows 7.
    Any suggestions please?

    >every 20 seconds or so the sound output becomes distorted for several seconds and in some cases this sound distortion also causes the computer display to freeze completely.
    This looks a little bit like system freeze.
    In such case some processes which are running in the system background load the CPU and this cause short system freeze.
    Possibly you have installed a lot of different applications and therefore its mostly impossible to say what software could be the troublemaker at the other hand it would be interesting to know if you ever try to reinstall the system and to clean the HDD.
    A new OS installation might be the key.

  • On putting the ipod on in the iphone,the sound breaks every few seconds

    As per the subject

    Your notebook is an Enterprise/Business model. I would recommend posting this in the HP Enterprise Support Forums for better coverage.
    You can access the enterprise support forums at the following link.
    http://h30499.www3.hp.com/
    However, my own personal opinion is there might be an issue with the headset, not the hardware/software on the notebook. You mentioned even changing the bluetooth hardware and the issue remained, which leads me to believe it might have to do with the headset and Windows 7. Have you tried another headset on this notebook to see if the issue was the same? 
    -------------How do I give Kudos? | How do I mark a post as Solved? --------------------------------------------------------

  • I have bought a new airport express and using it with my macbook (iTunes 10.2.2). I have joined an existing network for internet in my home and with that i am trying to play the music via itunes but there is audio dropouts every 60 secs or so. any soln ?

    I have bought a new airport express and using it with my macbook (iTunes 10.2.2). I have joined an existing wireless network for internet in my home and with that i am trying to play the music via itunes but there is audio dropouts every 60 secs or so. I am using a set of speakers from kenwood connected to the airport express. The operating system on my macbook is mac os X 10.5.8. i am sure it is not a problem of streaming music online because i have even tried playing music which are stored in my macbook.
    Is there any problem with the setting in itunes or quicktime ? Kindly reply...... I am waiting for your valuable suggestion.
    Thank you a lot in advance.

    I am shocked to have found this same AX audio dropout problem starting TODAY, every few seconds the audio just drops for a couple seconds and then resumes:  Latest software versions of everything.  No iPad, iPhone or Touch.  Internet hardwired to D-Link DES1105 (1000baseT Switch) hardwired to new 80211N AX, AX optical to stereo, AX Wi-Fi internet to basic 1st-gen MacBook operating at 80211G, and an older 'G' AX extender at the far end of the house, away from all this.  The MacBook streaming iTunes is usually 12 feet from AX.  I've used this setup for years of trouble-free AirTunes / Airplay until today.  Today I also found 2 very reliable fixes and 1 way to force a dropout, but first, I read some posts and tried ALL following settings one-at-a-time and restored them ALL because NONE of them helped:  Turned off IPV6.  Streamed to multiple speakers 'Computer' and 'AX' (restored to just AX).  Turned off 'Ask to Join new (WiFi) Networks'.  Turned off Bluetooth (can't live without Magic Trackpad, so glad that wasn't it).  Here's my discoveries:  Lo and behold, each time I click the Airport icon in the Menu (you know it shows you've got 4 bars from AX) when the status switches to 'Looking for Networks' for a second it CAUSES the AX audio to drop out for a couple seconds (it never did that before today.)  iTunes still playing, streaming, AX laser still lit, but the 'PCM' light on stereo and the sound GOES OUT EVERY time I click the Airport icon in the menubar, just like the regular, annoying dropouts.  So, to reduce traffic I quit Safari (3 tabs, no streaming, just Gmail, Google, and Netflix browsing).  Lo and behold, the dropouts stopped altogether.  No other Web apps going (not iTunes Store, Genius, Ping, nothing), so I launched Chrome to the same 3 tabs and the dropouts HAVE NOT RETURNED.  That's right, not only did simply QUITTING SAFARI cure it, and Chrome doesn't contribute to it, but I can demonstrate it just by forcing my Airport to re-scan.  Works for me, written using Chrome.  The other reliable fix is to hardwire MacBook to the Switch.  This is obviously not ideal, but Airplay audio doesn't drop out over Ethernet.  Also, in all my tests, it made no difference whether iTunes did the streaming, or Airfoil did.

  • I need a timer function to ping the server every 5 secs??using threads.

    I need a timer function to ping the server every 5 secs??
    using threads...i have to use a thread coz i cant use Timer and Timer Task coz clients r on the JDK1.2 version.I have created a thread which keeps checking th ping msg & any server msg is pings 4 the1st time properly but then it just waits to read the response from server but it doesnt but the server shows that it has send the msgs to client???PLEASE HELP URGENT

    Few things are not clear from your post, like, are you using sockets and if you are, how are u reading writing to them (ur sample code would help)...
    Anyways if you are, are you doing accept on your socket in a while(true) loop or just once... If you do it only once you will get the first ping message but none afterwards if the other side closes and opens new sockets for every send... What I am suggesting is something like the following:
    ss = new ServerSocket(port);
    while(true)
         s = ss.accept();
         is = s.getInputStream();
         os = s.getOutputStream();
         reader = new BufferedReader(new InputStreamReader(is));
         writer = new BufferedWriter(new OutputStreamWriter(os));
         String in = reader.readLine();
            // do something with this string
            s.close();
            // put some check here to break out of this infinite loop
    }// end of While

  • My MBA w/SSD makes click-click sounds every 6 secs ?

    I've read the post that describes ticking sounds that people are reporting on presumably MBAs w/HDD. That post seems to imply the ticking sounds come from the HDD. After reading that post and prior to receiving my MBA w/SSD today I thought I would not be plagued by the ticking sounds.
    However, I find that my MBA w/SSD is now making click-click sounds every 6 secs with about 1 sec between the click-click all the time.
    Do others w/SSD hear these click-click sounds every 6 secs or so ?
    I've disconnected the Mag Safe and it makes no difference. I've disconnected my USB-Ethernet adapter ad it makes no difference.
    The MBA is not hot either.
    I will say though that I don't recall hearing these sounds when I first booted my MBA today. It seems to have started some 6 hours after having used the MBA for the first time.
    I'm starting to find these click-click sounds annoying as apart from them the MBA is completely quiet and it's now become like hearing the tic-tok sound of a clock when trying to get to sleep.

    Brian:
    I'm in agreement with you on this. I downloaded smcFanControl App and it shows fan rpm at "000".
    Using TermperatureMonitor I find the Cores 1 & 2 are running at around 200ºF with RPM is 000.
    Not looking good at all. Time to Call AppleCare for sure.
    It does seem like my MBA w/SSD has a faulty fan.
    If MBA were to overheat is it designed to shutdown to protect itself ?
    Well I think I've got an answer to that question as CPU 2 has been disabled per Activity Monitor. It's just plain shutdown and only one processor is running now. Core 1 temp has dropped to 141ºF now.
    Stopped the two CPU burner Apps and now see that CPU 2 has come back online. At least the MBA is designed to protect itself from a meltdown even with the fan not running. Good design IMO.
    The baby is going back to the shop for sure. Bummer.
    I guess the click-click sound every 6 secs should serve as a warning to others.
    Thanks.

  • Macbook air Wi Fi and sound stops every time it goes to sleep. i have to  restart it every time to use wifi and sounds. this started happening just after the latest upgrade to X. any reasons why its doing that and how to fix it.

    Macbook air Wi Fi and sound stops every time it goes to sleep. i have to  restart it every time to use wifi and sounds. this started happening just after the latest upgrade to OS X. any reasons why its doing that and how to fix it.

    Test after taking each of the following steps. Back up all data before making any changes.
    1. Make sure the network is on the preferred list by following these instructions. It's important to read the article carefully, as it's the starting point for any further efforts to solve the problem. If you skip any of the steps, the problem may not be solved.
    2. Follow the instructions in this support article under the heading "Symptom: The network connection drops unexpectedly."
    3. Make a note of all your settings for Wi-Fi in the Network preference pane, then delete the connection from the connection list and recreate it with the same settings. You do this by clicking the plus-sign icon below the connection list, and selecting Wi-Fi as the interface in the sheet that opens. Select Join other network from the Network Name menu, then select your network. Enter the password when prompted and save it in the keychain.
    4. From the Location menu at the top of the Network preference pane, select Edit Locations. A sheet will drop down. Click the plus-sign button to create a new location. Give it any name you want. In the new location, set up the Wi-Fi service with the same settings you used before. Click Apply and test.
    5. Launch the Keychain Access application. Search for and delete all AirPort network password items that refer to the network. Make a note of the password first.
    6. In some cases, the problem has been resolved by repairing permissions on the startup volume.
    7. Turn off Bluetooth and test.
    8. Reinstall OS X.

  • Every 120 sec. my MacBook is creating a strange unknown sound

    Hi everyone out there,
    sorry for reaching out to you, but tonight s.th. strange happened. From one moment to the next my MacBook decided to create a strange system-like sound every 120 sec. I have recorded it, so if this helps, let me know.
    I did not install any new SW or change any of the system settings - really strange!
    Cheers,
    Hartmut

    HI,
    Open System Preferences/Sound and select the Sound Effects tab. If you have all three boxes checked for user sound effects that could be the culprit. Open Mac Mail/Preferences and select the General tab.
    Where you see: New messages sound, click the pop up menu. If you hve the; Play sounds for other mail actions... that could be it too.
    Since the sound is occuring on a timely basic, might be a fan.
    Try Resetting the PRAM
    Carolyn
    Message was edited by: Carolyn Samit

  • [hp dv6358se] Internal speaker play sound intermittent(every 15s). CPU use = Max.

    O/S - Windows 7
    [Personal Information Removed]
    p/n# - rv220ua#aba
    [hp dv6358se] Internal speaker plays sound intermittent(every 15s). CPU use = Max when audio driver enabled. CPU use = normal ranges when audio driver is disabled. Head phone jack only plays out of one speaker. Lastly when head phones are pluged cpu usage returns to normal. Is there a possible software fix for this issue?

    snarfer,
    You can normally mute the microphone in the Surround Mixer (that's provided in the software). As long as you leave it as the recording source it should still work in your voice software, but won't sound over the speakers.
    Was the card always in the last PCI slot or did you move it there? If it always was there, try the slot just above it in case that particular slot shares resources with certain motherboard functions/components.
    Do you still have sound problems when the microphone is muted, or taken away completely?
    Cat

  • Why does my mac air sound like it was going to take off every time i use the wifi????

    why does my mac air sound like it was going to take off every time i use the wifi????

    Power Cycle
    Power off the router. Unplug it from the wall. Wait a while.
    Plug it back to the wall. Power the router on. Wait until all the lights are lit properly. It will take a while.
    Restart the computer.
    Start up in Safe Mode.
    http://support.apple.com/kb/PH14204?viewlocale=en_US
    Reset SMC.     http://support.apple.com/kb/HT3964
    Choose the method for:
    "Resetting SMC on portables with a battery you should not remove on your own".

  • About every 30 sec im getting a lag in firefox,any ideas why?Useing the newest version.

    about every 30 sec or so my mouse freezes along with the page im viewing.

    Start Firefox in <u>[[Safe Mode]]</u> to check if one of the extensions or if hardware acceleration is causing the problem (switch to the DEFAULT theme: Firefox/Tools > Add-ons > Appearance/Themes).
    *Don't make any changes on the Safe mode start window.
    *https://support.mozilla.org/kb/Safe+Mode
    *https://support.mozilla.org/kb/Troubleshooting+extensions+and+themes
    Create a new profile as a test to check if your current profile is causing the problems.
    See "Basic Troubleshooting: Make a new profile":
    *https://support.mozilla.org/kb/Basic+Troubleshooting#w_8-make-a-new-profile
    There may be extensions and plugins installed by default in a new profile, so check that in "Tools > Add-ons > Extensions & Plugins" in case there are still problems.
    If that new profile works then you can transfer some files from the old profile to that new profile, but be careful not to copy corrupted files.
    See:
    *http://kb.mozillazine.org/Transferring_data_to_a_new_profile_-_Firefox

  • [Solved]Alsa funkiness (sound breaking)

    (Note: I originally thought this was a steam issue, but turns out it's not only steam that can break my sound (see the update on the bottom))
    I get an issue with Steam where I get a short (less than 1s) sound on repeat/loop (usually it's some part of the message notification sound, or a trailer that I was watching) sounding a bit like a broken record, randomly occurring after keeping steam open for long periods of time in the background. Only fix I've found so far is to restart steam.
    I have the Enlightenmen 18 Window Manager.
    Notable errors:
    Fontconfig error: "/etc/fonts/conf.d/10-scale-bitmap-fonts.conf", line 70: non-double matrix element
    Fontconfig warning: "/etc/fonts/conf.d/10-scale-bitmap-fonts.conf", line 78: saw unknown, expected number
    [0706/170950:ERROR:object_proxy.cc(239)] Failed to call method: org.freedesktop.DBus.Error.ServiceUnknown: The name org.freedesktop.NetworkManager was not provided by any .service files
    [0706/170950:WARNING:proxy_service.cc(958)] PAC support disabled because there is no system implementation
    PulseAudio connect failed (used only for Mic Volume Control) with error: Access denied
    ** (steam:7341): WARNING **: Could not initialize NMClient /org/freedesktop/NetworkManager: The name org.freedesktop.NetworkManager was not provided by any .service files
    (steam:7341): LIBDBUSMENU-GLIB-WARNING **: Trying to remove a child that doesn't believe we're it's parent.
    [0706/171536:ERROR:reference_audio_renderer.cc(46)] Not implemented reached in virtual void media::ReferenceAudioRenderer::OnCreated(media::AudioOutputController*)
    [0706/171536:ERROR:reference_audio_renderer.cc(50)] Not implemented reached in virtual void media::ReferenceAudioRenderer::OnPlaying(media::AudioOutputController*)
    [0706/171657:ERROR:reference_audio_renderer.cc(54)] Not implemented reached in virtual void media::ReferenceAudioRenderer::OnPaused(media::AudioOutputController*)
    AL lib: pulseaudio.c:612: Context did not connect: Access denied
    I don't have any reliable method to reproduce the issue, and it does not seem to output an error of it's own in the terminal output when it occurs. I have noticed that this is more likely to occur when steam has been open for prolonged periods. I am not using pulseaudio, just Alsa. I also noticed when I was running a Wine game (not through steam) that this issue occurred, and it seemed to contaminate the sound outputs for whine too (I got like a "double" sound for every sound effect the game played). If the sound was completely broken on steam and making a loop like I explained at the start of this post and then I close steam while the Wine game is running, the sound from steam will remain until I shut down the game too (i.e. seems that this isn't just breakage internally in steam, but in alsa itself)
    The one thing I have tried to solve this was install lib32-libpulse, this did not seem to fix the errors nor the problem. I imagine installing pulseaudio could fix this problem, but pulseaudio downright hates my sound card, so I would rather not use it.
    I also have two other issues too that are less severe.
    1: Mouse cursor sometimes gets locked in steam instance (Right clicking will show the steam context menu, pressing "stop" in that context menu will solve the issue. This sometimes happens when I use "Ctrl + C"(copy) or "Ctrl + V"(paste) when I'm typing in the discussions)
    2: Fullscreen videos will not go fullscreen (they will only fill the steam window)
    Update:
    I found a bulletproof way to make a similar issue occur.
    If I open facebook in firefox, and get a message notification while I am playing a movie in Cmplayer (my media player of choice) the sound in CMplayer breaks (but firefox's sound keeps working normally)
    Update2:
    I was rather desperate to get this fixed so I installed pulseaudio as much as I despise it, the quality of my audio is damaged by it, but this problem was as I suspected fixed by installing it. I am guessing pulseaudio is set up partially to prevent issues like this one, but I would relaly prefer not to have it. This does not rid me of all the errors however (reference_audio_renderer errors persist) but it does create a new error for steam:
    [0706/215704:ERROR:alsa_output.cc(684)] Failed querying delay: Input/output error
    Last edited by rabcor (2014-07-11 16:28:34)

    I always had to have an asound.conf in the name of upmixing 2.0 to 5.1 This is the content of my asound.conf before I made the changes. I also had a problem with a game where I had crackling noises on 48khz so I had to tell alsa to force 96khz (or 44.1khz but since my card supports 96khz that's what I went with) to avoid that.
    pcm.!default {
    slave.pcm "surround51"
    slave.channels 6
    type route
    # Front and rear
    ttable.0.0 0.7
    ttable.1.1 0.7
    ttable.2.2 0.6
    ttable.3.3 0.6
    # Center and LFE
    ttable.4.4 1
    ttable.5.5 1
    # Front left/right to center
    ttable.0.4 0.5
    ttable.1.4 0.5
    # Front left/right to rear
    ttable.0.2 0.5
    ttable.1.3 0.5
    Now it looks like this and everything seems to be working fine (except that mono sound only plays from my left speaker and I haven't defined a way to downmix 7.1 to 5.1):
    pcm.dmixed {
    type asym
    playback.pcm {
    # See plugin:dmix at http://www.alsa-project.org/alsa-doc/alsa-lib/pcm_plugins.html
    type dmix
    # Don't block other users, e.g. the Timidity midi-player daemon
    # http://www.alsa-project.org/alsa-doc/alsa-lib/pcm_plugins.html
    ipc_key_add_uid true
    ipc_key 5678293
    ipc_perm 0660
    ipc_gid audio
    # Don't put the rate here! Otherwise it resets the rate & channels set below, as shown by: cat /proc/asound/card0/pcm0p/sub0/hw_params
    slave {
    # 2 for stereo, 6 for surround51, 8 for surround71
    channels 6
    pcm {
    # mplayer chooses S32_LE, but others usually S16_LE
    format S32_LE
    #format S16_LE
    # 44100 or 48000
    # 44100 for music, 48000 is compatible with most h/w
    #rate 44100
    rate 96000
    # http://www.alsa-project.org/alsa-doc/alsa-lib/pcm_plugins.html
    # Maybe helps
    nonblock true
    type hw
    card 0
    device 0
    subdevice 0
    # mplayer2 chooses 1024
    # period_size 512 with buffer_size 16384 stops crackling in xmame
    # 320 breaks flash - https://bbs.archlinux.org/viewtopic.php?id=129458
    #period_size 512
    period_size 1024
    #period_size 512
    # 4096 might make sound crackle
    # mplayer2 chooses 8192. Half-Life 2 chooses 16384.
    # If too large, use CONFIG_SND_HDA_PREALLOC_SIZE=2048
    buffer_size 16384
    capture.pcm "hw:0"
    pcm.!default{
    type plug
    slave.pcm "upmix20_51"
    pcm.!surround20 {
    type plug
    slave.pcm "upmix20_51"
    pcm.!surround40 {
    type plug
    slave.pcm "dmixed"
    route_policy duplicate
    pcm.!surround51 {
    type plug
    slave.pcm "dmixed"
    pcm.upmix20_51 {
    slave.pcm "dmixed"
    slave.channels 6
    type route
    # Front and rear
    ttable.0.0 0.7
    ttable.1.1 0.7
    ttable.2.2 0.6
    ttable.3.3 0.6
    # Center and LFE
    ttable.4.4 1
    ttable.5.5 1
    # Front left/right to center
    ttable.0.4 0.5
    ttable.1.4 0.5
    # Front left/right to rear
    ttable.0.2 0.5
    ttable.1.3 0.5
    Is there a better way for me to achieve the results of the above config? Because I'm all ears.
    Last edited by rabcor (2014-07-08 11:09:23)

  • IPad loses sound aprox every 4 hours

    My iPad loses the sound aprox every 4 hours. When it happens somehow the camera recording function is also not working only Still picture. After restart everything works again.
    I reset to factory default and has reloaded from the backup same happens.
    I have bought an iPad mini and has reload my data to it from the old iPad2 same result.
    So it must be a software issue.
    Any ideas?

    I'm not entirely convinced that your problem is the same as mine, but it may be.
    My problem is that sounds and general media functions fail to work. Things don't just suddenly cut out during usage - they just don't work when I go to use them.
    Over the last couple of weeks while I've been on Christmas break the problem has not arisen, whereas previously it was recurring every few days. At this stage I'm becoming increasingly convinced that it's because the problem is being triggered by a particular app that I would normally use routinely, but haven't needed to use over the last couple of weeks. The most likely culprit is Nightstand which is an alarm clock app, and my theory is that a bug in the app is causing it to hog the media API and hence prevent any other app from playing media. I'm going to start using this app again next week and if the problem starts occurring again then I think I've cracked it.
    When you experience the problem yourself you may want to check which apps you've been using recently (the home button is an easy way to check this) and temporarily discontinue the use of particular apps to see if the problem goes away. If it is a rogue app causing your problem then you should be able to identify it by process of elimination.

  • Messagebox that displays a different randum number every 2 secs

    well im having trouble with putting a messagebox that displays a different randum number every 2 secs and closes with a close button. it goes in the print menu option of this simple text editor,you shoud also be able to work in the background while this message box is been displayed.
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.rtf.*;
    import javax.swing.event.*;
    import javax.swing.filechooser.*;
    import javax.swing.undo.*;
    import java.util.Timer;
    import java.util.TimerTask;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import java.beans.*;
      -------------------| Simple Text Editor example application using Java 1.3 with Swing |--------------
    public class SimpleTextEditor extends JFrame
            private JTextPane textpane;
            private JMenuBar mb;
            private JFileChooser chooser,picChooser;
            private Hashtable actions;
            private JPopupMenu popup;
            private JMenuItem exit, newDoc, save, open, saveAs,print;
            private About ab;
            private StyledEditorKit edkit;
            private RTFEditorKit rtfkit;
            private DefaultStyledDocument doc;
            private MyDocumentListener doclistener;
           private MyUndoableEditListener undolistener;
             //Useful variables
            private String filename="untitled1.txt",filetype=".txt";
            private File thisfile;
            protected String FileFormats[],FileDescriptions[],PicFileFormats[],PicFileDescriptions[];
            protected boolean DocumentIsUnedited=true, DocumentIsSaved=false;
            public static int SQUARE=0,TRIANGLE=1,CIRCLE=2;
            public String newline="\n";
            protected UndoManager undo ;
            protected UndoAction undoAction;
            protected RedoAction redoAction;
            // These are the actions used in the menus and on the toolbar
            protected Action bold, italic, underline, alignleft, alignright, aligncentre;
            protected Action spellchecker, alignjustify, more, cut, copy, paste, tools[];
            public SimpleTextEditor()
                    super("SimpleTextEditor - untitled1.rtf");
                    this.setLocation(200,200);
                    this.setIconImage(getMyIcon("Icon.gif").getImage());
                    getContentPane().setLayout(new BorderLayout());
                    undo = new UndoManager();
                    //Set up the file formats and file choosers etc
                    FileFormats = new String[]{".rtf",".txt",".java",".bat"};
                    FileDescriptions = new String[]{"Rich Text Format Files","Text Files","Java Source Files","DOS Batch Files"};
                    PicFileFormats = new String[]{".gif",".bmp",".jpg"};
                    PicFileDescriptions = new String[]{"Gif Images","Bitmap Images","JPEG Images"};
                    chooser = new JFileChooser();
                    picChooser = new JFileChooser();
                    picChooser.setAccessory(new ImagePreview(picChooser));
                    javax.swing.filechooser.FileFilter defaultFilter = new SimpleFilter(FileFormats[0],FileDescriptions[0]);
                    javax.swing.filechooser.FileFilter defaultPicFilter = new SimpleFilter(PicFileFormats[0],PicFileDescriptions[0]);
                    for(int i=1;i<FileFormats.length;i++){
                            chooser.addChoosableFileFilter(new SimpleFilter(FileFormats,FileDescriptions[i]));
    for(int i=1;i<PicFileFormats.length;i++){
    picChooser.addChoosableFileFilter(new SimpleFilter(PicFileFormats[i],PicFileDescriptions[i]));
    chooser.setFileFilter(defaultFilter);
    picChooser.setFileFilter(defaultPicFilter);
    File working = new File("C:/Documents");
    if(!working.exists()){
    working= new File("C:/MyDocuments");
    if(!working.exists()) working = new File("C:/");
    if(working.exists()) {
    chooser.setCurrentDirectory(working);
    picChooser.setCurrentDirectory(working);
    // Set up Document object and Editor kits
    doc = new DefaultStyledDocument();
    edkit = new StyledEditorKit();
    rtfkit = new RTFEditorKit();
    // Set up Listener objects
    doclistener= new MyDocumentListener();
    undolistener= new MyUndoableEditListener();
    doc.addDocumentListener(doclistener);
    doc.addUndoableEditListener(undolistener);
    //Set up main GUI content
    textpane=new JTextPane(doc);
    textpane.setPreferredSize(new Dimension(400,400));
    textpane.setMinimumSize(new Dimension(400,400));
    JScrollPane scroller=new JScrollPane(textpane);
    scroller.setPreferredSize(new Dimension(400,400));
    mb=new JMenuBar(); // Create a menu bar
    JMenu File=new JMenu("File");
    JMenu Help=new JMenu("Help");
    //Sort out Actions etc
    createActionTable(textpane);
    createToolbarActions();
    JMenu Style=createStyleMenu();
    undoAction = new UndoAction();
    redoAction = new RedoAction();
    //Create Style, Edit and Format menus + Toolbar
    JMenu Edit=createEditMenu();
    JMenu Format=createFormatMenu();
    JMenu Insert = createInsertMenu();
    JToolBar toolbar = createToolbar();
    getContentPane().add("North",toolbar);
    // set up main menu items with ActionListeners
    newDoc=new JMenuItem("New");
    newDoc.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    newDoc();
    exit=new JMenuItem("Exit");
    exit.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    exit();
    print=new JMenuItem("Print");
    print.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    print();
    save=new JMenuItem("Save");
    save.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    save();
    saveAs=new JMenuItem("Save As...");
    saveAs.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    saveas();
    open=new JMenuItem("Open...");
    open.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    open();
    JMenuItem about=new JMenuItem("About");
    about.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    ab=new About(SimpleTextEditor.this);
    ab.show();
    ab.setLocation(400,300);
    // Create the popup menu
    popup = createEditMenu().getPopupMenu();
    popup.addSeparator();
    popup.add(createStyleMenu());
    popup.add(createFormatMenu());
    textpane.add(popup);
    // set up Help and File menus
    Help.add(about);
    File.add(newDoc);
    File.add(open);
    File.add(print);
    File.add(save);
    File.add(saveAs);
    File.addSeparator();
    File.add(exit);
    // add the menus to the menubar
    mb.add(File);
    mb.add(Edit);
    mb.add(Format);
    mb.add(Style);
    mb.add(Insert);
    mb.add(Help);
    this.setJMenuBar(mb);
    getContentPane().add("Center",scroller);
    // Add mouse Listener to the textpane for popup events
    textpane.addMouseListener(new MouseAdapter(){
    public void mousePressed(MouseEvent e)
    if(e.isPopupTrigger())
    popup.show(textpane, e.getX(), e.getY());
    e.consume();
    public void mouseReleased(MouseEvent e)
    if(e.isPopupTrigger())
    popup.show(textpane, e.getX(), e.getY());
    e.consume();
    //-----------------| Main active methods |------------------
    public void exit()// Main Exit method
    if(DocumentIsUnedited){//Check that document is saved/unedited etc
    dispose();
    setVisible(false);
    System.exit(0);
    else{
    switch(showNotSavedDialog("Exit")){
    case JOptionPane.YES_OPTION: save(); exit(); break;
    case JOptionPane.NO_OPTION: DocumentIsUnedited=true;exit();break;
    case JOptionPane.CANCEL_OPTION: break;
    public void newDoc()//Method to create new documents
    if(DocumentIsUnedited){
    initDoc();
    filename="untitled.txt";
    filetype=".txt";
    resetTitle();
    else
    switch(showNotSavedDialog("New Document")){
    case JOptionPane.YES_OPTION: save(); newDoc(); break;
    case JOptionPane.NO_OPTION: DocumentIsUnedited=true;newDoc();break;
    case JOptionPane.CANCEL_OPTION: break;
    private void initDoc()// Helper method to initialize a new document
    doc = null;
    doc = (DefaultStyledDocument)edkit.createDefaultDocument();
    doc.addDocumentListener(doclistener);
    textpane.setStyledDocument(doc);
    public void print()
    new TimerTestFrame();
    class TimerTestFrame extends JFrame
    Timer timer;
    TimerTestFrame()
    super();
    timer = new Timer(true);
    TimerTask task = new MessageTimer(TimerTestFrame.this);
    timer.schedule(task,2000,2000);
    class MessageTimer extends TimerTask
    Component parent;
    public MessageTimer(Component parent)
    this.parent = parent;
    public void run()
    int randnum = (1 +(int)(Math.random()*10));
    JOptionPane.showMessageDialog(parent,""+randnum,"Timer Message",JOptionPane.INFORMATION_MESSAGE);
    public void saveas()
    int n = chooser.showSaveDialog(this);
    if(n==0){
    filename=chooser.getSelectedFile().getName();
    boolean ext = false;
    setFiletype();
    thisfile = new File(chooser.getCurrentDirectory(),filename);
    DocumentIsSaved=true;
    save();
    resetTitle();
    repaint();
    public void save()// Save method. Used by "Save As..." as well
    if( DocumentIsSaved)
    try
    FileOutputStream out = new FileOutputStream(thisfile);
    if((filetype.equals(".rtf"))||(filetype.equals(".doc"))){
    rtfkit.write(out,doc,0,doc.getLength());
    else edkit.write(out,doc,0,doc.getLength());
    catch(Exception e)
    System.out.println(""+e.getMessage()+"");
    DocumentIsUnedited=true;
    else saveas();
    public void open()// Find a file and read it into the document
    if(DocumentIsUnedited){
    int n = chooser.showOpenDialog(this); // get the outcome of the dialog
    if(n==0){
    File file = chooser.getSelectedFile();
    filename=chooser.getName(file);
    setFiletype();
    resetTitle();
    initDoc();
    try
    FileInputStream in= new FileInputStream(file);
    if(filetype.equals(".rtf")){
    rtfkit.read(in,doc,0);
    edkit.read(in,doc,0);
    catch(Exception e)
    System.out.println(""+e.getMessage()+"");
    thisfile= new File(chooser.getCurrentDirectory(),chooser.getSelectedFile().getName());
    DocumentIsUnedited=true;
    DocumentIsSaved=true;
    resetTitle();
    repaint();
    else
    switch(showNotSavedDialog("Open")){
    case JOptionPane.YES_OPTION: save(); open(); break;
    case JOptionPane.NO_OPTION: DocumentIsUnedited=true; open(); break;
    case JOptionPane.CANCEL_OPTION: break;
    private void setFiletype()// Helper method to get the filetype of saved/opened documents
    filetype=null;
    for(int i=0;i<FileFormats.length;i++){
    if(filename.toLowerCase().endsWith(FileFormats[i])) filetype = FileFormats[i];
    else{
    for(i=0;i<filename.length();i++){
    if(filename.toLowerCase().charAt(i)=='.')
    filetype=filename.substring(i);
    if(filetype==null) filetype=".txt";
    private void resetTitle()
    this.setTitle("SimpleTextEditor - "+filename);
    private ImageIcon getMyIcon(String filename){
    ImageIcon pic = new ImageIcon("Images/"+filename);
    return pic;
    private int showNotSavedDialog(String title)// Helper method to create "Save? Yes/No/Cancel" dialogs
    int n = JOptionPane.showConfirmDialog(this,"The last document has not been saved. \nDo you want to save it first?",
    title,
    JOptionPane.YES_NO_CANCEL_OPTION,
    JOptionPane.QUESTION_MESSAGE);
    return n;
    //-----------------| Listeners and Helper classes |----------------
    protected class MyDocumentListener implements DocumentListener
    public void insertUpdate(DocumentEvent e) {
    SimpleTextEditor.this.DocumentIsUnedited=false;
    public void removeUpdate(DocumentEvent e) {
    SimpleTextEditor.this.DocumentIsUnedited=false;
    public void changedUpdate(DocumentEvent e) {
    SimpleTextEditor.this.DocumentIsUnedited=false;
    protected class MyUndoableEditListener implements UndoableEditListener {
    public void undoableEditHappened(UndoableEditEvent e) {
    //Remember the edit and update the menus.
    undo.addEdit(e.getEdit());
    undoAction.updateUndoState();
    redoAction.updateRedoState();
    //Helper class for FileFilter, allows a description to be assigned to a filetype
    protected class SimpleFilter extends javax.swing.filechooser.FileFilter
    String type,des;
    public SimpleFilter(String type, String des)
    this.des=des;
    this.type=type;
    public boolean accept(File f){
    if(f.isDirectory())return true;
    else{
    if(f.getName().toLowerCase().endsWith(type)) return true;
    else return false;
    public String getDescription(){
    return des;
    //------------| Methods to help create menus and toolbar |--------------
    protected JMenu createStyleMenu()
    JMenu menu = new JMenu("Style");
    menu.add(bold);
    menu.add(italic);
    menu.add(underline);
    menu.addSeparator();
    menu.add(new StyledEditorKit.FontSizeAction("12", 12));
    menu.add(new StyledEditorKit.FontSizeAction("14", 14));
    menu.add(new StyledEditorKit.FontSizeAction("18", 18));
    menu.addSeparator();
    menu.add(new StyledEditorKit.FontFamilyAction("Serif","Serif"));
    menu.add(new StyledEditorKit.FontFamilyAction("SansSerif","SansSerif"));
    menu.addSeparator();
    Action red = new StyledEditorKit.ForegroundAction("Red", new Color(255,0,0));
    red.putValue(Action.SMALL_ICON,getMyIcon("red.gif"));
    menu.add(red);
    Action green = new StyledEditorKit.ForegroundAction("Green", new Color(0,150,0));
    green.putValue(Action.SMALL_ICON,getMyIcon("green.gif"));
    menu.add(green);
    Action blue = new StyledEditorKit.ForegroundAction("Blue", new Color(0,50,150));
    blue.putValue(Action.SMALL_ICON,getMyIcon("blue.gif"));
    menu.add(blue);
    Action black = new StyledEditorKit.ForegroundAction("Black", new Color(0,0,0));
    black.putValue(Action.SMALL_ICON,getMyIcon("black.gif"));
    menu.add(black);
    menu.add(more);
    return menu;
    protected JMenu createEditMenu() {
    JMenu menu = new JMenu("Edit");
    menu.add(undoAction);
    menu.add(redoAction);
    menu.addSeparator();
    menu.add(cut);
    menu.add(copy);
    menu.add(paste);
    menu.addSeparator();
    Action selectall=getActionByName(DefaultEditorKit.selectAllAction);
    selectall.putValue(Action.NAME, "Select All");
    menu.add(selectall);
    return menu;
    protected JMenu createFormatMenu(){
    JMenu menu = new JMenu("Format");
    menu.add(spellchecker);
    menu.add(alignleft);
    menu.add(alignright);
    menu.add(aligncentre);
    menu.add(alignjustify);
    return menu;
    protected JMenu createInsertMenu(){
    JMenu menu = new JMenu("Insert");
    Action insertimage = new InsertImageAction(this);
    menu.add(insertimage);
    Action insertdate = new InsertDateAction();
    menu.add(insertdate);
    Action insertline = new InsertLineAction();
    menu.add(insertline);
    JMenu bullets =new JMenu("Bullet Points");
    bullets.add(new InsertBulletAction(CIRCLE,"Circle"));
    bullets.add(new InsertBulletAction(TRIANGLE,"Triangle"));
    bullets.add(new InsertBulletAction(SQUARE,"Square"));
    menu.add(bullets);
    return menu;
    public JToolBar createToolbar(){
    JToolBar bar= new JToolBar();
    JButton newbutton=new JButton(getMyIcon("new.gif"));
    newbutton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    newDoc();
    bar.add(newbutton);
    JButton savebutton=new JButton(getMyIcon("save.gif"));
    savebutton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    save();
    bar.add(savebutton);
    JButton openbutton=new JButton(getMyIcon("open.gif"));
    openbutton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    open();
    bar.add(openbutton);
    bar.addSeparator();
    for(int i=0;i<tools.length;i++){
    JButton button=new JButton();
    button.setAction(tools[i]);
    button.setIcon(getMyIcon(tools[i].getValue(Action.NAME)+".gif"));
    button.setText("");
    bar.add(button);
    if((i==2)||(i==6))bar.addSeparator();
    return bar;
    public void createToolbarActions(){
    bold = new StyledEditorKit.BoldAction();
    bold.putValue(Action.NAME, "Bold");
    italic = new StyledEditorKit.ItalicAction();
    italic.putValue(Action.NAME, "Italic");
    underline = new StyledEditorKit.UnderlineAction();
    underline.putValue(Action.NAME, "Underline");
    more = new MoreColorsAction();
    cut = getActionByName(DefaultEditorKit.cutAction);
    cut.putValue(Action.NAME, "Cut");
    copy = getActionByName(DefaultEditorKit.copyAction);
    copy.putValue(Action.NAME, "Copy");
    paste = getActionByName(DefaultEditorKit.pasteAction);
    paste.putValue(Action.NAME, "Paste");
    alignleft = new StyledEditorKit.AlignmentAction("Left Justify",StyleConstants.ALIGN_LEFT);
    alignright = new StyledEditorKit.AlignmentAction("Right Justify",StyleConstants.ALIGN_RIGHT);
    aligncentre = new StyledEditorKit.AlignmentAction("Align Centre",StyleConstants.ALIGN_CENTER);
    alignjustify = new StyledEditorKit.AlignmentAction("Fully Justify",StyleConstants.ALIGN_JUSTIFIED);
    spellchecker = new StyledEditorKit.AlignmentAction("Spell Checker",StyleConstants.ALIGN_JUSTIFIED);
    tools = new Action[]{  cut, copy, paste, bold, italic, underline, more, alignleft, alignright, aligncentre, alignjustify, spellchecker };
    // helper methods to enable menu creators to get their actions by name
    private void createActionTable(JTextComponent textComponent) {
    actions = new Hashtable();
    Action[] actionsArray = textComponent.getActions();
    for (int i = 0; i < actionsArray.length; i++) {
    Action a = actionsArray[i];
    actions.put(a.getValue(Action.NAME), a);
    private Action getActionByName(String name) {
    return (Action)(actions.get(name));
    //----------------| Custom Actions |--------------------
    class InsertImageAction extends AbstractAction {
    protected SimpleTextEditor parent;
    public InsertImageAction(SimpleTextEditor parent){
    super("Image...");
    this.parent=parent;
    public void actionPerformed(ActionEvent e) {
    int n = parent.picChooser.showOpenDialog(parent);
    if(n==0){
    String filename=picChooser.getSelectedFile().getName();
    File file = new File(picChooser.getCurrentDirectory(),filename);
    Icon pic = new ImageIcon(file.getAbsolutePath());
    textpane.insertIcon(pic);
    SimpleTextEditor.this.repaint();
    class InsertDateAction extends AbstractAction {
    public InsertDateAction(){
    super("Date");
    public void actionPerformed(ActionEvent ble) {
    Calendar c= Calendar.getInstance();
    String[] months= new String[]{"01","02","03","04","05","06","07","08","09","10","11","12"};
    textpane.replaceSelection(c.get(c.DAY_OF_MONTH)+"/"+months[c.get(c.MONTH)]+"/"+c.get(c.YEAR));
    class InsertLineAction extends AbstractAction {
    public InsertLineAction(){
    super("Horizontal line");
    public void actionPerformed(ActionEvent e) {
    Icon pic = new ImageIcon("Images/line.gif");
    textpane.insertIcon(pic);
    class InsertBulletAction extends AbstractAction {
    protected int type;
    protected String filenames[] = new String[]{"square.gif","triangle.gif","circle.gif"};
    public InsertBulletAction(int type,String name){
    super(name);
    this.type=type;
    this.putValue(SMALL_ICON,new ImageIcon("Images/"+filenames[type]));
    public void actionPerformed(ActionEvent e) {
    Icon pic = new ImageIcon("Images/"+filenames[type]);
    textpane.insertIcon(pic);
    textpane.replaceSelection(" ");
    class MoreColorsAction extends AbstractAction {
    public MoreColorsAction(){
    super("More Colors");
    public void actionPerformed(ActionEvent e){
    AttributeSet as = textpane.getCharacterAttributes();
    SimpleAttributeSet sas = new SimpleAttributeSet(as);
    Color newColor = JColorChooser.showDialog(
    SimpleTextEditor.this,
    "C

    Here you go guys:
    Peace!
    import javax.swing.*;
    import javax.swing.Timer;
    import javax.swing.border.BevelBorder;
    import javax.swing.text.*;
    import javax.swing.text.rtf.*;
    import javax.swing.event.*;
    import javax.swing.filechooser.*;
    import javax.swing.undo.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import java.beans.*;
      -------------------| Simple Text Editor example application using Java 1.3 with Swing |--------------
    public class SimpleTextEditor extends JFrame
        private JTextPane textpane;
        private JMenuBar mb;
        private JFileChooser chooser,picChooser;
        private Hashtable actions;
        private JPopupMenu popup;
        private JMenuItem exit, newDoc, save, open, saveAs,print;
        private About ab;
        private StyledEditorKit edkit;
        private RTFEditorKit rtfkit;
        private DefaultStyledDocument doc;
        private MyDocumentListener doclistener;
        private MyUndoableEditListener undolistener;
        //Useful variables
        private String filename = "untitled1.txt",filetype = ".txt";
        private File thisfile;
        protected String FileFormats[],FileDescriptions[],PicFileFormats[],PicFileDescriptions[];
        protected boolean DocumentIsUnedited = true, DocumentIsSaved = false;
        public static int SQUARE = 0,TRIANGLE = 1,CIRCLE = 2;
        public String newline = "\n";
        protected UndoManager undo;
        protected UndoAction undoAction;
        protected RedoAction redoAction;
        // These are the actions used in the menus and on the toolbar
        protected Action bold, italic, underline, alignleft, alignright, aligncentre;
        protected Action spellchecker, alignjustify, more, cut, copy, paste, tools[];
        public SimpleTextEditor()
            super("SimpleTextEditor - untitled1.rtf");
            this.setLocation(200, 200);
            this.setIconImage(getMyIcon("Icon.gif").getImage());
            getContentPane().setLayout(new BorderLayout());
            undo = new UndoManager();
            //Set up the file formats and file choosers etc
            FileFormats = new String[]{".rtf", ".txt", ".java", ".bat"};
            FileDescriptions = new String[]{"Rich Text Format Files", "Text Files", "Java Source Files", "DOS Batch Files"};
            PicFileFormats = new String[]{".gif", ".bmp", ".jpg"};
            PicFileDescriptions = new String[]{"Gif Images", "Bitmap Images", "JPEG Images"};
            chooser = new JFileChooser();
            picChooser = new JFileChooser();
            picChooser.setAccessory(new ImagePreview(picChooser));
            javax.swing.filechooser.FileFilter defaultFilter = new SimpleFilter(FileFormats[0], FileDescriptions[0]);
            javax.swing.filechooser.FileFilter defaultPicFilter = new SimpleFilter(PicFileFormats[0], PicFileDescriptions[0]);
            for (int i = 1; i < FileFormats.length; i++)
                chooser.addChoosableFileFilter(new SimpleFilter(FileFormats, FileDescriptions[i]));
    for (int i = 1; i < PicFileFormats.length; i++)
    picChooser.addChoosableFileFilter(new SimpleFilter(PicFileFormats[i], PicFileDescriptions[i]));
    chooser.setFileFilter(defaultFilter);
    picChooser.setFileFilter(defaultPicFilter);
    File working = new File("C:/Documents");
    if (!working.exists())
    working = new File("C:/MyDocuments");
    if (!working.exists()) working = new File("C:/");
    if (working.exists())
    chooser.setCurrentDirectory(working);
    picChooser.setCurrentDirectory(working);
    // Set up Document object and Editor kits
    doc = new DefaultStyledDocument();
    edkit = new StyledEditorKit();
    rtfkit = new RTFEditorKit();
    // Set up Listener objects
    doclistener = new MyDocumentListener();
    undolistener = new MyUndoableEditListener();
    doc.addDocumentListener(doclistener);
    doc.addUndoableEditListener(undolistener);
    //Set up main GUI content
    textpane = new JTextPane(doc);
    textpane.setPreferredSize(new Dimension(400, 400));
    textpane.setMinimumSize(new Dimension(400, 400));
    JScrollPane scroller = new JScrollPane(textpane);
    scroller.setPreferredSize(new Dimension(400, 400));
    mb = new JMenuBar(); // Create a menu bar
    JMenu File = new JMenu("File");
    JMenu Help = new JMenu("Help");
    //Sort out Actions etc
    createActionTable(textpane);
    createToolbarActions();
    JMenu Style = createStyleMenu();
    undoAction = new UndoAction();
    redoAction = new RedoAction();
    //Create Style, Edit and Format menus + Toolbar
    JMenu Edit = createEditMenu();
    JMenu Format = createFormatMenu();
    JMenu Insert = createInsertMenu();
    JToolBar toolbar = createToolbar();
    getContentPane().add("North", toolbar);
    // set up main menu items with ActionListeners
    newDoc = new JMenuItem("New");
    newDoc.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    newDoc();
    exit = new JMenuItem("Exit");
    exit.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    exit();
    print = new JMenuItem("Print");
    print.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    print();
    save = new JMenuItem("Save");
    save.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    save();
    saveAs = new JMenuItem("Save As...");
    saveAs.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    saveas();
    open = new JMenuItem("Open...");
    open.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    open();
    JMenuItem about = new JMenuItem("About");
    about.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    ab = new About(SimpleTextEditor.this);
    ab.show();
    ab.setLocation(400, 300);
    // Create the popup menu
    popup = createEditMenu().getPopupMenu();
    popup.addSeparator();
    popup.add(createStyleMenu());
    popup.add(createFormatMenu());
    textpane.add(popup);
    // set up Help and File menus
    Help.add(about);
    File.add(newDoc);
    File.add(open);
    File.add(print);
    File.add(save);
    File.add(saveAs);
    File.addSeparator();
    File.add(exit);
    // add the menus to the menubar
    mb.add(File);
    mb.add(Edit);
    mb.add(Format);
    mb.add(Style);
    mb.add(Insert);
    mb.add(Help);
    this.setJMenuBar(mb);
    getContentPane().add("Center", scroller);
    // Add mouse Listener to the textpane for popup events
    textpane.addMouseListener(new MouseAdapter()
    public void mousePressed(MouseEvent e)
    if (e.isPopupTrigger())
    popup.show(textpane, e.getX(), e.getY());
    e.consume();
    public void mouseReleased(MouseEvent e)
    if (e.isPopupTrigger())
    popup.show(textpane, e.getX(), e.getY());
    e.consume();
    //-----------------| Main active methods |------------------
    public void exit()// Main Exit method
    if (DocumentIsUnedited)
    {//Check that document is saved/unedited etc
    dispose();
    setVisible(false);
    System.exit(0);
    else
    switch (showNotSavedDialog("Exit"))
    case JOptionPane.YES_OPTION:
    save();
    exit();
    break;
    case JOptionPane.NO_OPTION:
    DocumentIsUnedited = true;
    exit();
    break;
    case JOptionPane.CANCEL_OPTION:
    break;
    public void newDoc()//Method to create new documents
    if (DocumentIsUnedited)
    initDoc();
    filename = "untitled.txt";
    filetype = ".txt";
    resetTitle();
    else
    switch (showNotSavedDialog("New Document"))
    case JOptionPane.YES_OPTION:
    save();
    newDoc();
    break;
    case JOptionPane.NO_OPTION:
    DocumentIsUnedited = true;
    newDoc();
    break;
    case JOptionPane.CANCEL_OPTION:
    break;
    private void initDoc()// Helper method to initialize a new document
    doc = null;
    doc = (DefaultStyledDocument) edkit.createDefaultDocument();
    doc.addDocumentListener(doclistener);
    textpane.setStyledDocument(doc);
    public void print()
    new TimerTestDialog(this);
    class TimerTestDialog extends JDialog
    TimerTestDialog(Frame parent)
    super(parent);
    setLocationRelativeTo(parent);
    setupDialog();
    setModal(false); // this will allow you to do still stuff with the main frame
    * sorry, using a Timer instead of your original TimerTask - it's simpler
    Timer t = new Timer(2000, ticker);
    t.start();
    private void setupDialog()
    Container c = getContentPane();
    c.setLayout(new BorderLayout());
    c.add(getDisplayPanel(), BorderLayout.CENTER);
    c.add(getButtonPanel(), BorderLayout.SOUTH);
    setSize(300, 150);
    setVisible(true);
    private Component getDisplayPanel()
    label = new JLabel("---", JLabel.CENTER);
    label.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
    JPanel panel = new JPanel(new BorderLayout());
    panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    JPanel backing = new JPanel(new BorderLayout());
    backing.add(label, BorderLayout.NORTH); // this will ensure the label doesn't go all tall
    panel.add(backing, BorderLayout.CENTER);
    return panel;
    private Component getButtonPanel()
    JPanel panel = new JPanel(new BorderLayout());
    panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    JPanel backing = new JPanel(new BorderLayout());
    JButton closeButton = new JButton("close");
    closeButton.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    dispose();
    backing.add(closeButton, BorderLayout.NORTH);
    panel.add(backing, BorderLayout.EAST);
    return panel;
    private ActionListener ticker = new ActionListener()
    public void actionPerformed(ActionEvent e)
    label.setText(String.valueOf(getRandomNumber()));
    private int getRandomNumber()
    return r.nextInt(10) + 1; // shift from 0-9 to 1-10
    private JLabel label;
    * NOTE - this is the best way to use random stuff in java. if you use instance members
    * you can sometimes get the same result each time. not really sure how that works but
    * i've seen it happen
    private static Random r = new Random();
    public void saveas()
    int n = chooser.showSaveDialog(this);
    if (n == 0)
    filename = chooser.getSelectedFile().getName();
    boolean ext = false;
    setFiletype();
    thisfile = new File(chooser.getCurrentDirectory(), filename);
    DocumentIsSaved = true;
    save();
    resetTitle();
    repaint();
    public void save()// Save method. Used by "Save As..." as well
    if (DocumentIsSaved)
    try
    FileOutputStream out = new FileOutputStream(thisfile);
    if ((filetype.equals(".rtf")) || (filetype.equals(".doc")))
    rtfkit.write(out, doc, 0, doc.getLength());
    else
    edkit.write(out, doc, 0, doc.getLength());
    catch (Exception e)
    System.out.println("" + e.getMessage() + "");
    DocumentIsUnedited = true;
    else
    saveas();
    public void open()// Find a file and read it into the document
    if (DocumentIsUnedited)
    int n = chooser.showOpenDialog(this); // get the outcome of the dialog
    if (n == 0)
    File file = chooser.getSelectedFile();
    filename = chooser.getName(file);
    setFiletype();
    resetTitle();
    initDoc();
    try
    FileInputStream in = new FileInputStream(file);
    if (filetype.equals(".rtf"))
    rtfkit.read(in, doc, 0);
    edkit.read(in, doc, 0);
    catch (Exception e)
    System.out.println("" + e.getMessage() + "");
    thisfile = new File(chooser.getCurrentDirectory(), chooser.getSelectedFile().getName());
    DocumentIsUnedited = true;
    DocumentIsSaved = true;
    resetTitle();
    repaint();
    else
    switch (showNotSavedDialog("Open"))
    case JOptionPane.YES_OPTION:
    save();
    open();
    break;
    case JOptionPane.NO_OPTION:
    DocumentIsUnedited = true;
    open();
    break;
    case JOptionPane.CANCEL_OPTION:
    break;
    private void setFiletype()// Helper method to get the filetype of saved/opened documents
    filetype = null;
    for (int i = 0; i < FileFormats.length; i++)
    if (filename.toLowerCase().endsWith(FileFormats[i]))
    filetype = FileFormats[i];
    else
    for (i = 0; i < filename.length(); i++)
    if (filename.toLowerCase().charAt(i) == '.')
    filetype = filename.substring(i);
    if (filetype == null) filetype = ".txt";
    private void resetTitle()
    this.setTitle("SimpleTextEditor - " + filename);
    private ImageIcon getMyIcon(String filename)
    ImageIcon pic = new ImageIcon("Images/" + filename);
    return pic;
    private int showNotSavedDialog(String title)// Helper method to create "Save? Yes/No/Cancel" dialogs
    int n = JOptionPane.showConfirmDialog(this, "The last document has not been saved. \nDo you want to save it first?",
    title,
    JOptionPane.YES_NO_CANCEL_OPTION,
    JOptionPane.QUESTION_MESSAGE);
    return n;
    //-----------------| Listeners and Helper classes |----------------
    protected class MyDocumentListener implements DocumentListener
    public void insertUpdate(DocumentEvent e)
    SimpleTextEditor.this.DocumentIsUnedited = false;
    public void removeUpdate(DocumentEvent e)
    SimpleTextEditor.this.DocumentIsUnedited = false;
    public void changedUpdate(DocumentEvent e)
    SimpleTextEditor.this.DocumentIsUnedited = false;
    protected class MyUndoableEditListener implements UndoableEditListener
    public void undoableEditHappened(UndoableEditEvent e)
    //Remember the edit and update the menus.
    undo.addEdit(e.getEdit());
    undoAction.updateUndoState();
    redoAction.updateRedoState();
    //Helper class for FileFilter, allows a description to be assigned to a filetype
    protected class SimpleFilter extends javax.swing.filechooser.FileFilter
    String type,des;
    public SimpleFilter(String type, String des)
    this.des = des;
    this.type = type;
    public boolean accept(File f)
    if (f.isDirectory())
    return true;
    else
    if (f.getName().toLowerCase().endsWith(type))
    return true;
    else
    return false;
    public String getDescription()
    return des;
    //------------| Methods to help create menus and toolbar |--------------
    protected JMenu createStyleMenu()
    JMenu menu = new JMenu("Style");
    menu.add(bold);
    menu.add(italic);
    menu.add(underline);
    menu.addSeparator();
    menu.add(new StyledEditorKit.FontSizeAction("12", 12));
    menu.add(new StyledEditorKit.FontSizeAction("14", 14));
    menu.add(new StyledEditorKit.FontSizeAction("18", 18));
    menu.addSeparator();
    menu.add(new StyledEditorKit.FontFamilyAction("Serif", "Serif"));
    menu.add(new StyledEditorKit.FontFamilyAction("SansSerif", "SansSerif"));
    menu.addSeparator();
    Action red = new StyledEditorKit.ForegroundAction("Red", new Color(255, 0, 0));
    red.putValue(Action.SMALL_ICON, getMyIcon("red.gif"));
    menu.add(red);
    Action green = new StyledEditorKit.ForegroundAction("Green", new Color(0, 150, 0));
    green.putValue(Action.SMALL_ICON, getMyIcon("green.gif"));
    menu.add(green);
    Action blue = new StyledEditorKit.ForegroundAction("Blue", new Color(0, 50, 150));
    blue.putValue(Action.SMALL_ICON, getMyIcon("blue.gif"));
    menu.add(blue);
    Action black = new StyledEditorKit.ForegroundAction("Black", new Color(0, 0, 0));
    black.putValue(Action.SMALL_ICON, getMyIcon("black.gif"));
    menu.add(black);
    menu.add(more);
    return menu;
    protected JMenu createEditMenu()
    JMenu menu = new JMenu("Edit");
    menu.add(undoAction);
    menu.add(redoAction);
    menu.addSeparator();
    menu.add(cut);
    menu.add(copy);
    menu.add(paste);
    menu.addSeparator();
    Action selectall = getActionByName(DefaultEditorKit.selectAllAction);
    selectall.putValue(Action.NAME, "Select All");
    menu.add(selectall);
    return menu;
    protected JMenu createFormatMenu()
    JMenu menu = new JMenu("Format");
    menu.add(spellchecker);
    menu.add(alignleft);
    menu.add(alignright);
    menu.add(aligncentre);
    menu.add(alignjustify);
    return menu;
    protected JMenu createInsertMenu()
    JMenu menu = new JMenu("Insert");
    Action insertimage = new InsertImageAction(this);
    menu.add(insertimage);
    Action insertdate = new InsertDateAction();
    menu.add(insertdate);
    Action insertline = new InsertLineAction();
    menu.add(insertline);
    JMenu bullets = new JMenu("Bullet Points");
    bullets.add(new InsertBulletAction(CIRCLE, "Circle"));
    bullets.add(new InsertBulletAction(TRIANGLE, "Triangle"));
    bullets.add(new InsertBulletAction(SQUARE, "Square"));
    menu.add(bullets);
    return menu;
    public JToolBar createToolbar()
    JToolBar bar = new JToolBar();
    JButton newbutton = new JButton(getMyIcon("new.gif"));
    newbutton.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    newDoc();
    bar.add(newbutton);
    JButton savebutton = new JButton(getMyIcon("save.gif"));
    savebutton.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    save();
    bar.add(savebutton);
    JButton openbutton = new JButton(getMyIcon("open.gif"));
    openbutton.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    open();
    bar.add(openbutton);
    bar.addSeparator();
    for (int i = 0; i < tools.length; i++)
    JButton button = new JButton();
    button.setAction(tools[i]);
    button.setIcon(getMyIcon(tools[i].getValue(Action.NAME) + ".gif"));
    button.setText("");
    bar.add(button);
    if ((i == 2) || (i == 6)) bar.addSeparator();
    return bar;
    public void createToolbarActions()
    bold = new StyledEditorKit.BoldAction();
    bold.putValue(Action.NAME, "Bold");
    italic = new StyledEditorKit.ItalicAction();
    italic.putValue(Action.NAME, "Italic");
    underline = new StyledEditorKit.UnderlineAction();
    underline.putValue(Action.NAME, "Underline");
    more = new MoreColorsAction();
    cut = getActionByName(DefaultEditorKit.cutAction);
    cut.putValue(Action.NAME, "Cut");
    copy = getActionByName(DefaultEditorKit.copyAction);
    copy.putValue(Action.NAME, "Copy");
    paste = getActionByName(DefaultEditorKit.pasteAction);
    paste.putValue(Action.NAME, "Paste");
    alignleft = new StyledEditorKit.AlignmentAction("Left Justify", StyleConstants.ALIGN_LEFT);
    alignright = new StyledEditorKit.AlignmentAction("Right Justify", StyleConstants.ALIGN_RIGHT);
    aligncentre = new StyledEditorKit.AlignmentAction("Align Centre", StyleConstants.ALIGN_CENTER);
    alignjustify = new StyledEditorKit.AlignmentAction("Fully Justify", StyleConstants.ALIGN_JUSTIFIED);
    spellchecker = new StyledEditorKit.AlignmentAction("Spell Checker", StyleConstants.ALIGN_JUSTIFIED);
    tools = new Action[]{cut, copy, paste, bold, italic, underline, more, alignleft, alignright, aligncentre, alignjustify, spellchecker};
    // helper methods to enable menu creators to get their actions by name
    private void createActionTable(JTextComponent textComponent)
    actions = new Hashtable();
    Action[] actionsArray = textComponent.getActions();
    for (int i = 0; i < actionsArray.length; i++)
    Action a = actionsArray[i];
    actions.put(a.getValue(Action.NAME), a);
    private Action getActionByName(String name)
    return (Action) (actions.get(name));
    //----------------| Custom Actions |--------------------
    class InsertImageAction extends AbstractAction
    protected SimpleTextEditor parent;
    public InsertImageAction(SimpleTextEditor parent)
    super("Image...");
    this.parent = parent;
    public void actionPerformed(ActionEvent e)
    int n = parent.picChooser.showOpenDialog(parent);
    if (n == 0)
    String filename = picChooser.getSelectedFile().getName();
    File file = new File(picChooser.getCurrentDirectory(), filename);
    Icon pic = new ImageIcon(file.getAbsolutePath());
    textpane.insertIcon(pic);
    SimpleTextEditor.this.repaint();
    class InsertDateAction extends AbstractAction
    public InsertDateAction()
    super("Date");
    public void actionPerformed(ActionEvent ble)
    Calendar c = Calendar.getInstance();
    String[] months = new String[]{"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"};
    textpane.replaceSelection(c.get(c.DAY_OF_MONTH) + "/" + months[c.get(c.MONTH)] + "/" + c.get(c.YEAR));
    class InsertLineAction extends AbstractAction
    public InsertLineAction()
    super("Horizontal line");
    public void actionPerformed(ActionEvent e)
    Icon pic = new ImageIcon("Images/line.gif");
    textpane.insertIcon(pic);
    class InsertBulletAction extends AbstractAction
    protected int type;
    protected String filenames[] = new String[]{"square.gif", "triangle.gif", "circle.gif"};
    public InsertBulletAction(int type, String name)
    super(name);
    this.type = type;
    this.putValue(SMALL_ICON, new ImageIcon("Images/" + filenames[type]));
    public void actionPerformed(ActionEvent e)
    Icon pic = new ImageIcon("Images/" + filenames[type]);
    textpane.insertIcon(pic);
    textpane.replaceSelection(" ");
    class MoreColorsAction extends AbstractAction
    public MoreColorsAction()
    super("More Colors");
    public void actionPerformed(ActionEvent e)
    AttributeSet as = textpane.getCharacterAttributes();
    SimpleAttributeSet sas = new SimpleAttributeSet(as);
    Color newColor = JColorChooser.showDialog(
    SimpleTextEditor.this,
    "Choose Text Color",
    doc.getForeground(as));
    if (newColor != null)
    StyleConstants.setForeground(sas, newColor);
    textpane.setCharacterAttributes(sas, true);
    SimpleTextEditor.this.repaint();
    class UndoAction extends AbstractAction
    public UndoAction()
    super("Undo");
    setEnabled(false);
    public void actionPerformed(ActionEvent e)
    try
    undo.undo();
    catch (CannotUndoException ex)
    System.out.println("Unable to undo: " + ex);
    ex.printStackTrace();
    updateUndoState();
    redoAction.updateRedoState();
    protected void updateUndoState()
    if (undo.canUndo())
    setEnabled(true);
    putValue(Action.NAME, undo.getUndoPresentationName());
    else
    setEnabled(false);
    putValue(Action.NAME, "Undo");
    class RedoAction extends AbstractAction
    public RedoAction()
    super("Redo");
    setEnabled(false);
    public void actionPerformed(ActionEvent e)
    try
    undo.redo();
    catch (CannotRedoException ex)
    System.out.println("Unable to redo: " + ex);
    ex.printStackTrace();
    updateRedoState();
    undoAction.updateUndoState();
    protected void updateRedoState()
    if (undo.canRedo())
    setEnabled(true);
    putValue(Action.NAME, undo.getRedoPresentationName());
    else
    setEnabled(false);
    putValue(Action.NAME, "Redo");
    //-------------| Very nice Image Previewer 'borrowed' from Sun's Java Tutorial
    class ImagePreview extends JComponent implements PropertyChangeListener
    ImageIcon thumbnail = null;
    File file = null;
    public ImagePreview(JFileChooser fc)
    setPreferredSize(new Dimension(100, 50));
    fc.addPropertyChangeListener(this);
    public void loadImage()
    if (file == null)
    return;
    ImageIcon tmpIcon = new ImageIcon(file.getPath());
    if (tmpIcon.getIconWidth() > 90)
    thumbnail = new ImageIcon(tmpIcon.getImage().getScaledInstance(90, -1,
    Image.SCALE_DEFAULT));
    else
    thumbnail = tmpIcon;

Maybe you are looking for

  • Unable to save ANY types of files in Elements 5.0

    Today I was working with Elements, creating a photomanipulation. This involved several layers, including a background of a beach, a horse, and some text. I've done this before with this exact same program on this exact same computer and not had too m

  • Document Splitting Function in 6.0 dectvt & reactvt

    Dear All, At our client site, some user with access to customisation, deactivated the Document Splitting by checking the Inactive Tick for the Company Code. This came to light after some days. This directly affected out Business area balance sheet. N

  • Turn off purchase History

    I want to delete SOME of the artists I purchased on my purchase history, so when I'm on my iOS device, I dont have to scroll thru all my purchases to get just the ones I want.  Is there a way to control this?  Delete a certain artist so it NEVER show

  • When sp_add_log_shipping_primary_database Creates Alert job - why sp_add_log_shipping_alert_job ?

    Hi,  sp_add_log_shipping_primary_database created two jobs : 1. Backup Job 2.Alert Job . Why do we require sp_add_log_shipping_alert_job ?  Many Thanks Chaithanya M Regards Chaithu.. If it is usefull,Mark this as Answer.

  • Mavericks and itunes 11.1.2 not synching atv1

    since upgrading to mavericks, including itunes 11.1.2, my atv1 does not work. watching shared movies takes forever to  load a movie and then freezes approx 1 minute into the movie.  Cannot not watch trails etc either. I have deleted the atv and tried