AWT vs SWING and more

1)Though the components used in awt and swing are similar what is the need for two seperate packages ?
and
2)what is the main usage of "getContentPane()" ?
3)why do we use an appletviewer for executing applets provided the OS is Windows NT ..

1)Though the components used in awt and swing are
similar what is the need for two seperate packages ?AWT uses the native (heavyweight) components of the underlying Operating System. Actually a common (and small) subset of the provided components.
In Swing the components a lightweight, there's no native component behind them, the components are painted by pure java code (sometimes sophisticated components). The swing applications thus can look and feel the same on all platforms.
2)what is the main usage of "getContentPane()" ?When using swing you shouldn't add lightweight components to the window subclasses, only to the content pane.
3)why do we use an appletviewer for executing applets
provided the OS is Windows NT ..Did not understand.
Kurta

Similar Messages

  • Difference between AWT,Swing and swt

    Hello,
    I am giving a seminar about swing in which I need to point out differences between AWT,Swing and SWT(Software Widget Tool).
    I have two questions:
    1)I read that-A heavyweight component is one that is associated with its own native screen resource (commonly known as a peer). A lightweight component is one that "borrows" the screen resource of an ancestor-which makes it lighter.Can anybody explain What native screen resource is and how it is borrowed?
    2)I read that SWT uses native widgets and how can it be better than swing?If it is in what way?

    Use Swing for new projects. AWT is the rendering layer underneath Swing in many cases, and AWT provides utility things like Graphics. SWT is an alternative to Swing which used more native rendering, but actually with Java 6, Swing is using a lot of native rendering.
    Fire up NetBeans and use Matisse. Build an application. Run it under Windows, and then under Linux, and then realize how great it is.

  • Need  java code to perform refresh button action using swings and awt

    i need java code to perform refresh button action using swings and awt.please help me

    Wait ! Noboby ? OK, I'll do it
    public void onBtnAction ()
        if (!fresh)
            refresh ();
    }Seriously, did you expect anyone to answer such a cryptic question ?

  • Swing and jmf

    can u please have a look to the attached file
    i know that this involves the jmf API but I have the feeling that has to do more with swing, thats whay I post my question here
    this simple application is based on the MDI.java example of the jmf web
    pages
    I also added a slider and want to set the playback rate for the player from
    there if possible
    that is I want everytime that I move the slider and the value is biggerthan
    50 the rate to be reduced according to a simple calculation that converts
    the slider value to a value between 0 an1 for the rate...
    so all i want to do is pass the slider value to the player everytime that
    the slider changes value and this is bigger than 50
    the attached file can do that only when the player starts playing the
    file,,,,
    after the player has started and the rate is set I cant change it even if
    the slider moves
    when I tried to do that from within the stateChanged method of the slider I
    was getting a Nullpointer exception because of the EventDispatching thread,
    so I thought to take this piece of code out of there (create the setnewrate
    method in the jmframe instead),,,,but then of course doesnt work like I
    would want,,,,,
    do I have to register the class that implements the frame for the player as
    a ChangeListener on the slider to achieve that, is something like that
    possible....
    I know that swing is not supposed to be thread safe, so maybe this is what
    the problem is after all...any suggestions to that direction?
    Can u please have a look??
    I am a beginner so any help would really be very much appreciated
    thanx :)
    maria
    .....and the attached file
    I think the problem is with the stateChanged method for the Jslider...
    I am getting a null pointerexception because of the eventdispatching thread
    pls ignore any silly mistakes I am a completely newbie in java
    myAppfr2.java
    import javax.media.*;
    import com.sun.media.ui.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.Vector;
    import javax.swing.border.Border.*;
    import java.util.Hashtable;
    public class myAppfr2 extends Frame {
    * VARIABLES
    JMFrame jmframe = null;
    JDesktopPane desktop;
    FileDialog fd = null;
    CheckboxMenuItem cbAutoLoop = null;
    Player player ;
    //Player newPlayer = null;
    String filename;
    boolean stopped;
    public my_slider test_slider;//put it here so I can use it by name by all code
    float rate;
    * MAIN PROGRAM / STATIC METHODS
    public static void main(String args[]) {
    //if (args.length > 0)
         //rate=Float.parseFloat(args[0]);
    myAppfr2 mdi = new myAppfr2();
    static void Fatal(String s) {
    MessageBox mb = new MessageBox("JMF Error", s);
    * METHODS
    public myAppfr2() {
    super("VHE Demo");
    // Add the desktop pane
    setLayout( new BorderLayout() );
    desktop = new JDesktopPane();
    desktop.setDoubleBuffered(true);
         desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);//makes dragging faster
    add("Center", desktop);
    setMenuBar(createMenuBar());
    setSize(640, 480);
    setVisible(true);
         test_slider = new my_slider("networkutil");
         createnetworkutil();
         try {
         UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel") ;
    } catch (Exception e) {
    System.err.println("Could not initialize personal look and feel");
    addWindowListener( new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    System.exit(0);
    Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, new Boolean(true));
    private MenuBar createMenuBar() {
    ActionListener al = new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    String command = ae.getActionCommand();
    if (command.equals("Open")) {
    if (fd == null) {
    fd = new FileDialog(myAppfr2.this, "Open File",
    FileDialog.LOAD);
    fd.setDirectory("~/movies");
    fd.show();
    if (fd.getFile() != null) {
    String filename = fd.getDirectory() + fd.getFile();
    openFile("file:" + filename);
    } else if (command.equals("Exit")) {
    dispose();
    System.exit(0);
    MenuItem item;
    MenuBar mb = new MenuBar();
    // File Menu
    Menu mnFile = new Menu("File");
    mnFile.add(item = new MenuItem("Open"));
    item.addActionListener(al);
    mnFile.add(item = new MenuItem("Exit"));
    item.addActionListener(al);
    // Options Menu
    Menu mnOptions = new Menu("Options");
    cbAutoLoop = new CheckboxMenuItem("Auto replay");
    cbAutoLoop.setState(true);
    mnOptions.add(cbAutoLoop);
    mb.add(mnFile);
    mb.add(mnOptions);
    return mb;
    //create slider and add it to desktop
    public void createnetworkutil(){
    test_slider.pack();
    desktop.add(test_slider);
    test_slider.setVisible(true);
    * Open a media file.
    private void openFile(String filename) {
    String mediaFile = filename;
    Player player = null;
    // URL for our media file
    URL url = null;
    try {
    // Create an url from the file name and the url to the
    // document containing this applet.
    if ((url = new URL(mediaFile)) == null) {
    Fatal("Can't build URL for " + mediaFile);
    return;
    // Create an instance of a player for this media
    try {
    player = Manager.createPlayer(url);
    } catch (NoPlayerException e) {
    Fatal("Error: " + e);
    } catch (MalformedURLException e) {
    Fatal("Error:" + e);
    } catch (IOException e) {
    Fatal("Error:" + e);
    if (player != null) {
    this.filename = filename;
    JMFrame jmframe = new JMFrame(player, filename);
    desktop.add(jmframe);
    class JMFrame extends JInternalFrame implements ControllerListener {
    public Player mplayer;
    Component visual = null;
    Component control = null;
    int videoWidth = 0;
    int videoHeight = 0;
    int controlHeight = 30;
    int insetWidth = 10;
    int insetHeight = 30;
    // boolean firstTime = true;
    public JMFrame(Player player, String title) {
    super(title, true, true, true, true);
    getContentPane().setLayout( new BorderLayout() );
    //setSize(320, 10);
    setLocation(200, 25);
    setVisible(true);
    mplayer = player;
    mplayer.addControllerListener((ControllerListener) this);
    mplayer.realize();
    addInternalFrameListener( new InternalFrameAdapter() {
    public void internalFrameClosing(InternalFrameEvent ife) {
    mplayer.close();
    public void controllerUpdate(ControllerEvent ce) {
    // System.out.println("controllerUpdate");
    //SwingUtilities.isEventDispatchThread();
    if (ce instanceof RealizeCompleteEvent) {
    mplayer.prefetch();
    } else if (ce instanceof PrefetchCompleteEvent) {
    if (visual != null)
    return;
         //setnewrate();
         //rate=mplayer.getRate();
         System.out.println( mplayer.getRate());
    if ((visual = mplayer.getVisualComponent()) != null) {
    Dimension size = visual.getPreferredSize();
    videoWidth = size.width;
    videoHeight = size.height;
    getContentPane().add("Center", visual);
    } else
    videoWidth = 320;
    /*if ((control = mplayer.getControlPanelComponent()) != null) {
    controlHeight = control.getPreferredSize().height;
    getContentPane().add("South", control);
    setSize(videoWidth + insetWidth,
    videoHeight + controlHeight + insetHeight);
    validate();
    mplayer.start();
    } else if (ce instanceof StartEvent){
         if (test_slider.netutil==0) {
         mplayer.stop();
         } else if (ce instanceof EndOfMediaEvent && cbAutoLoop.getState()) {
    mplayer.setMediaTime(new Time(0));
              boolean stopped=true;
              mplayer.prefetch();
              mplayer.start();
              stopped=false;
    class my_slider extends JInternalFrame implements ChangeListener{
    //Set up parameters.
    int netini=50;
    public int netutil=netini;
    public my_slider(String windowTitle) {
    super(windowTitle, false, false, false, false);
    getContentPane().setLayout(new BorderLayout());
    setLocation(25,25);// for the internal frame that contains the slider
    setVisible(true); //..same
    //Create the slider(the component included in "my_slider" internal frame
         JSlider mslider = new JSlider(JSlider.VERTICAL,
    0, 100, netini);
    mslider.addChangeListener((ChangeListener) this);
    mslider.setMajorTickSpacing(10);
    mslider.setPaintTicks(true);
    //Create the label table.
    Hashtable labelTable = new Hashtable();
    labelTable.put(new Integer( 0 ),
    new JLabel("0%") );
    labelTable.put(new Integer( 25 ),
    new JLabel("25%") );
    labelTable.put(new Integer( 50 ),
    new JLabel("50%") );
    labelTable.put(new Integer(75),
    new JLabel("75%") );
         labelTable.put(new Integer( 100),
    new JLabel("100%") );     
    mslider.setLabelTable(labelTable);
    mslider.setPaintLabels(true);
    mslider.setBorder(
    BorderFactory.createEmptyBorder(0,0,0,10));
         //Put everything in the content pane.
    getContentPane().add(mslider, BorderLayout.CENTER);
    public void stateChanged(ChangeEvent e) { //System.out.println("stateChanged");
    // SwingUtilities.isEventDispatchThread();
    if (e instanceof ChangeEvent){
    JSlider source = (JSlider)e.getSource();
    if (!source.getValueIsAdjusting()) {
    netutil= (int)source.getValue();
         System.out.println(netutil);
              if (jmframe.mplayer!=null) {
         jmframe.mplayer.setRate((float)(netutil/(netutil+(0.3*netutil))));
              if (jmframe.mplayer.getTargetState() <Player.Started)
         jmframe.mplayer.prefetch();
    i am stuck so any help would be really very much appreciated

    did you ever resolve this.
    I may be having similar problems
    I have an JMF application running under webstart. It runs ok in Java 1.3
    Now I am trying to get ti to run under Java 1.4. The attached error is rather useless,
    but by guess at what is happening is that the JMF control has some .awt. stuff included
    but that Java 1.4 emulates .awt. in swing. But something was not set and the default does not
    work.
    This error messages does not appear in the 1.3 run
    Any suggestions would be greatly appriatated.
    1.4 result:
    mg version 2.1.1a
    player created com.sun.media.content.unknown.Handler@3a1834
    ctr com.sun.media.PlaybackEngine$BitRateA@4a9a7d
    ctr com.sun.media.BasicJMD[panel0,0,0,512x200,invalid,layout=java.awt.BorderLayout]
    duration? javax.media.Time@6b5666 sec = 9.223372036854776E9
    time unknown javax.media.Time@754699
    will realize the player
    realize
    javax.media.TransitionEvent[source=com.sun.media.content.unknown.
    Handler@3a1834,previous=Unrealized,current=Realizing,
    target=Realized]
    start smxBADS
    bass start
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at javax.swing.plaf.metal.MetalLookAndFeel.getControlInfo(Unknown Source)
    at javax.swing.plaf.metal.MetalScrollButton.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintWithBuffer(Unknown Source)
    at javax.swing.JComponent._paintImmediately(Unknown Source)
    at javax.swing.JComponent.paintImmediately(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at javax.swing.plaf.metal.MetalLookAndFeel.getControlInfo(Unknown Source)
    at javax.swing.plaf.metal.MetalScrollButton.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintWithBuffer(Unknown Source)
    at javax.swing.JComponent._paintImmediately(Unknown Source)
    at javax.swing.JComponent.paintImmediately(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    realize done
    panel found java.awt.Panel[panel1,0,0,0x0,invalid] java.awt.Panel[panel2,4,216,292x30,layout=java.awt.FlowLayout]
    press a button
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at javax.swing.plaf.metal.MetalLookAndFeel.getControlInfo(Unknown Source)
    at javax.swing.plaf.metal.MetalScrollButton.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintWithBuffer(Unknown Source)
    at javax.swing.JComponent._paintImmediately(Unknown Source)
    at javax.swing.JComponent.paintImmediately(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    1.3 result
    mg version 2.1.1a
    player created com.sun.media.content.unknown.Handler@354749
    ctr com.sun.media.PlaybackEngine$BitRateA@5b484d
    ctr com.sun.media.BasicJMD[panel3,0,0,512x200,invalid,layout=java.awt.BorderLayout]
    duration? javax.media.Time@46d228 sec = 9.223372036854776E9
    time unknown javax.media.Time@f7386
    will realize the player
    realize
    javax.media.TransitionEvent[source=com.sun.media.content.unknown.
    Handler@354749,previous=Unrealized,current=Realizing,
    target=Realized]
    start smxBADS
    bass start
    javax.media.DurationUpdateEvent[source=com.sun.media.content.unknown.Handler@354749,duration=javax.media.Time@55c0f9
    javax.media.Time@55c0f9
    javax.media.RealizeCompleteEvent[source=com.sun.media.content.unknown.Handler@354749,previous=Realizing,current=Realized,target=Realized]
    realized complete
    prefetch
    realize done
    controlComp com.sun.media.ui.DefaultControlPanel[,0,0,74x21,invalid,layout=java.awt.BorderLayout]
    add controlComp 21 java.awt.Panel[panel4,10,-12,258x47,invalid]
    javax.media.TransitionEvent[source=com.sun.media.content.unknown.Handler@354749,previous=Realized,current=Prefetching,target=Prefetched]
    start smxBADS
    bass start
    running ok from here on

  • Learn AWT before Swing?

    I have zero practical knowledge of Java GUI programming.
    Swing sits on top of AWT. Swing is easier than AWT. Yet, so as to understand Swing, and to be able to do things Swing might not be able to do, I am inclined to first only use AWT. Build a base on which to learn Swing.
    A counter argument would be, in my opinion, C vs. C++. While C++ sits on top of C, I don't see any benefit to learning pure C before C++. Further, I don't want things to be too difficult before making them easier regarding GUIs.
    Should the progression be: AWT then Swing? Swing then AWT then Swing? just Swing, and learn AWT if ever needed?

    I agree with the others, just learn swing and the parts of awt you need will just come along.
    But I want to add that using a GUI generator to create swing for you is very tempting, especially at first, but is the worst thing you can do to handicap yourself. I know you didn't mention them, so this is sort of comming from left field, but just saying avoid them until you really know swing.
    Also, how can you not see a benefit in learning C before C++? True C++ (even if not always practiced) is object oriented whereas true C is procedural. While OO programming is generally better, it is beneficial to understand procedural programming as well, and knowing both will only make you better as a programmer. But even more important is by never learning true C one never has a chance to learn just how powerful pointers are. Pointers are difficult to get your head around, but they are extreemly usefull, if you are one of the few rare people who can use them correctly and unlock their true power.
    Just Saying.
    JSG

  • AWT VS Swing *The Future*

    I've heard at the moment, AWT is faster than Swing, because of the way the code is more native to the OS, but, is Sun trying to eventually get rid of AWT and go all Swing? I already know a LOT of swing, and have created many programs like simple checklist Swing programs, to the more advanced Multiplayer Networked Pong in Swing, but, recently, I decided to expand my knowledge a bit, and learn AWT, and found it's not that much different. I can't seem to figure out how to paint in my AWT frame, it seems different from Swing for painting. Here's my code if you don't mind helping me out :) :
    public class AWT_Speed{
         public static void main(String [] args){
              Frame frame = new Frame("Abstract Window Toolkit");
              Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
              frame.setLocation((dimension.width - 500) / 2 , (dimension.height - 500) / 2);
              frame.setSize(500 , 500);
              frame.setResizable(false);
              frame.addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent we){
                        System.exit(0);
              Panel panel = new Panel();
              panel.setBackground(Color.black);
              panel.add(new Button("AWT Button"));
              panel.add(new Button("AWT Button"));
              panel.add(new Button("AWT Button"));
              frame.add(panel , BorderLayout.SOUTH);
              frame.setVisible(true);
         public void paint(Graphics g){
              Graphics2D g2d = (Graphics2D) g;
              g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING , RenderingHints.VALUE_ANTIALIAS_ON);
              g2d.setPaint(Color.black);
              g2d.fillOval(50 , 50 , 50 , 50);
    }I would appreciate if anyone could help me paint in my frame...I looked all over the internet and just kept finding these tutorials that use AWT for Applets and Applets paint differently than Applications.
    Thanks
    Also, should I even bother with AWT? Why did Sun decide to make Swing anyway? Is Swing eventually going to take over?
    Thanks!
    -Neo-

    Change the first lines of your code to this:
    import java.awt.*;
    import java.awt.event.*;
    public class AWT_Speed extends Frame {
         public AWT_Speed(String text) {
              super(text);
         public static void main(String [] args){
              Frame frame = new AWT_Speed("Abstract Window Toolkit");

  • Connect swing and J2EE

    In WEB Application i used JSP, Struts and J2EE.
    But Now use swing application, and something for joing swing and j2ee
    Somebody knows something...
    I need your help....

    In WEB Application i used JSP, Struts and J2EE.
    But Now use swing application, and something for joing
    swing and j2ee
    hopefully, no business logic is in struts; only the application logic (i.e. order of screens, input type validation, etc.). If this is the case you have many options:
    - direct calls to the ejb (assuming you have a service defined as an EJB)
    - SOAP, SOAP-RPC, or a full web-service (as mentioned above)
    - your own custom protocol over HTTP
    - RMI (probably too much work; easier to just make direct EJB calls)
    - JMS (probably more work than just using SOAP or HTTP)
    - Socket based communication with your own custom protocol
    Probably the fastest to get going is direct calls from swing to the EJB.
    You'll have to re-implement your application logic; but this is fine as the swing app will probably have a different flow than the web-app.
    Best of luck,
    Andrew

  • How can I create a my own dialog in awt or swings

    How can I create a my own dialog in awt or swings instead of JDialog,Joption.
    if possible some example.
    Thanks in advance
    bhaskar

    hi,
    just use the building blocks of of GUI components and their methods. For examlpe u want to write a Font Dialog box,
    use Frame with lists , thers is classes by which u can pick the all fonts installes on ur system. Do appropriate programming to event handlers . On last in event handler of 'OK' button get the selected item from list and assign to wht u want thats all...........

  • Swings and Threads

    My applet communicates with the database. To ensure that the GUI is updated in the Event-Dispatching Thread I am using a SwingWorker: in construct() the application communicates with DB, and in finished() it updates the GUI. In construct() of the SwingWorker thread I need to create a dialog box to prompt the user for an input like to chose a color or to answer yes/no.
    My question is: Do I need to use invokeAndWait() to create the dialog box? The more general question is: do we use invokeLater() or SwingWorker only for GUIs that are shared by several threads or we have to use it for every swing we create after Event-Dispatching Thread started running?
    Thank you

    One of the fun things about Swing and its EventDispatchThread is that
    doing things wrong (such as performing Swing operations from a thread
    other than the EDT) is that more often than not, even though they are done
    technically wrong, they will still appear to work, especially in small programs.
    (In a larger sense, this applies to any multi-threaded program: things might
    appear to work until the timing changes just a teensy bit...)
    What's even more fun is working with someone who has previously only
    done small programs and because of that, takes this approach in large programs, and then spending a large amount of time trying to figure out why
    something sporadically stops working, only to trace it back to a Swing
    operation being invoked from a thread other than the EDT. Fun!
    You know how to do it correctly.
    You know why to do it correctly.
    But you choose not to. Good luck with that.

  • Using swing and swt together

    i would like to use some of the components of swt such labels or buttons in swing as swt has better look and feel. but in all the examples i found they are using a whole set of swt api to create frames and showing them up.
    Isnt there any way to add button or label of SWT in Swing. i found a method SWT_AWT.newFrame(). But it is returning a awt frame not a Swing JFrame that at the frame level. i need them at individual component level(buttons and labels).
    hope u understood my problem.. any other suggestions??

    Swing and SWT are two different framework. Usually, peoiple choose one and stick with it. I would not mess with mixing SWT with Swing or vice-versa. I really don't understand why you would choose to mix these two framework together. "better look and feel" is not the best answer for this. what i would look into is a look and feel for Java (like JGoodies look n feel)..and check for Swing component that pther people have made (or enhance upon the Swing library).
    Stick with one framework. Your life will be much easier.
    Futhermore, maintainance would be less difficult. (you only have to know one framework instead of two, plus how they interact)

  • Catching events on Desktop , without using any AWT or Swing components.

    How can I catch events(for eg: mouse clicks) on the Desktop? I do not want to use any AWT or Swing components in my application.
    Also, i want to get events even some other java/non-java application windows are visible on desktop, as long as my application is running.

    Myrequirement is to capture all AWT events, regardless of on which component its being happened.
    I mean I have to capture events outside the current running application (on desktop and any other java/no-java appliation windows also).
    I couldn't find any other forum which discusses about event handling.
    This is part of my app. other end extensively uses awt.

  • Awt  V Swing in applets ???

    I've written an applet using Swing but I'm having huge problems trying to get it to run in Internet Explorer (even though it works in the Applet viewer).
    Someone suggested rewriting it using awt so that users with older browsers don't have to download a plugin to be able to view it? Is it necessary to download a plugin to view applets with Swing? Is this better to avoid using packages like Swing if possible, in your opinion? Please let me know what you think - I would like as many people as possible to be able to see the applet on their browsers.
    Thanks for your time.

    It's because of Microsoft and Sun falling out over Java, effectively Microsoft couldn't/wouldn't move beyond 1.1 which was AWT based. At some point in the not too distant future they will remove all Java support so at that point you will be reliant on a plug-in to get to the IE base.
    At the moment, if you've already done some AWT work and the GUI is simple, I'd stick with it, otherwise go to Swing and the plug-in. This is of course subjective, others would disagree strongly with me.
    Answer provided by Friends of the Water Cooler. Please inform forum admin via the 'Discuss the JDC Web Site' forum that off-topic threads should be supported.

  • Help Plz! AWT to Swing Conversion

    Hey everyone, I'm new to java and trying to convert this AWT program to Swing, I got no errors, the menu shows but they dont work !! Could somebody please help me? thanks alot!
    Current Under-Construction Code: (no errors)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class zipaint extends JFrame implements ActionListener,      ItemListener,
    MouseListener, MouseMotionListener, WindowListener {
    static final int WIDTH = 800;     // Sketch pad width
    static final int HEIGHT = 600;     // Sketch pad height
    int upperLeftX, upperLeftY;     // Rectangle upper left corner coords.
    int width, height;          // Rectangle size
    int x1, y1, x2, y2, x3, y3, x4, y4; // Point coords.
    boolean fillFlag = false; //default filling option is empty
    boolean eraseFlag = false; //default rubber is off
    String drawColor = new String("black"); //default drawing colour is black
    String drawShape = new String("brush"); //default drawing option is brush
    Image background; //declear image for open option
    private FileDialog selectFile = new FileDialog( this,
    "Select background (.gif .jpg)",
    FileDialog.LOAD );
    // Help
    String helpText = "Draw allows you to sketch different plane shapes over a " +
    "predefined area.\n" + "A shape may be eother filled or in outline, " +
    "and in one of eight different colours.\n\n" + "The position of the " +
    "mouse on the screen is recorded in the bottom left-hand corner of the " +
    "drawing area. The choice of colour and shape are disoplayed also in the " +
    "left-habnd corner of the drawing area.\n\n" + "The size of a shape is " +
    "determined by the mouse being dragged to the final position and " +
    "released. The first click of the mouse will generate a reference dot on " +
    "the screen. This dot will disapear after the mouse button is released.\n\n" +
    "Both the square and the circle only use the distance measured along the " +
    "horizontal axis when determining the size of a shape.\n\n" + "Upon " +
    "selecting erase, press the mouse button, and move the mouse over the " +
    "area to be erased. releasing the mouse button will deactivate erasure.\n\n" +
    "To erase this text area choose clearpad from the TOOLS menu.\n\n";
    // Components
    JTextField color = new JTextField();
    JTextField shape = new JTextField();
    JTextField position = new JTextField();
    CheckboxGroup fillOutline = new CheckboxGroup();
    JTextArea info = new JTextArea(helpText,0,0/*,JTextArea.JSCROLLBARS_VERTICAL_ONLY*/);
    JFrame about = new JFrame("About Zi Paint Shop");
    // Menues
    String[] fileNames = {"Open","Save","Save as","Exit"};
    String[] colorNames = {"black","blue","cyan","gray","green","magenta","red","white","yellow"};
    String[] shapeNames = {"brush","line","square","rectangle","circle","ellipse"};
    String[] toolNames = {"erase","clearpad"};
    String[] helpNames = {"Help","about"};
    public zipaint(String heading) {
    super(heading);
    getContentPane().setBackground(Color.white);
    getContentPane().setLayout(null);
    /* Initialise components */
    initialiseTextFields();
    initializeMenuComponents();
    initializeRadioButtons();
    addWindowListener(this);
    addMouseListener(this);
    addMouseMotionListener(this);
    /* Initialise Text Fields */
    private void initialiseTextFields() {
    // Add text field to show colour of figure
    color.setLocation(5,490);
    color.setSize(80,30);
    color.setBackground(Color.white);
    color.setText(drawColor);
    getContentPane().add(color);
    // Add text field to show shape of figure
    shape.setLocation(5,525);
    shape.setSize(80,30);
    shape.setBackground(Color.white);
    shape.setText(drawShape);
    getContentPane().add(shape);
    // Add text field to show position of mouse
    position.setLocation(5,560);
    position.setSize(80,30);
    position.setBackground(Color.white);
    getContentPane().add(position);
    // Set up text field for help
    info.setLocation(150,250);
    info.setSize(500,100);
    info.setBackground(Color.white);
    info.setEditable(false);
    private void initializeMenuComponents() {
    // Create menu bar
    JMenuBar bar = new JMenuBar();
    // Add colurs menu
    JMenu files = new JMenu("Files");
    for(int index=0;index < fileNames.length;index++)
    files.add(fileNames[index]);
    bar.add(files);
    files.addActionListener(this);
    // Add colurs menu
    JMenu colors = new JMenu("COLORS");
    for(int index=0;index < colorNames.length;index++)
    colors.add(colorNames[index]);
    bar.add(colors);
    colors.addActionListener(this);
    // Add shapes menu
    JMenu shapes = new JMenu("SHAPES");
    for(int index=0;index < shapeNames.length;index++)
    shapes.add(shapeNames[index]);
    bar.add(shapes);
    shapes.addActionListener(this);
    // Add tools menu
    JMenu tools = new JMenu("TOOLS");
    for(int index=0;index < toolNames.length;index++)
    tools.add(toolNames[index]);
    bar.add(tools);
    tools.addActionListener(this);
    // Add help menu
    JMenu help = new JMenu("HELP");
    for(int index=0;index < helpNames.length;index++)
    help.add(helpNames[index]);
    bar.add(help);
    help.addActionListener(this);
    // Set up menu bar
    setJMenuBar(bar);
    /* Initilalise Radio Buttons */
    private void initializeRadioButtons() {
    // Define checkbox
    Checkbox fill = new Checkbox("fill",fillOutline,false);
    Checkbox outline = new Checkbox("outline",fillOutline,true);
    // Fill buttom
    fill.setLocation(5,455);
    fill.setSize(80,30);
    getContentPane().add(fill);
    fill.addItemListener(this);
    // Outline button
    outline.setLocation(5,420);
    outline.setSize(80,30);
    getContentPane().add(outline);
    outline.addItemListener(this);
    /* Action performed. Detects which item has been selected from a menu */
    public void actionPerformed(ActionEvent e) {
    Graphics g = getGraphics();
    String source = e.getActionCommand();
    // Identify chosen colour if any
    for (int index=0;index < colorNames.length;index++) {
    if (source.equals(colorNames[index])) {
    drawColor = colorNames[index];
    color.setText(drawColor);
    return;
    // Identify chosen shape if any
    for (int index=0;index < shapeNames.length;index++) {
    if (source.equals(shapeNames[index])) {
    drawShape = shapeNames[index];
    shape.setText(drawShape);
    return;
    // Identify chosen tools if any
    if (source.equals("erase")) {
    eraseFlag= true;
    return;
    else {
    if (source.equals("clearpad")) {
    remove(info);
    g.clearRect(0,0,800,600);
    return;
    if (source.equals("Open")) {
    selectFile.setVisible( true );
    if( selectFile.getFile() != null )
    String fileLocation = selectFile.getDirectory() + selectFile.getFile();
    background = Toolkit.getDefaultToolkit().getImage(fileLocation);
    paint(getGraphics());
    if (source.equals("Exit")) {
    System.exit( 0 );
    // Identify chosen help
    if (source.equals("Help")) {
    getContentPane().add(info);
    return;
    if (source.equals("about")) {
    displayAboutWindow(about);
    return;
    public void paint(Graphics g)
    super.paint(g);
    if(background != null)
    Graphics gc = getGraphics();
    gc.drawImage( background, 0, 0, this.getWidth(), this.getHeight(), this);
    /* Dispaly About Window: Shows iformation aboutb Draw programme in
    separate window */
    private void displayAboutWindow(JFrame about) {
    about.setLocation(300,300);
    about.setSize(350,160);
    about.setBackground(Color.cyan);
    about.setFont(new Font("Serif",Font.ITALIC,14));
    about.setLayout(new FlowLayout(FlowLayout.LEFT));
    about.add(new Label("Author: Zi Feng Yao"));
    about.add(new Label("Title: Zi Paint Shop"));
    about.add(new Label("Version: 1.0"));
    about.setVisible(true);
    about.addWindowListener(this);
    // ----------------------- ITEM LISTENERS -------------------
    /* Item state changed: detect radio button presses. */
    public void itemStateChanged(ItemEvent event) {
    if (event.getItem() == "fill") fillFlag=true;
    else if (event.getItem() == "outline") fillFlag=false;
    // ---------------------- MOUSE LISTENERS -------------------
    /* Blank mouse listener methods */
    public void mouseClicked(MouseEvent event) {}
    public void mouseEntered(MouseEvent event) {}
    public void mouseExited(MouseEvent event) {}
    /* Mouse pressed: Get start coordinates */
    public void mousePressed(MouseEvent event) {
    // Cannot draw if erase flag switched on.
    if (eraseFlag) return;
    // Else set parameters to 0 and proceed
    upperLeftX=0;
    upperLeftY=0;
    width=0;
    height=0;
    x1=event.getX();
    y1=event.getY();
    x3=event.getX();
    y3=event.getY();
    Graphics g = getGraphics();
    displayMouseCoordinates(x1,y1);
    public void mouseReleased(MouseEvent event) {
    Graphics g = getGraphics();
    // Get and display mouse coordinates
    x2=event.getX();
    y2=event.getY();
    displayMouseCoordinates(x2,y2);
    // If erase flag set to true reset to false
    if (eraseFlag) {
    eraseFlag = false;
    return;
    // Else draw shape
    selectColor(g);
    if (drawShape.equals("line")) g.drawLine(x1,y1,x2,y2);
    else if (drawShape.equals("brush"));
    else drawClosedShape(drawShape,g);
    /* Display Mouse Coordinates */
    private void displayMouseCoordinates(int x, int y) {
    position.setText("[" + String.valueOf(x) + "," + String.valueOf(y) + "]");
    /* Select colour */
    private void selectColor(Graphics g) {
    for (int index=0;index < colorNames.length;index++) {
    if (drawColor.equals(colorNames[index])) {
    switch(index) {
    case 0: g.setColor(Color.black);break;
    case 1: g.setColor(Color.blue);break;
    case 2: g.setColor(Color.cyan);break;
    case 3: g.setColor(Color.gray);break;
    case 4: g.setColor(Color.green);break;
    case 5: g.setColor(Color.magenta);break;
    case 6: g.setColor(Color.red);break;
    case 7: g.setColor(Color.white);break;
    default: g.setColor(Color.yellow);
    /* Draw closed shape */
    private void drawClosedShape(String shape,Graphics g) {
    // Calculate correct parameters for shape
    upperLeftX = Math.min(x1,x2);
    upperLeftY = Math.min(y1,y2);
    width = Math.abs(x1-x2);
    height = Math.abs(y1-y2);
    // Draw appropriate shape
    if (shape.equals("square")) {
    if (fillFlag) g.fillRect(upperLeftX,upperLeftY,width,width);
    else g.drawRect(upperLeftX,upperLeftY,width,width);
    else {
    if (shape.equals("rectangle")) {
    if (fillFlag) g.fillRect(upperLeftX,upperLeftY,width,height);
    else g.drawRect(upperLeftX,upperLeftY,width,height);
    else {
    if (shape.equals("circle")) {
    if (fillFlag) g.fillOval(upperLeftX,upperLeftY,width,width);
    else g.drawOval(upperLeftX,upperLeftY,width,width);
    else {
    if (fillFlag) g.fillOval(upperLeftX,upperLeftY,width,height);
    else g.drawOval(upperLeftX,upperLeftY,width,height);
    /* Mouse moved */
    public void mouseMoved(MouseEvent event) {
    displayMouseCoordinates(event.getX(),event.getY());
    /* Mouse dragged */
    public void mouseDragged(MouseEvent event) {
    Graphics g = getGraphics();
    x2=event.getX();
    y2=event.getY();
    x4=event.getX();
    y4=event.getY();
    displayMouseCoordinates(x1,y1);
    if (eraseFlag) g.clearRect(x2,y2,10,10);
    else {
    selectColor(g);
    if(drawShape.equals("brush")) g.drawLine(x3,y3,x4,y4);
    x3 = x4;
    y3 = y4;
    // ---------------------- WINDOW LISTENERS -------------------
    /* Blank methods for window listener */
    public void windowClosed(WindowEvent event) {}
    public void windowDeiconified(WindowEvent event) {}
    public void windowIconified(WindowEvent event) {}
    public void windowActivated(WindowEvent event) {}
    public void windowDeactivated(WindowEvent event) {}
    public void windowOpened(WindowEvent event) {}
    /* Window Closing */
    public void windowClosing(WindowEvent event) {
    if (event.getWindow() == about) {
    about.dispose();
    return;
    else System.exit(0);
    Code End
    Thanks again!
    class ziapp {
    /* Main method */
    public static void main(String[] args) {
    zipaint screen = new zipaint("Zi Paint Shop");
    screen.setSize(zipaint.WIDTH,zipaint.HEIGHT);
    screen.setVisible(true);

    First of all use the [url http://forum.java.sun.com/features.jsp#Formatting]Formatting Tags when posting code to the forum. I'm sure you don't code with every line left justified so we don't want to read unformatted code either.
    Hey everyone, I'm new to java and trying to convert this AWT program to SwingInstead of converting the whole program, start with something small, understand how it works and then convert a different part of the program. You can start by reading this section from the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html]How to Use Menus.
    From a quick glance of your code it looks like you are not adding an ActionListener to your JMenuItems. You are adding them to the JMenu.
    Other observations:
    1) Don't mix AWT with Swing components. You are still using CheckBox
    2) Don't override paint(). When using Swing you should override paintComponent();
    3) Use LayoutManagers. Using a null layout does not allow for easy maintenance of the gui. Right now you are using 800 x 600 as your screen size. Most people are probably using at least 1024 x 768 screen sizes. When using LayoutManagers you would suggest component sizes by using setPreferredSize(), not setSize().

  • From awt to swing = classcastexception ?

    Hi !
    I am trying to move from awt to swing (j2sdk1.4.0_01)
    On recompiling with javac, no visible errors, nor when I try to debug with jdb.
    However when I try to load the class file, the java console tells me that I have a ClassCastException. Going thru the codes, I cannot see where I have type-casted anything wrong !
    Can someone point me in the right direction ?
    THX

    Hi !
    Tried some very simple codes...
    import javax.swing.*;
    public class TreeExample
    public static void main(String args[])
    JFrame frame = new JFrame("The Tree");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(250,250);
    frame.show();
    jdb will run it and display it in an appletviewer
    window, but IE and Netscape will report a
    ClassCastException...
    At this point I think it might be some plug-ins ?The example you gave isn't an applet. Were you trying to run this exact code in a browser or was this just a sample? If you are trying to run this in a browser, it's probably trying to cast your TreeExample class to an Applet, which would explain the ClassCastException.

  • AWT vs SWING vs JAVA 2D vs JFC

    Hi,
    can you please describe or show me the path to find the difference
    among 4. (mentioned in subject line)
    The basic difference i know, what i want is how to decide when to use
    what?
    In my view, awt is used no where these days.
    swing and Java 2D (what is this?) are used mostly but which to choose
    for my application, how to decide? and What is JFC all about?
    sometimes it becomes very confusing.
    Can anyone throw some light on these terms.
    - Thanks
    Azodious
    Edited by: Azodious on Jan 26, 2008 5:23 AM

    Azodious wrote:
    i didn't search on Google because here experts have some special answers. by special answers i mean less words but exact answer. with a lot of learning.
    i am expectng those kind of answers.You may be waiting a long time. Your question is very broad, very general, and most experts would likely refer you to reference sources.
    This may be a language thing, but to say you "expect" answers is awfully presumptuous.
    otherwise i'd to go through all those many pages again and again to grasp a simple but conceptual thing.Have at it.

Maybe you are looking for