AWT Canvas vs. Swing "glass pane"

Hello again world.
The book I've been reading led me down the Swing path but I thought I would go back and take a closer look at the AWT package.
Is an AWT Canvas analogous to a Swing JRootPane's glass pane?
Thank you one and all.
Ciao for now.

No, not really.
1) A Canvas is specifically for drawing. There's really no other purpose for it to exist. It's not a container, like Panel. Although, you can use AWT Panel in place of a Canvas, there'd be nothing wrong with that.
A glasspane has a purpose in a JFrame or other top-level Swing container. It's there to be shown, but often transparently, on top of all other components in that top-level container. You can make the glasspane be any class, yes, but generally it's going to be a JPanel or subclass, and you could paint on it if you override the paintComponent method, or add mouse listeners to intercept mouse events (when it's visible).
That you can draw on a Canvas or a glasspane component is irrelevant. One can can subclass JButton or JTree or AWT List or any other AWT or Swing component and override the paint or paintComponent method and do custom painting on it. The ability to paint on components is universal. But you wouldn't use a JButton or AWT Button for a glasspane.
2) You don't want to use Canvas as a glass pane (or any AWT component) if you want the pane to be transparent. AWT components cannot be transparent, so if the component is visible, it'll block out anything under it. It's the whole issue of AWT's heavyweight components vs Swing's lightweight components.

Similar Messages

  • Swing component for awt.canvas

    Hi,
    Can anyone tell me the equivalent SWING component for awt CANVAS. I need it because i need to display only Images (nothing else) on it. If anyone can tell how I can do it.

    JPanel is the Swing-equivalent of java.awt.Canvas, but if you are just displaying images, you can use the JLabel class, which supports use of images as icons (see also ImageIcon class).
    Mitch Goldstein
    Author, Hardcore JFC (Cambridge Univ Press)
    [email protected]

  • How can I block the keyboard using the glass pane ?

    I have a problem with the GlassPaneDemo from the Java Tutorial in
    the
    uiswing/components/example-swing
    folder.
    When the glass pane is visible it blocks the mouse input but the
    keyboard input doesn't. For example if the glass pane is visible and
    you press the F10 key, the menu will be activated. So the keyboard is
    not at all blocked.
    Can this problem be fixed ? I mean, to really block the keyboard
    when the glass pane is visible.
    Here I wrote down the specification written in the
    Java Documentation at the setGlassPane method from the
    RootPaneContainer interface:
    The glassPane is always the first child of the rootPane and the
    rootPanes layout manager ensures that it's always as big as the
    rootPane. By default it's transparent and not visible. It can be
    used to temporarily grab all keyboard and mouse input by adding
    listeners and the making it visible. by default it's not visible.
    As it may be seen, one says that the keyboard input can be blocked.
    HOW ?
    In hope that I resolve the problem, I have made some changes such as,
    adding a key listener to the glass pane add listening to the keyboard events,
    but I failed to fix the problem.
    Faithfully yours,
    Sarmis

    Here is an example that I think will work for you.
    Note the consume() call on the event object. I think that is what you're after.
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    public class Comparer extends JFrame implements ActionListener
        private GlassComponent myGlassPane;
        private JTextField myField;
        public Comparer()
            getContentPane().setLayout(new FlowLayout());
            getContentPane().add(myField = new JTextField(20));
            setGlassPane(myGlassPane = new GlassComponent());
            JButton theButton = new JButton("Glass");
            theButton.addActionListener(this);
            getContentPane().add(theButton);
            pack();
        public void actionPerformed(ActionEvent anEvent)
            myGlassPane.setVisible(true);       
        public static void main(String[] args)
            new Comparer().setVisible(true);       
    class GlassComponent extends JComponent implements AWTEventListener
        Window myParentWindow;
        public GlassComponent()
            super();
            this.setCursor( Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR) );
            setOpaque(false);
            addMouseListener( new MouseAdapter() {} );
        public void setVisible(boolean aVisibleBoolean)
            if(aVisibleBoolean)
                if(this.myParentWindow == null)
                    this.myParentWindow = SwingUtilities.windowForComponent(this);
                Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.KEY_EVENT_MASK);
            else
                Toolkit.getDefaultToolkit().removeAWTEventListener(this);
            super.setVisible(aVisibleBoolean);
        public void eventDispatched(AWTEvent anEvent)
            if(anEvent instanceof KeyEvent && anEvent.getSource() instanceof Component)
                if(SwingUtilities.windowForComponent( (Component)anEvent.getSource()) == this.myParentWindow )
                    ((KeyEvent)anEvent).consume();
    } HTH,
    Fredrik

  • Redrawing glass pane

    Hi, I have a program where I am storing information which takes up some time. I created a progressbar and put it in the glass pane and update it several times during this process. Below i posted a simplified example. In this example it works as it should and the progress bar gets redrawn every time I call pb.update().
    However the code I use in the application is complex and the progress bar does not get drawn onto the screen until the method finishes, which is too late. I have tried putting repaint() calls at the end of the update() method, but that does not work. Although the program enters the paint method, nothing gets drawn onto the screen. The only thing that helped was paintimmediately(), which painted the contentPane() on the screen, but did not paint the glassPane.
    My question is, how does java determine when to redraw the glass pane, since I don't have a repaint() call anywhere. Is there a way to force java to draw the glasspane on the screen? Or if you have any tips as to what could be the problem.
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    public class Main extends JFrame {
       public Main() {
         setSize(200,50);
         setVisible(true);
         ProgressBar pb = new ProgressBar();
         setGlassPane(pb);
         pb.setVisible(true);
         Thread t = new Thread();
         try {
             t.sleep(1000);
             pb.update();
             t.sleep(1000);
             pb.update();
             t.sleep(1000);
             pb.update();
             t.sleep(1000);
             pb.update();
             t.sleep(300);
         } catch ( Exception e ) {}
         pb.setVisible(false);
        public static void main(String[] args) {
         JFrame.setDefaultLookAndFeelDecorated(true);
         Main app = new Main();
         app.addWindowListener(
            new WindowAdapter() {
               public void windowClosing( WindowEvent e )
              System.exit( 0 );
    public class ProgressBar extends JComponent {
    JProgressBar jProg;
    int cur;
        public ProgressBar () {
         init();
         cur = 0;
         setOpaque(false);
        public void init() {
            jProg = new javax.swing.JProgressBar(0,100);
         jProg.setValue(0);
         jProg.setStringPainted(true);
         jProg.setSize(200,30);
         add(jProg);
       public void update() {
         cur += 25;
         jProg.setValue(cur);
    }

    Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html]How to Use Progress Bars for a working example. You should also read the section from the tutorial on "How to Use Threads" since you are not using the Thread correctly in you simple demo.

  • Why glass pane requires setLightWeightPopupEnabled(false)?

    In the code below, the glass pane is a JPanel which everybody knows is a Swing lightweight component. Then why JComboBox requires setLightWeightPopupEnabled(false) for its proper functioning? What on earth does the method, in the first place? Why glass pane? What oddity in the hell does the glass pane have that other Swing component doesn't, never?
    import javax.swing.*;
    import java.awt.*;
    public class GlassPaneOddity{
      public static void main(String[] args){
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel gp = new JPanel(new BorderLayout());
        frame.setGlassPane(gp);
        JComboBox cb
          = new JComboBox(new String[]{"alpha", "beta", "gamma", "delta"});
        cb.setLightWeightPopupEnabled(false); // why this line is so critical?
        gp.add(cb, BorderLayout.NORTH);
        frame.setSize(300, 300);
        frame.setVisible(true);
        gp.setVisible(true);
    }

    This is a quite interesting subject:
    The JRootPane has basically 2 components (although its layout is managing a few more):
    - the glasspane
    - the layered pane
    The z-order of components inside containers (so also for JRootPane) is defined to be:
    - index 0 is highest
    - index 1 is lower but higher than 2 etc...
    The glasspane is added always on index 0 (meaning highest)
    The layered pane is added after (meaning lower)
    Inside the layered pane are added:
    - the content pane
    - the menubar
    And the layout of the rootpane (RootLayout) takes care of the positioning of the glasspane, layered pane, content pane and the menubar.
    The layered pane has a layer for content (containing contentpane and menubar) but also for popups. The popups are shown on top of the content pane, but always under the glasspane.
    As far as I can see this seems to be in line with the explanation under the rootpane tutorial. And in line with Michael's observation.
    Hope it helps,
    Marcel

  • Why Glass Pane becomes visible when resizing JInternalFrame?

    This qustion has been asked _*here*_ but got no response.
    Hello,
    I've created a JFrame with JDesktop and one JInternalFrame on it. I've also added a glasspane (which draws a black circle only) to JFrame - it's invisible by default but when I resize JInternalFrame it shows up.. is this correct behavior? Why it is visible only when I resize and diappears when I release mouse button after resize? How I can make it invisible when resizing JInternalFrame? (Is removing JFrame's glasspane only solution?)import java.awt.Graphics;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JPanel;
    public class RunMe extends JFrame {
         public RunMe() {
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setBounds(10, 10, 800, 600);
              JDesktopPane desktop = new JDesktopPane();
              JInternalFrame testJIF = new JInternalFrame("test", true, true, true, true);
              testJIF.setBounds(10, 10, 100, 100);
              desktop.add(testJIF);
              testJIF.setVisible(true);
              this.add(desktop);
              this.setGlassPane(new MyGlassPane());
              this.setVisible(true);
         private class MyGlassPane extends JPanel {
              public MyGlassPane() {
                   this.setOpaque(false);
              @Override
              protected void paintComponent(Graphics g) {
                   g.fillOval(0, 0, 100, 100);
                   super.paintComponent(g);
         public static void main(String[] args) {
              new RunMe();
    }

    First of all, thank you for being upfront about cross posting.
    Whether this is "correct" behavior or not may be debatable, but it's certainly expected behavior. From the source of javax.swing.plaf.basic.BasicInternalFrameUI.BorderListener.mousePressed (towards the end of the method)Container c = frame.getTopLevelAncestor();
    if (c instanceof RootPaneContainer) {
       Component glassPane = ((RootPaneContainer)c).getGlassPane();
       glassPane.setVisible(true);
       glassPane.setCursor(s);
    }The glass pane is made visible to show the resize cursor.
    It's set back to visible(false) in finishMouseReleased() which is invoked from mouseRelease and elsewhere (e;g; from cancelResize which is invoked from windowLostFocus)
    Looks like you can't use the glass pane for whatever you had planned, the Swing designers have already used it for something else. Or this could be a workaround, depending on exactly what it is you're trying to do.@Override
    protected void paintComponent(Graphics g) {
       super.paintComponent(g);
       if (this.isOpaque()) {
          g.fillOval(0, 0, 100, 100);
    }You could also declare and use a boolean flag, rather than using isOpaque (which may happen to be set/reset somewhere else in the Swing code ;-)
    db

  • Resizing glass pane

    Disabling GUI controlls causing the loose of the controls beauty.
    However, sometimes it is neccessary, to display the control in
    a uneditable mode, especially when the input can not be consumed.
    The perfect idea to maintain the beauty of the GUI contorls and
    make them uneditable, is to put a glass infront of them, so you just
    look from pattern :).
    This is a greate idea provided through GlassPane in the Swing API.
    But, still there is a limitation, why?
    The glass pane should be as large as the JRootPane, which means
    that you have to cover the whole top-level container :(.
    Take this example:
    I have a TabbedPane that consists of multiple tabs and the tabbed pane is loacted in a JApplet. I need to move between the tabs while making the controls in side the tabbs uneditable. Here I was constrained by the
    Glass Pane since it covers the whole applet's area, and no more accessability to the tabbs.
    Some one said: redispatch the event to the TabbedPane, I said: Ok, but
    no method in the TabbedPane tells me which tab has the x,y point.
    I suggest to make the GlassPane resizable, and to provide a method in
    the TabbedPane which takes the x,y a returns the index of the selected
    tab.
    Please what do you think ? :-)

    I think it is not useful because you can create your own glasspane for any component you want !
    Look at this thread :
    http://forum.java.sun.com/thread.jsp?forum=57&thread=268566
    I hope this helps,
    Denis

  • Can I draw *.bmp, *.png in java.awt.canvas ?

    In paint method of my program, I get image from Toolkit like this:
    public class CanCanvas extends Canvas{
    //In loadImage method
    Toolkit.getDefaultToolkit().getImage(
                        getClass().getClassLoader().getResource(
                                  resource.getString("bg.jpg")));
    //.... In paint method
    if (image != null && image.size() > 0) {
                   for (int j = 0; j < image.size(); j++) {
                        Image image1 = (Image) image.elementAt(j);
                        Rectangle rectangle = (Rectangle) imgLocation.elementAt(j);
                        g.drawImage(image1, rectangle.x, offset + rectangle.y,
                                  rectangle.width, rectangle.height, null);
                        i = i <= rectangle.y + rectangle.height + 7 ? rectangle.y
                                  + rectangle.height + 7 : i;But there is something very strange, if my image is *.jpg or *.gif, it runs ok, otherwise -*.bmp, *.png-, it can't draw the image.
    Would anyone tell me why ? Is the reason java.awt.canvas ?
    Thanks in advance ^ ^

    If you'd bother to read the documentation of the methods you're using, you'd know:
    http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Toolkit.html#getImage(java.lang.String)
    Returns an image which gets pixel data from the specified file, whose format can be either GIF, JPEG or PNG.

  • Different glass pane behaviour in Mac and Windows

    I have an application with a glass pane containing a panel that is set non-opaque. On this panel I do amouse drag and draw a transparent rectangle when the mouse is released. On the main frame below there is a picture. This works fine on a Mac, I end up with a transparent rectangle on top of the bottom frame. However, when I run the same program on a Windows machine, as soon as the mouse is released, the rectangle is drawn and the glass pane layer gets opaque, hiding the picture below.
    Any solutions?

    >
    I'd suggest you to post some code. ...>Some code is good, but an SSCCE is better. ;-)

  • Glass pane  how to use it?

    please i am new to Java i wanted toknow more about the glass pane component why cant it be use as the content pane .

    google is your friend
    http://java.sun.com/docs/books/tutorial/uiswing/components/rootpane.html#glasspane

  • Glass Pane( preventUserInput when user clicks on Search button in af:query)

    Hi,
    We are using glass pane implementation on a search screen.
    When I click on Search button in af:query component (having selectInputDate (Date Picker) components)., glass pane is firing correctly,
    but second time when I am trying to select date using Date Picker (and Change the Month), glass pane is fired (entering into handleBusyState function) and calendar popup is not opening.
    I folled the below article for implementation.
    url: http://www.oracle.com/technetwork/developer-tools/adf/learnmore/27-long-running-queries-169166.pdf used for glassPane implementation.
    Can any one help me for this issue.

    Hi am using the following code (javascript) -- Jdev(11.1.1.3)
    function preventUserInput(evt){   
    var eventSource = evt.getSource();
    var popup1 = eventSource.findComponent("showGlassPanePopup");
    if (popup1 != null){
    AdfPage.PAGE.addBusyStateListener(popup1,handleBusyState);
    evt.preventUserInput();
    //JavaScript call back handler
    function handleBusyState(evt){ 
    var popup = AdfPage.PAGE.findComponentByAbsoluteId('r3:0:r1:0:showGlassPanePopup');
    if(popup!=null){
    if (evt.isBusy()){
    popup.show();
    } else if (popup.isPopupVisible()) {
    popup.hide();
    AdfPage.PAGE.removeBusyStateListener(popup, handleBusyState);
    ... End of Code..
    This line .. (popup.isPopupVisible()) removes the Popup , if popup is visible...
    If u want the view am using..
    SELECT EMPNO , DEPTNO , HIREDATE FROM EMPLOYEE (sample Application i have created), created a view criteria for this..
    ( (EMPNO = :empNum ) AND (DEPTNO = :deptNum ) AND (TO_CHAR( TO_TIMESTAMP(HIREDATE), 'yyyy-mm-dd hh24:mi:ss.ff') = :hireDts ) ) (View Criteria)
    .. <af:clientListener method="enforcePreventUserInput" type="query"/> (added for af:query)
    Popup Used: <af:popup id="showGlassPanePopup" contentDelivery="immediate">
    <af:dialog id="d2" type="none" closeIconVisible="false">
    <af:panelGroupLayout id="panelGroupLayout1" layout="vertical">
    <af:outputText value="Processing......Please Wait.." id="ot97"/>
    </af:panelGroupLayout>
    </af:dialog>
    </af:popup>
    1. When i click search for first time.. it is showing like -- Processing .. Please Wait'
    2. When i click select Date picker it is show -- Processing .. Please Wait'
    and show a calender popup window.. If we change the month ... it will again show like -- Processing .. Please Wait'
    and it will not open calender window.
    Please Help me on this..Am facing trouble due to this.
    Thanks in Advance.
    Edited by: user10115793 on Nov 15, 2011 12:58 AM

  • Changing AWT components to Swing components

    I'm having a little trouble changing some AWT components to Swing components. I received an error message when I tried to run my program. I looked up the component in the java docs. But, I did not see the option the error was talking about. The error and the area of code is listed below. Thank you for any help you can provide.
    Error message:
    Exception in thread "main" java.lang.Error: Do not use P5AWT.setLayout() use P5A
    WT.getContentPane().setLayout() instead
    at javax.swing.JFrame.createRootPaneException(JFrame.java:446)
    at javax.swing.JFrame.setLayout(JFrame.java:512)
    at P5AWT.<init>(P5AWT.java:56)
    at P5AWT.main(P5AWT.java:133)
    Press any key to continue . . .
    Code:
    JPanel p3 = new JPanel();
    p3.setLayout(new FlowLayout(FlowLayout.CENTER));
    ta = new JTextArea(20, 60);
    p3.add(ta);
    setLayout(new FlowLayout(FlowLayout.CENTER));
    add(p3);

    you need to change the line...
    setLayout(new FlowLayout(FlowLayout.CENTER)); to
    getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));

  • Why is it that awt.canvas does not show in javafx

    I wrapped an AWT canvas using a JPanel as a SwingComponent in JavaFX in order to use jvlc to view a video. When calling this JPanel from a JFrame it renders fine and I see the video which is sent there. When I put the SwingComponent on a scene in a stage, I only seem to see the Panel, I don't see the rendered video on the canvas, I got no exception and I can hear the audio. I don't understand why the canvas doesn't render. Does someone have a solution or an explanation?
    Has anyone succeeded in using jvlc with JavaFX?
    Thanx

    Search AWT on the forum.
    Several people asked how to use it in JavaFX, nobody gave a usable answer...
    One of the answer (from me...) concludes that mixing heavyweight component with a pure graphical scenegraph is probably not possible (at least for end-users like us), particularly if said scenegraph is drawn using OpenGL or DirectX.
    Just my (uninformed) opinion.

  • Splitpane under a glass pane

    I have a lot of components under a transparent glass pane.
    I dispatch mouse events captured by the topmost glasspane
    to underling components converting coordinates with
    SwingUtilities methods.
    Everything works fine except a splitpane. When a try to
    resize one of the components it contains, nothing happens.
    validate(), repaint() methods invoked on the split at event
    dispatching time are completely unusefull.
    The glasspane gets MouseListener and MouseMotionListener
    events.
    Whats the trik to get the split working?
    Thanks.

    Thanks for the response. The application I am writing has a split pane down the middle, with a glasspane on each side already over what are called View containers. However, a View in either of those containers may contain another splitpane.
    I was hoping for a simpler framework style solution such that the developers of a View would not be required to implement their own glasspane functionality and have to tie into the active View management.
    My current recourse is to utilize the KeyboardFocusManager to attempt to accomplish what I was trying to do with the GlassPane: set the active view based on selection in any portion of the View (component or empty Panel area). Got the first half working pretty easily, I expect the second have to be quite more challenging.
    Thanks again.

  • Glass pane in popup

    I have a button on click i will load a popup window. I want to show a glass pane and splash screen in the popup. How can I do that on click of parent screen command button ?
    <af:commandImageLink text="#{row.ProjectName}" id="cil1"
    action="dialog:callEditProject"
    useWindow="true"
    windowEmbedStyle="inlineDocument"
    windowModalityType="applicationModal"
    windowHeight="500" windowWidth="900"
    launchListener="#{EditProjectLaunchBean.launchEditProject}"/>
    I am able to do a glasspane splash screen on the same window using the example
    http://www.oracle.com/technetwork/developer-tools/adf/learnmore/27-long-running-queries-169166.pdf
    Thanks
    Suneesh

    I got the same problem. Is there any solution yet??

Maybe you are looking for

  • Linkage and performance problems with "Additional source folders"

    Hello There seems to be a some problems when using "additional source folders" in Flash Builder 4.5 and 4.5.1 (links to folders outside a project see pic below). Hopefully I'm doing something wrong and some kind soul could point it out. I have a libr

  • How do you change the document settings of an alternate layout?

    When you create an alternate layout this modal pops up allowing you to choose a page size with width and height dimensions. After you've selected "OK" how to you get back to this modal? When you go to File > Document Settings it only shows the settin

  • How do i fix [The iPod "iPod" could not be restored. an unknown error occured -1]

    I've been looking through all the discussions regarding similar problems (with different error codes), but all i know is that I cannot restore, I cannot turn on/off my iPod, and I cannot find a discussion to fix this issue.  Any insight would be grea

  • Ipod touch and itunes sync

    ok...I now have a Mac Pro Notebook. I want to get allllllll of my songs into my itunes library. However, it will only sync the songs "purchased" on my ipod. How do I get them all from my ipod touch without having to download to a jump drive from my o

  • OIM installation with Oracle db Standard Edition

    The 11g version of OIM, OAM works with Oracle 11g db Enterprise Edition. Will these components work with Oracle db 11g Standard Edition ? If this works then I am planning to use only for prototype purpose, where I can use a low end server.