Why  do we use Swing?

Hello all,
The Java Specification tell us that AWT is different with Swing, The AWT component is heavy-weight while Swing is light-weight, and the light-weight component can be painted only when they are added into a heavy-weight window.
Can anyone tell me why??
Thx

Problem 1: more classes and object methods than you can shake a stick at. Too damn many
Yes, it's quite true that there are a lot of classes and methods. How else would you expect to get the wide range of functionality that Swing provides? In any case, you don't have to use or even know about most of them, only a small subset related to what you're doing. For example, to create a simple dialog box you need only know about JFrame and the components you'll be putting in it (JButton, etc.).
Problem 2: some inconsistencies in the methods that apply to one object do not logically apply to another similar eg: TextArea, TextPane, JEditorPane, DefaultStyledDocument.
Could you give specific examples?
Problem 3: swing was designed to look sleek, individual (with a 'I am java' stamp) and stylish too. This most certainly failed, to most its just flat, grey and boring. (Yeah, yeah, I know - the swing set that comes in the samples with 1.4 looks orgasmic)
Swing was designed to use a pluggable look & feel; you can set its appearance to one of several preinstalled sets or download one that suits your needs. For me, anyway, I don't want my applications to look "individual"; I want consistency in my user interface. I may prefer the Mac look & feel to Windows', but I would never want a Windows application to attempt to follow the Mac user interface conventions; having to switch frequently between fundamentally different user interface styles would drastically reduce my efficiency.
Problem 4: performance! Its just too damn slow.
Yes, Swing is slow compared to native user interface toolkits, but that's the price you pay for full cross-platform compatibility. I for one would never want to go back to the days of "write once, debug everywhere" that were the result of using native user interface components, which as a matter of course have many subtle (and some not-so-subtle) differences across different platforms.
I believe Swing is a great user interface toolkit, and that it's headed in the right direction. It does have many rough edges, but for its age it is quite robust. The reason we use Swing, in my opinion, is that it provides the best combination of simplicity and functionality in a free, cross-platform user interface toolkit.
Mike

Similar Messages

  • Help! File in use problem when using Swing app

    Hi. I got a program that is pretty much a JFileChooser that prints to standard output the path of the file that I've chosen. If I invoke the DOS command:
    java JFileChooserDemo, I will get the following as expected from the program:
    "You chose a file named: C:\MyJava\Book.xls".
    But if I invoke the following DOS command:
    java JFileChooserDemo > output.txt, the file "output.txt" contains the following:
    "GetModuleHandleA succeed
    LoadLibrary returns baaa0000
    You chose a file named: C:\MyJava\Book.xls"
    So, if I try to open the file or try to modify "output.txt", I get an error message stating that the file is in use.
    What's weird is that, I THINK if I have a program that DOES'NT use Swing or anything GUI-related and prints to standard output with the DOS "> outfile" command, I won't get this problem. So in other words, I can duplicate this problem with a sample Swing application that prints to standard output. Try it yourself.
    In my original program, it does have an event handler that closes the JFileChooser and its container and exits the system via "System.exit(0);", but for some reason, something still has "locked" the output.txt file. I even did the ctr+alt+del and can't find anything that would lock the output.txt file. What's even weirder is that if I run the application again, but output to a different file like "output2.txt", this file is not locked, but the "output.txt" file still is. output2.txt also don't have contain the
    "GetModuleHandleA succeed
    LoadLibrary returns baaa0000" message.
    The only way I know of that would "unlock" output.txt is to re-boot my computer.
    So it seems I have to modify my program somehow because it appears the OS still thinks output.txt file is still in use.
    Someone may think why would I invoke the java interpreter with the DOS "> outfile" command. Well, the reason being, I got a different version of the program that executes a query and I want it to create a delimited text file that contains the resultset of the query, so that I can then import it to Access, Excel, or whatever. But, because of this problem, I can't modify the query result without having to either run the application again and created another file name with the same result or re-boot. Of course, this would be silly.
    Any help in how I can modify my program or any GUI-program so that if I invoke the DOS "> outfile" command, the outfile won't be "locked" would be greatly appreciated. Thanks. If you want my program, you can e-mail me or run any sample program from the Swing Tutorial that prints to standard output and just add the " > outfile" to the java interpreter command.
    -Dan
    [email protected]

    Oops sorry, forgot to add the code. Here it is:
    BTW, can I edit posts? Oh well...
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    public class FileChooserDemo2 extends JFrame {
    static private String newline = "\n";
    public FileChooserDemo2() {
    super("FileChooserDemo2");
    //Create the log first, because the action listener
    //needs to refer to it.
    final JTextArea log = new JTextArea(5,20);
    log.setMargin(new Insets(5,5,5,5));
    log.setEditable(false);
    JScrollPane logScrollPane = new JScrollPane(log);
    JButton sendButton = new JButton("Attach...");
    sendButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    JFileChooser fc = new JFileChooser();
    fc.addChoosableFileFilter(new ImageFilter());
    fc.setFileView(new ImageFileView());
    fc.setAccessory(new ImagePreview(fc));
    int returnVal = fc.showDialog(FileChooserDemo2.this,
    "Attach");
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    File file = fc.getSelectedFile();
    /** The next 2 lines I added, the rest of the code is original taken from the Swing Tutorial **/
    System.out.println("You chose a file named: " +
                             fc.getSelectedFile().getPath());
    log.append("Attaching file: " + file.getName()
    + "." + newline);
    } else {
    log.append("Attachment cancelled by user." + newline);
    Container contentPane = getContentPane();
    contentPane.add(sendButton, BorderLayout.NORTH);
    contentPane.add(logScrollPane, BorderLayout.CENTER);
    public static void main(String[] args) {
    JFrame frame = new FileChooserDemo2();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.pack();
    frame.setVisible(true);

  • Desktop like view of files and folders using Swing

    I have an application for upload/download of files from a server. The application is developed using swing and it works perfectly. Currently, the files and folders are displayed in a table view(using jtable) in which the file/ folder will be displayed with icon and extension in each row.
    I need to display these files and folders in a desktop like view. How can I implement this?
    Anees

    Any sample demos or links? Thats why people give you links to the Swing tutorial. The hope is that you will actually look at the Table of Contents and read the tutorial before you post a question.
    Or you could even read the JList API to find a link to the tutorial.

  • Why should I use Java

    HI,
    Someone asked me why are you using Java when you can use Visual Basic.
    Well, I ask this question in this forum ?? why ...
    please leave out the portablity part
    --j                                                                                                                                                                                                                                                                                                                                                   

    Well, here is my 2 cents, as it were. I tried learning VB, and found that while it is powerful, when it comes to designing specifically for Windows systems, I found it extremely hard to understand. When I first learned Java, it didn't take me long to understand the concept and relation of classes and objects, and I was writing Swing apps in no time. With VB, it wasn't that easy. Yes, it was mostly drag and drop and add a few lines of code, but I don't like that. I like to be able to get down into the code and see why it works the way it did, and with VB, I just couldn't grasp it. But with Java, it took me no time at all to be able to understand why it worked the way it did, and because of that, I will always choose Java over any other language, except maybe Miva Script, which is a server side language used for e-commerce websites. It was another language that was easy to learn. Does this mean I'm a lazy programmer, always taking the easy way out? Probably, but if it's easy for me to learn, it's easy for me to implement.
    James

  • Why would you use JavaFX over JavaEE or JavaSE?

    Just curious why you would use FX over the others? Is it because of the GUI, and some added features, or what makes FX better?
    Also what exactly is the differences between the 3? It seems like SE is the basic, then EE is used for client-server and maybe security and such? FX seems to just have advanced GUI and stuff like that? Does anyone have a link or a list of what features are different and such?
    Thanks a lot!!!
    ~KZ
    Edited by: KonradZuse on Jul 6, 2012 8:41 AM

    KonradZuse wrote:
    I usually use swing, but I am starting a new business application for real world use, so I want it to be the best it can be. FX's Gui is great, but is it worth it to start using that right away? I also want to be able to use 3D, and as someone said you can do 2D in a 3D space, so that is basically what I need for now, but I would like to be able to do full 3D.JFX isn't exactly built to do 3D stuff right now. But neither is Java2D (the base for AWT and Swing), so nothing is different really.
    So what I really want to know is what is the differences between SE and EE?One is "Java", the other is a specification. For more information I refer to Google.

  • Why do I use my ipod as a camera when I lose precious photos even when I try to back up before an update! Selling my ipod at the first chance I get

    Why do I use my Ipod tiuch as a camera when lose precious photos of my granddaughter every time there is an operating system update? Even when I try to back up the ipod, I can't find the pics etc on my pc. It is very annoying and I am seriously considering selling my ipod because of this. No warning is given that photos will be lost. So very disappointed in aple, lost all my music last time, as well as my pics.

    Yes, using the windows photo capture application is how you get photos taken with the iPod onto your pc. You should store them there, and organize them in folders.
    Create one main photo folder. Inside that folder create additional folders to hold photos. Each folder will become an album on an iPod, iPad, or iPhone. Do not next any other folders inside the first album folder.
    Then start iTunes on your pc and connect your iPod. Select your iPod in itunes and select the Photos tab that will be ps enter. You will most likely have first find your main photos folder. Ten select to sync all photos from your pc or select only those albums you want to have on your iPod. The click on Apply or Sync. That will copy the photos to your iPod.
    If you should do something later to cause these albums to disappear from your iPod you can quickly copy them back by doing another sync.

  • Can't use Swing in my java application

    I installed J2SE 5 Update 4 on my machine and was trying my hands on creating GUI using swing. I kept getting the error message: "Package javax,swing not found in import".
    I have the statement: import javax.swing.*; in my code so I don't what to do again.
    Thanks

    I think your best bet is to try uninstalling and installing Java again. Your problem could be something small, however you wull eaist less time to re-install everything, then to try searching for the problem.
    btw-What Development tool do you use? Just in case you may try to check whether it could be a problem of the ide (It should not be however), just check with another Ide, and see if the same happens. If yes, then follow my first advise, I think it would take you less time.

  • I can't use swing components in my applets

    When I write an applet without any swing components, my browser never has any trouble finding the classes it needs, whether they're classes I've written or classes that came with Java. However, when I try to use swing components it cannot find them, because it is looking in the wrong place:
    On my computer I have a directory called C:\Java, into which I installed my Java Development Kit (so Sun's classes are stored in the default location within that directory, wherever that is), and I store my classes in C:\Java\Files\[path depends on package]. My browser gives an error message along the lines of "Cannot find class JFrame at C:\Java\Files\javax\swing\JFrame.class"; it shouldn't be looking for this non-existent directory, it should find the swing components where it finds, for example, the Applet class and the Graphics class.
    Is there any way I can set the classpath on my browser? Are the swing components stored separately from other classes (I'm using the J2SE v1.3)?
    Thanks in advance.

    Without having complete information, it appears that you are running your applets using the browser's VM. Further, I assume you are using either IE or Netscape Navigator pre-v6. In that case, your browser only supports Java 1.1, and Swing was implemented in Java 1.2. You need to use the Java plug-in in order to use the Swing classes (see the Plug-in forum for more information), or else download the Swing classes from Sun and include them in your CLASSPATH.
    HTH,
    Carl Rapson

  • Using Swing as interface to a dll

    I am trying to use Swing as my cross platform GUI for c++ dll's. Each dll has its own GUI. However, one of my dll's controls what other dlls are loaded. This works fine until I try to load a second instance of the control dll. I get an access violation message when I try to update my gui. If I try to load the two dlls from the c++ everything works fine, but if I load one from the Java GUI I get an null access exception. I'm guessing its caused by one of two problems:
    1) The DLL loading is trashing the executing stack of either the JAVA or the native code.
    2) As the code returns from the constructor call to the newly loaded dll JNI is deleting the interface objects that it is creating on the heap.
    Any ideas would be greatly appreciated.
    Unfortunately I don't get an error log from JAVA.
    VisualStudio gives me:
    Unhandled exception at 0x10014a7d (nativedll.dll) in testjava.exe: 0xC0000005: Access violation reading location 0xfeeefef6.
    The print out reads:
    Creating Java VM
    No. Created VMs 0
    Creating Frame
    Created frame
    Begin master update loop
    Calling Update
    Updated Frame 0
    Creating Java VM
    No. Created VMs 1
    Creating Frame
    Created frame
    Calling Update
    I am using Visual Studio .Net 2003 and jdk 1.4.4, 1.5.0_08 and 1.6.0.
    Main application:
    #include "Windows.h"
    #include "nativelibrary.h"
    #include <stdlib.h>
    #include <string.h>
    #include "jni.h"
    int main(int argc, char* argv[])
           //Load first library
         HMODULE handle = LoadLibrary( "../../nativedll/debug/nativedll.dll");
         nativelibrary* (*funcPtr)();
         funcPtr = (nativelibrary*(*)())GetProcAddress( handle, "createObj");
         nativelibrary* newObj = (*funcPtr)();
            // update each library
         for (int i = 0; i < 10000; i++)
              printf ("Begin master update loop\n");
              void (*funcPtr2)();
              funcPtr2 = (void(*)())GetProcAddress( handle, "update");
              (*funcPtr2)();
              printf ("End master update loop\n");
              Sleep(10);
         // Sleep(100000);
         return 0;
    }Main Library
    #include <iostream>
    #include "jni.h"
    #include "MyFrame.h"
    #include "StaticFunc.h"
    #include <stdlib.h>
    #include <vector>
    #include "Windows.h"
    using namespace std;
    class nativelibrary
    public:
         JavaVM *jvm;
         JNIEnv *env;
         jclass cls;
         jobject myFrame;
         nativelibrary();
         void locupdate();
         static vector<nativelibrary*> objects;
    vector<nativelibrary*> nativelibrary::objects;
    nativelibrary* createObj()
         return new nativelibrary();
    nativelibrary::nativelibrary()
         // JavaVMOption options[0];
         JavaVMInitArgs vm_args;
         memset(&vm_args, 0, sizeof(vm_args));
         vm_args.version = JNI_VERSION_1_4;
         vm_args.nOptions = 0;
         vm_args.ignoreUnrecognized = true;
         vm_args.nOptions = 0;
         // vm_args.options = options;
         JavaVM** jvmBuf = (JavaVM**)malloc(sizeof(JavaVM*));
         jsize buflen = 1;
         jsize nVMs =0;
         // vm_args.options[0].optionString = "-Djava.class.path=../../bin/Debug";
         // Create the Java VM
         printf("Creating Java VM\n");
         jint res = JNI_GetCreatedJavaVMs(jvmBuf, buflen, &nVMs);
         if ( res >= 0)
              printf("No. Created VMs %i\n", nVMs);
              if ( nVMs > 0)
                   jvm = jvmBuf[0];
                   res = jvm->GetEnv((void**)&env,vm_args.version);
              else
                   res = JNI_CreateJavaVM(&jvm,(void**)&env,&vm_args);
         else
              res = JNI_CreateJavaVM(&jvm,(void**)&env,&vm_args);
         cls = env->FindClass("LMyFrame;");     
         if ( cls == 0 ) printf("Cannot find MyFrame");
         jmethodID mid = env->GetMethodID(cls, "<init>", "()V");
         if ( mid == 0 ) printf("Cannot find constructor");
         printf("Creating Frame\n");
         myFrame = env->NewObject(cls, mid);
         if (env->ExceptionOccurred())
              env->ExceptionDescribe();
         printf("Created frame\n");
         objects.push_back(this);
    void nativelibrary::locupdate()
         printf("Calling Update\n");
         jmethodID updatemid = env->GetMethodID(cls, "update", "()V");
         if ( updatemid == 0 ) printf("Cannot find update");
         env->CallVoidMethod(myFrame, updatemid);
         if (env->ExceptionOccurred())
              env->ExceptionDescribe();
    void update()
         vector<nativelibrary*>::iterator it = nativelibrary::objects.begin();
         while (it != nativelibrary::objects.end())
              nativelibrary* lib = *it;
              lib->locupdate();
              it++;
    JNIEXPORT void JNICALL Java_MyFrame__1createObj
      (JNIEnv *, jclass)
         createObj();
    }Java Class (User interface)
    class MyFrame
         static native void _createObj();
         static int creations = 0;
         int framenum;
         MyFrame()
              System.loadLibrary("../../nativedll/Debug/nativedll");
              framenum = creations++;
         void update()
              System.out.println("Updated Frame " + framenum);
              if ( creations == 1)
                   // load dll as a result of the user clicking on the interface
                   createObj();
         public static void createObj()
              _createObj();
    }

    I am trying to use Swing as my cross platform GUI for c++ dll's. Each dll has its own GUI. However, one of my dll's controls what other dlls are loaded. This works fine until I try to load a second instance of the control dll. I get an access violation message when I try to update my gui. If I try to load the two dlls from the c++ everything works fine, but if I load one from the Java GUI I get an null access exception. I'm guessing its caused by one of two problems:
    1) The DLL loading is trashing the executing stack of either the JAVA or the native code.
    2) As the code returns from the constructor call to the newly loaded dll JNI is deleting the interface objects that it is creating on the heap.
    Any ideas would be greatly appreciated.
    Unfortunately I don't get an error log from JAVA.
    VisualStudio gives me:
    Unhandled exception at 0x10014a7d (nativedll.dll) in testjava.exe: 0xC0000005: Access violation reading location 0xfeeefef6.
    The print out reads:
    Creating Java VM
    No. Created VMs 0
    Creating Frame
    Created frame
    Begin master update loop
    Calling Update
    Updated Frame 0
    Creating Java VM
    No. Created VMs 1
    Creating Frame
    Created frame
    Calling Update
    I am using Visual Studio .Net 2003 and jdk 1.4.4, 1.5.0_08 and 1.6.0.
    Main application:
    #include "Windows.h"
    #include "nativelibrary.h"
    #include <stdlib.h>
    #include <string.h>
    #include "jni.h"
    int main(int argc, char* argv[])
           //Load first library
         HMODULE handle = LoadLibrary( "../../nativedll/debug/nativedll.dll");
         nativelibrary* (*funcPtr)();
         funcPtr = (nativelibrary*(*)())GetProcAddress( handle, "createObj");
         nativelibrary* newObj = (*funcPtr)();
            // update each library
         for (int i = 0; i < 10000; i++)
              printf ("Begin master update loop\n");
              void (*funcPtr2)();
              funcPtr2 = (void(*)())GetProcAddress( handle, "update");
              (*funcPtr2)();
              printf ("End master update loop\n");
              Sleep(10);
         // Sleep(100000);
         return 0;
    }Main Library
    #include <iostream>
    #include "jni.h"
    #include "MyFrame.h"
    #include "StaticFunc.h"
    #include <stdlib.h>
    #include <vector>
    #include "Windows.h"
    using namespace std;
    class nativelibrary
    public:
         JavaVM *jvm;
         JNIEnv *env;
         jclass cls;
         jobject myFrame;
         nativelibrary();
         void locupdate();
         static vector<nativelibrary*> objects;
    vector<nativelibrary*> nativelibrary::objects;
    nativelibrary* createObj()
         return new nativelibrary();
    nativelibrary::nativelibrary()
         // JavaVMOption options[0];
         JavaVMInitArgs vm_args;
         memset(&vm_args, 0, sizeof(vm_args));
         vm_args.version = JNI_VERSION_1_4;
         vm_args.nOptions = 0;
         vm_args.ignoreUnrecognized = true;
         vm_args.nOptions = 0;
         // vm_args.options = options;
         JavaVM** jvmBuf = (JavaVM**)malloc(sizeof(JavaVM*));
         jsize buflen = 1;
         jsize nVMs =0;
         // vm_args.options[0].optionString = "-Djava.class.path=../../bin/Debug";
         // Create the Java VM
         printf("Creating Java VM\n");
         jint res = JNI_GetCreatedJavaVMs(jvmBuf, buflen, &nVMs);
         if ( res >= 0)
              printf("No. Created VMs %i\n", nVMs);
              if ( nVMs > 0)
                   jvm = jvmBuf[0];
                   res = jvm->GetEnv((void**)&env,vm_args.version);
              else
                   res = JNI_CreateJavaVM(&jvm,(void**)&env,&vm_args);
         else
              res = JNI_CreateJavaVM(&jvm,(void**)&env,&vm_args);
         cls = env->FindClass("LMyFrame;");     
         if ( cls == 0 ) printf("Cannot find MyFrame");
         jmethodID mid = env->GetMethodID(cls, "<init>", "()V");
         if ( mid == 0 ) printf("Cannot find constructor");
         printf("Creating Frame\n");
         myFrame = env->NewObject(cls, mid);
         if (env->ExceptionOccurred())
              env->ExceptionDescribe();
         printf("Created frame\n");
         objects.push_back(this);
    void nativelibrary::locupdate()
         printf("Calling Update\n");
         jmethodID updatemid = env->GetMethodID(cls, "update", "()V");
         if ( updatemid == 0 ) printf("Cannot find update");
         env->CallVoidMethod(myFrame, updatemid);
         if (env->ExceptionOccurred())
              env->ExceptionDescribe();
    void update()
         vector<nativelibrary*>::iterator it = nativelibrary::objects.begin();
         while (it != nativelibrary::objects.end())
              nativelibrary* lib = *it;
              lib->locupdate();
              it++;
    JNIEXPORT void JNICALL Java_MyFrame__1createObj
      (JNIEnv *, jclass)
         createObj();
    }Java Class (User interface)
    class MyFrame
         static native void _createObj();
         static int creations = 0;
         int framenum;
         MyFrame()
              System.loadLibrary("../../nativedll/Debug/nativedll");
              framenum = creations++;
         void update()
              System.out.println("Updated Frame " + framenum);
              if ( creations == 1)
                   // load dll as a result of the user clicking on the interface
                   createObj();
         public static void createObj()
              _createObj();
    }

  • How do you remove back up data from the memory storage? my storage data states that i have over 80gb of data used for back ups and i dont know why as i use a external hard drive as a time machine .now my 250gb flash storage is nearly full

    how do you remove back up data from the memory storage? my storage data states that i have over 80gb of data used for back ups and i dont know why as i use a external hard drive as a time machine .now my 250gb flash storage is nearly full.. HELP!

    When Time Machine backs up a portable Mac, some of the free space will be used to make local snapshots, which are backup copies of recently deleted files. The space occupied by local snapshots is reported as available by the Finder, and should be considered as such. In the Storage display of System Information, local snapshots are shown as  Backups. The snapshots are automatically deleted when they expire or when free space falls below a certain level. You ordinarily don't need to, and should not, delete local snapshots yourself. If you followed bad advice to disable local snapshots by running a shell command, you may have ended up with a lot of data in the Other category. Ask for instructions in that case.
    See this support article for some simple ways to free up storage space.

  • How can i connect multiple forms using swings or applets(AWT) & with D-Base

    Hello Friends,
    I am Sreedhar from Hyderabad. working as a java developer in a small organization. I got a challenge to work on java stand alone (desktop) application. Basically our company is based on SCM(Supply Chain Management), I never work before using swings and AWT. now my present challenge is to develope an application on swings and AWT using Net Beans IDE. but i am unble find the code to connect one form to another form, i want to develop similar application like a web application , suppose if i click on OK button it has to connect next form. in the next for it has to take user name and password should allow me to access main form. please help me about this topic, if anybody interested i can send u the screen shots and i can post to ur mail. please help me as soon as possible,

    sreedharkommuru wrote:
    Hello Friends,
    I am Sreedhar from Hyderabad. working as a java developer in a small organization. I got a challenge to work on java stand alone (desktop) application. Basically our company is based on SCM(Supply Chain Management), I never work before using swings and AWT. now my present challenge is to develope an application on swings and AWT using Net Beans IDE. but i am unble find the code to connect one form to another form, i want to develop similar application like a web application , suppose if i click on OK button it has to connect next form. in the next for it has to take user name and password should allow me to access main form. please help me about this topic, if anybody interested i can send u the screen shots and i can post to ur mail. please help me as soon as possible,There is no magic, you need to spend a good amount of time in tutorials, here is a good one to start off with:
    [The Really Big Index|http://java.sun.com/docs/books/tutorial/reallybigindex.html]
    Here are a few tips:
    1 - Do not mix AWT and SWING: it'll just cause you headaches in the long run that you cannot fix without refactoring to properly not mix the 2 together.
    2 - You use JDBC to access the database
    3 - You make accessors/constructors to pass parameters that you need from one form to another.
    Have fun.

  • Is it possible to use events for objects that do not use swing or awt

    Dear Experts
    I want to know if events are possible with plain java objects. A simple class that is capable of firing an event and another simple class that can receive that event. My question is
    1. If it is possible - then what is the approach that needs to be taken and would appreciate an example.
    2. Is Observer Pattern in java going to help?
    To explain further i am doing [Add,Modify,Delete,Traverse] Data tutorial using swing in Net beans. I have a ButtonState Manager class that enables and disables buttons according to a given situation. For example if add is clicked the modify button becomes Save and another becomes Cancel. The other buttons are disabled. What i want is the ButtonStateManager class to do a little further - i.e. if Save is clicked it should report to DBClass that it has to save the current record which was just added. I am foxed how this can be done or what is the right way. Thanks for reading a long message. Appreciate your help.
    Best regards

    Thanks Kayaman
    i guess i am doing something else maybe it is crazy but i need to work further i guess... i cant post the entire code as it is too big but some snippets
    public class DatabaseApplication extends javax.swing.JFrame {
        ButtonStateManager bsm;
        /** Creates new form DatabaseApplication */
        public DatabaseApplication() {
            initComponents();
            // ButtonStateManager has a HUGE constructor that takes all the buttons as argument!
            bsm = new ButtonStateManager(
                    btnAdd,
                    btnModify,
                    btnDelete,
                    btnQuit,
                    btnMoveNext,
                    btnMovePrevious,
                    btnMoveLast,
                    btnMoveFirst );One of the methods in the ButtonStateManager Class is as follows
      private void modifyButtonState()
            btnAdd.setText("Save");
            btnModify.setEnabled(false);
            btnDelete.setText("Cancel");
            btnQuit.setEnabled(false);
            ...Finally the Crazy way i was trying to do ... using EXCEPTIONS!
      void modifyClicked() throws DBAction
            if(btnModify.getText().equalsIgnoreCase("MODIFY"))
                modifyButtonState();
            else
                throw new DBAction("SaveAddedRecord");
        }And Finally how i was Tackling exceptions....
      private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {                                      
          try {
                bsm.addClicked();
            } catch (Exception e1) {
                processDBAction(e1.getMessage());
        private void processDBAction(String msg)
            if(msg.equalsIgnoreCase("SAVEMODIFIEDRECORD"))
                System.err.println(msg);
                bsm.normalButtonState();
            }Edited by: standman on Mar 30, 2011 4:51 PM

  • Why do we use open URL in default browser function? What are the uses of it?

    Why do we use "open URL in default browser" function?  What are the uses of it?

    kdm7 wrote:
    Okay.
    So can we keep a web button to access the www.ni.com ? So that web site opens only when button pressed?
    P.S  I,m a newbie.
    Yes, you can also, e.g. include a help file or manual as html and open that in the browser.
    /Y
    LabVIEW 8.2 - 2014
    "Only dead fish swim downstream" - "My life for Kudos!" - "Dumb people repeat old mistakes - smart ones create new ones."
    G# - Free award winning reference based OOP for LV

  • What is the best way to use Swing GUIs in an MVC design?

    I have a question on how to build an application using swing frames for the UI, but using an MVC architecture. I've checked the rest of the forum, but not found an answer to my question that meets my needs.
    My application at this stage presents a login screen to get the userid and password, or to allow the user to choose a new locale. If an Enter action is performed, the userid and password are checked against the DB. If not accepted, the screen is repainted with a "try-again" message. If the Cancel action is performed, the process stops. If a locale action is performed, the screen is repainted with different langauge labels. Once the login process is passed, a front screen (another swing frame) is presented.
    Implementation: I am using a session object (Session, represents the user logging in) that calls the Login screen (LoginGUI, a Swing JFrame object with various components). Session uses setters in LoginGUI to set the labels, initial field entries etc, before enabling the screen. From this point, the user will do something with the LoginGUI screen - could be closing the window, entering a mix of userid and password, or maybe specifying a locale. Once the user has taken the action, if required, the session object can use getters to retrieve the userid and password values entered in the fields.
    The crux of the problem is 1) how will Session know that an action has been taken on the LoginGUI, and 2) how to tell what action has been taken.
    This could be solved by getting LoginGUI to call back to Session, however, I am trying to buid the application with a good separation of business, logic and presentation (i.e MVC, but not using any specific model). Therefore, I do not want LoginGUI to contain any program flow logic - that should all be contained in Session.
    I am aware of two possible ways to do this:
    1. Make LoginGUI synchronised, so that Session waits for LoginGUI to send a NotifyAll(). LoginGUI could hold a variable indicating what has happened which Session could interrogate.
    2. Implement Window Listener on Session so that it gets informed of the Window Close action. For the other two actions I could use a PropertyChangeListener in Session, that is notified when some variable in LoginGUI is changed. This variable could contain the action performed.
    Has anyone got any comments on the merits of these methods, or perhaps a better method? This technique seems fundamental to any application that interfaces with end-users, so I would like to find the best way.
    Thanks in advance.

    Hi,
    I tried to avoid putting in specific code as my question was more on design, and I wanted to save people having to trawl through specific code. And if I had any school assignments outstanding they would be about 20 years too late :-). I'm not sure computers more sophisticated than an abacus were around then...
    Rather than putting the actual code (which is long and refers to other objects not relevant to the discussion), I have put together two demo classes to illustrate my query. Comments in the code indicate where I have left out non-relevant code.
    Sessiondemo has the main class. When run, it creates an instance of LoginGUIdemo, containing a userid field, password field, a ComboBox (which would normally have a list of available locales), an Enter and a Cancel box.
    When the Locale combo box is clicked, the LoginGUIdemo.userAction button is changed (using an ActionListener) and a property change is fired to Session (which could then perform some work). The same technique is used to detect Enter events (pressing return in password and userid, or clicking on Enter), and to detect Cancel events (clicking on the cancel button). Instead of putting in business code I have just put in System.out.printlns to print the userAction value.
    With this structure, LoginGUIdemo has no business logic, but just alerts Sessiondemo (the class with the business logic).
    Do you know any more elegant way to achieve this function? In my original post, I mentioned that I have also achieved this using thread synchronisation (Sessiondemo waits on LoginGUI to issue a NotifyAll() before it can retrieve the LoginGUI values). I can put together demo code if you would like. Can you post any other demo code to demonstrate a better technique?
    Cheers,
    Alan
    Here's Sessiondemo.class
    import java.io.*;
    import java.awt.event.*;
    import java.util.*;
    import java.beans.*;
    public class Sessiondemo implements PropertyChangeListener {
        private LoginGUIdemo lgui;   // Login screen
        private int localeIndex; // index referring to an array of available Locales
        public Sessiondemo () {
            lgui = new LoginGUIdemo();
            lgui.addPropertyChangeListener(this);
            lgui.show();
        public static void main(String[] args) {
            Sessiondemo sess = new Sessiondemo();
        public void propertyChange(java.beans.PropertyChangeEvent pce) {
            // Get the userAction value from LoginGUI
            String userAction = pce.getNewValue().toString();
            if (userAction == "Cancelled") {
                System.out.println(userAction);
                // close the screen down
                lgui.dispose();
                System.exit(0);
            } else if (userAction == "LocaleChange") {
                System.out.println(userAction);
                // Get the new locale setting from the LoginGUI
                // ...modify LoginGUI labels with new labels from ResourceBundle
    lgui.show();
    } else if (userAction == "Submitted") {
    System.out.println(userAction);
    // ...Get the userid and password values from LoginGUIdemo
                // run some business logic to decide whether to show the login screen again
                // or accept the login and present the application frontscreen
    }And here's LoginGUIdemo.class
    * LoginGUIdemox.java
    * Created on 29 November 2002, 18:59
    * @author  administrator
    import java.beans.*;
    public class LoginGUIdemo extends javax.swing.JFrame {
        private String userAction;
        private PropertyChangeSupport pcs;
        /** Creates new form LoginGUIdemox */
        // Note that in the full code there are setters and getters to allow access to the
        // components in the screen. For clarity they are not included here
        public LoginGUIdemo() {
            pcs = new PropertyChangeSupport(this);
            userAction = "";
            initComponents();
        public void setUserAction(String s) {
            userAction = s;
            pcs.firePropertyChange("userAction",null,userAction);
        public void addPropertyChangeListener(PropertyChangeListener l) {
            pcs.addPropertyChangeListener(l);
        public void removePropertyChangeListener(PropertyChangeListener l) {
            pcs.removePropertyChangeListener(l);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            jTextField1 = new javax.swing.JTextField();
            jTextField2 = new javax.swing.JTextField();
            jComboBox1 = new javax.swing.JComboBox();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            getContentPane().setLayout(new java.awt.FlowLayout());
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            jTextField1.setText("userid");
            jTextField1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    EnterActionPerformed(evt);
            getContentPane().add(jTextField1);
            jTextField2.setText("password");
            jTextField2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    EnterActionPerformed(evt);
            getContentPane().add(jTextField2);
            jComboBox1.setToolTipText("Select Locale");
            jComboBox1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    LocaleActionPerformed(evt);
            getContentPane().add(jComboBox1);
            jButton1.setText("Enter");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    EnterActionPerformed(evt);
            getContentPane().add(jButton1);
            jButton2.setText("Cancel");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    CancelActionPerformed(evt);
            getContentPane().add(jButton2);
            pack();
        private void LocaleActionPerformed(java.awt.event.ActionEvent evt) {
            setUserAction("LocaleChange");
        private void CancelActionPerformed(java.awt.event.ActionEvent evt) {
            setUserAction("Cancelled");
        private void EnterActionPerformed(java.awt.event.ActionEvent evt) {
            setUserAction("Submitted");
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            new LoginGUIdemo().show();
        // Variables declaration - do not modify
        private javax.swing.JTextField jTextField2;
        private javax.swing.JTextField jTextField1;
        private javax.swing.JComboBox jComboBox1;
        private javax.swing.JButton jButton2;
        private javax.swing.JButton jButton1;
        // End of variables declaration

  • WHY CANT I USE FINAL CUT EXPRESS HD IN MY MACBOOK

    WHY CANT I USE FINAL CUT EXPRESS HD IN MY MACBOOK?

    hey there DavoMrMac,
    according to Apple's 'site:
    System Requirements
    Macintosh computer with 500MHz or faster PowerPC G4 or G5 (550MHz for PowerBook G4) or Intel Core Duo
    512MB RAM
    Display with 1024-by-768 (or higher) resolution
    An AGP or PCI Express graphics card compatible with Quartz Extreme or an Intel GMA integrated graphics processor in MacBook or Mac Mini
    Mac OS X 10.4.6 or later
    QuickTime 7.0.4 or later
    HDV features require 1GHz or faster processor and 1GB of RAM (2GB recommended)
    500MB disk space required for applications; additional 16GB of additional storage space for Soundtrack and LiveType content (can be installed on separate disks)
    DVD drive for software installation
    i've been running FCE HD 3.5 on my MacBook since i got it in November '06. runs okay for the few short SD projects(15:00) or less i've put together.

Maybe you are looking for

  • JDBC Adapter Quoting of String

    Hi everybody! I am posting data to a JDBC Receiver adapter using the JDBC adapter's XML format. I have configured the logging of the adapter to show the SQL commands issued to the adapter, since I received some strange errors from the database. I now

  • Keynote Prints off the Page

    Since upgrading to the latest version of iWork apps, Keynote now prints off the left side of the page. I've noticed that there's no place to set margins. Is there anything I can do to get them to print normally? The current work around has been to sh

  • End of my patience

    Can anybody let me know what is wrong with my ipod? When connected to my PC the ipod does not appear in itunes, My Computer or Device manager. I have a docking station connected to my sound system and i do not know if this problem is connected but th

  • [SOLVED]bin32-wine 1.1.1 opengl error

    Trying to start counter-strike 1.6 on arch64 I get the error Error initializing gl driver, check that the file 'opengl32.dll' exists Using xf86-video-intel driver, direct rendering enabled. Used to work with older versions of wine, but no longer... L

  • Executing DPM Powershell Commands

    Hi All,          I am trying to execute DPM 2012 Powershell commands from a console application in c#, but at the time of Invoke it is giving me the following error. {"Could not load file or assembly 'ACM, Version=1.0.523.0, Culture=neutral, PublicKe