Jdialog paint

How does the painting work on a JDialog window ? I am opening a JDialog on clicking a button and on that Jdialog has 2 jpanels. one with a jbutton and other panel for just painting a image. on the top of the image the user can draw rectangles. where should i put the code for mousedragged event ??

here is my code. please run after replacing the image URL. I ned to draw rectangles on top of the image...it draws but something is not right
import java.net.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class MapDialog extends JDialog implements MouseMotionListener{
     JButton btnMap,btnCancel;
     JLabel lblImage;
     JPanel pnlButtons,pnlImage;
     Image  im;
     int locationx,locationy;
     int startx,starty;
     boolean bIsMouseDragged;
     int counter;
     int rectPoints[];
     int iRectCounter;
     String[] strCoords;
     public MapDialog() {
          rectPoints = new int[200];
          strCoords = new String[200];
          addMouseMotionListener(this);
               MyMouseListener mml = new MyMouseListener();
               addMouseListener(mml);
               pnlButtons = new JPanel();
               pnlImage = new JPanel();
               btnMap = new JButton("Save");
               btnCancel = new JButton("Cancel");
               pnlButtons.add(btnMap);
               pnlButtons.add(btnCancel);
               getContentPane().add(pnlImage, BorderLayout.CENTER);
               getContentPane().add(pnlButtons, BorderLayout.SOUTH);
               pack();
               Toolkit tk = Toolkit.getDefaultToolkit();
               Dimension d = tk.getScreenSize();
               setLocation(((int)d.getWidth() /2 ) - getWidth() / 2  , ((int)d.getHeight() / 2) - getHeight() / 2);
          public void paint(Graphics g) {
                         System.out.println("paint called");
                         validate();
                         super.paint(g);
     public void paintComponents(Graphics g) {
          System.out.println("pc called");
          Graphics g2 = pnlImage.getGraphics();
          try {
                         URL url = new URL("http://localhost/java/mapedit2/images/leftart.jpg");
                         im = Toolkit.getDefaultToolkit().getImage(url);
                         MediaTracker mt = new MediaTracker(this);
                         mt.addImage(im, 0);
                         try {
                              mt.waitForAll();
                         } catch (InterruptedException e) {}
                    } catch(MalformedURLException ure) {System.out.println("exception");}
          g2.drawImage(im,0,0,this);
          if( bIsMouseDragged) {
                              g2.drawLine(startx,starty,locationx,starty);
                              g2.drawLine(startx,starty,startx,locationy);
                              g2.drawLine(startx,locationy,locationx,locationy);
                              g2.drawLine(locationx,starty,locationx,locationy);
     //     g2.dispose();
     public void mouseDragged(MouseEvent me) {
                         locationx = me.getX();
                         locationy = me.getY();
                         bIsMouseDragged = true;
                         repaint();
                    public void mouseMoved(MouseEvent me) {
                                   //System.out.println(me.getX());
          class MyMouseListener extends MouseAdapter {
                         public void mousePressed(MouseEvent me) {
                                        startx = 0;
                                        starty = 0;
                                        locationx = 0;
                                        locationy = 0;
                                        System.out.println("start X : " + me.getX());
                                        System.out.println("start Y : " + me.getX());
                                        startx = me.getX();
                                        starty = me.getY();
                                        //repaint();
                         public void mouseReleased(MouseEvent me) {
                              int rectWidth = (int) Math.sqrt( (locationx - startx) * (locationx - startx));
                              int rectHeight = (int) Math.sqrt( (locationy - starty) * (locationy - starty));
                              System.out.println("iRectCounter " + iRectCounter);
                              rectPoints[iRectCounter] = startx;
                              rectPoints[iRectCounter+1] = starty;
                              rectPoints[iRectCounter+2] = rectWidth;
                              rectPoints[iRectCounter+3] = rectHeight;
                              iRectCounter += 4;
                              System.out.println("end X : " + me.getX());
                              System.out.println("end Y : " + me.getX());
                              bIsMouseDragged = false;
                              // THIS IS THE LINE THAT POPS UP THE HTTP ENTERING VALUE
                              //AddlinkDialog2 aldialog = new AddlinkDialog2(ImagePanel.this, true);
     public static void main(String[] args) {
          //JFrame frame = new JFrame();
          //frame.add(
          MapDialog md = new MapDialog();
          md.pack();
          md.setVisible(true);
          md.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
     }

Similar Messages

  • JDialog dances or flickers

    Hi,
    I've been experiencing Jdialog dragging problems. I've made myself a custom JDialog in which i've removed the windows' default Border, placed a JPanel in the JDialog, painted a TitleBorder in it and managed the drag options when the mouse is correctly positionned on the TitleBorder.
    My problem is that when i drag the dialog, it frickles generously in every ways. Anybody have a clue???
    Here's a portion of my code:
    public void initDialog(Component componentToShow)
       JDialog dialog = new JDialog();
       JPanel borderPanel = new JPanel();
       TitleBorder border = BorderFactory.createTitleBorder(strTitle);
       borderPanel.setBorder(border);
       dialog.setUndecorated(true);
       dialog.setResizable(false);
       dialog.getContentPane().removeAll();
       dialog.getContentPane().setLayout(TableLayout.createDefaultLayout(FILL_TYPE)); //this is a custom layout
       dialog.getContentPane().add(borderPanel, "1,1");
       borderPanel.setLayout(TableLayout.createDefaultLayout(FILL_TYPE));
       borderPanel.add(componentToShow, "1,1");
       DialogMouseListener mouseListener = new DialogMouseListener(dialog);
       borderPanel.addMouseMotionListener(mouseListener);
       borderPanel.addMouseListener(mouseListener);
    private static class DialogMouseListener implements MouseMotionListener, MouseListener
       private JDialog dialog = null;
       private Point origin = null;
       public DialogMouseListener(JDialog objDialog)
          dialog = objDialog;
          origin = new Point();
       public void mouseDragged(MouseEvent e)
          Point p = dialog.getLocation();
          if (objDialog != null && origin.getY() <= 26) // 26 = TitleBorder Height
             dialog.setLocation(p.x + e.getX() - origin.x, p.y + e.getY() - origin.y);
       public void mousePressed(MouseEvent e)
          origin.x = e.getX();
          origin.y = e.getY();
       //other events are empty so not shown here...
    }Tanks a bunch for the help

    Maybe this will help:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=599181
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • How to position a window behind its owner

    Have you seen these slide out panels on OS X? For example, if you use Preview to view multiple images, a panel will slide out from behind the window, with thumbnails of the images. I have seen similar things on other applications. The effect is that a panel slides out from behind the window.
    I want to use this effect to add help information to my dialogs. You click on the "info" icon, and a frameless window slides out from behind the dialog, with additional information.
    In any case, I have most of it working. The dialog is a JDialog. The slide-out window is a frameless JWindow with the JDialog as its parent.
    The only problem I have been unable to solve, is how to make the slide-out window appear behind its owner. I tried calling toFront() on the parent, but that does not do it. Calling toBack() on the child does not have the desired effect either. The child window remains in front. How do I control the depth of a window, relative to its owner?
    -Ron.

    I think it should be something about focus and modality (just like other users said).
    Anyway, if nothing really works, you could override the JDialog paint method so that everything that is supposed to be 'under' the owner doesn't get painted (calling super and clipping returned graphics may be enough already), could this work?
    Bye.

  • Paint background of a JDialog

    Hey,
    i have a quite simple problem: I want to paint the background of my own JDialog, but i dont know how. I looked for a method like paintComponent(Graphics g) like in a JPanel, but there is no function. So i overwrite the method paint(Graphics g) but this doesnt work because my JList and JButtons on the dialog won?t be shown anymore.
    Any idea? Thanks a lot.
    Ohnoooooo!

    OhNo wrote:
    i have a quite simple problem: I want to paint the background of my own JDialog, but i dont know how. I looked for a method like paintComponent(Graphics g) like in a JPanel, but there is no function. On looking through the forum, I've found threads such as this one:
    http://forum.java.sun.com/thread.jspa?threadID=5257250&tstart=30
    Where it is recommended to do custom painting in a BufferedImage, then draw the BufferedImage in a JPanel's paintComponent override. Then add your JList, JButtons, and whatnot to the same JPanel. And then finally add the JPanel to the contentPane of the JApplet and you should be good to go.
    Many here have their GUI programs produce a JPanel as the final product. This increases flexibility quite a bit, since if the GUI is needed as a JFrame, simply add the JPanel to a JFrame, if a dialog, add the panel to a JDialog, and finally if a JApplet is needed, simply add the JPanel to the JApplet.
    Good luck!

  • Non-modal JDialog is not painted and blocks the GUI

    I have developed a GUI that's basically a JFrame with a JDesktopPane.
    The user can, via a menu item, pop up a JDialog that contains some JLists and then select some value from it. Once he/she has done the selection and clicks on OK, the dialog disappears (data processing is then done in the main GUI) and comes back once a specific event has happened. The user then selects other data and so on, until he/she clicks on Cancel, which definitely disposes of the JDialog.
    The graphics of the JDialog are build in the class constructor, which does a pack() but does not make the dialog visible yet. The dialog appears only when doSelection() is called.
         /** Called the first time when user selects the menu item, and then
         when a specific event has happened. */
         public Data[] doSelection() {
              dialog.setVisible(true);
              // ... Code that reacts to user's input. Basically, the ActionListener
              // added to the buttons retrieves the user's selection and calls
              // dialog.setVisible(false) if OK is clicked, or calls dialog.dispose()
              // if Cancel is clicked.
         }Now, everything works fine if the JDialog is modal, but if I make it non-modal only the window decorations of the JDialog are painted, and the control doesn't return to the main GUI. Calling doLayout() or repaint() on the doSelection() has no effect. How can this be fixed?
    I hope I have been able to explain the problem satisfactorily, I could not create a suitable SSCCEE to show you. Thanks in advance for any hint.

    Ok, I've taken some time to think about this problem and I've modified the code a bit.
    Now the dialog shows itself and is responsive (i.e. its JLists can be operated), but the Ok button does not close the dialog as I'd want. I believe that I'm messing up things about threading, and the operations in actionPerformed() should be carried out in another thread, if possible.
    Thanks in advance for any hint / suggestion / comment / insult.
         private Data[] selection;
         /** Constructor */
         public MyDialog() {
              // ... Here is the code that builds the dialog...
              dialog.setModal(false);
              dialog.pack();
              // Note that the dialog is not visible yet
         public Data[] doSelection() {
              operatorAnswer = NONE_YET;
              dialog.setVisible(true);          
              while (operatorAnswer == NONE_YET) {
                   try {
                        wait();
                   } catch (InterruptedException e) { }
              return (operatorAnswer == OK ? selection : null);
         public void actionPerformed(ActionEvent evt) {
              if (okButton.equals(evt.getSource())) {
                   operatorAnswer = OK;
                   retrieveSelection();
                   dialog.setVisible(false);
              else if (cancelButton.equals(evt.getSource())) {               
                   operatorAnswer = CANCEL;
                   dialog.dispose();
         private void retrieveSelection() {
              // ... Here is the code that retrieves selected data from the dialog's JLists
              // and stores it in the "selection" private array...
              notifyAll();
         }

  • Why doesn't my JDialog content paint?

    Folks,
    I started playing with converting the "little mouse-maze" game in [this thread|http://forums.sun.com/thread.jspa?threadID=5353283] from an applet to a swing app, and I'm stuck.
    The contents of the "Game Over" JDialog doesn't paint (I see dialog border, but the background through content window... and I'm totally clueless as to why or what to do about it... It's pretty obvious that it's a side-effect of the custom painting routine... which I presume must be painting over the top of the dialog content... or maybe the dialog isn't being painted at all because I've blocked the parent's paint-component by showing the dialogue... Hmmm, maybe I need to invoke-it-Later?
    package forums;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MaxWallacesCollision extends JPanel
      private static final long serialVersionUID = 1L;
      private static final int[] leftWallX = {0,204,204,149,149,162,162,243,260,235,259,232,260,230,207,207,0};
      private static final int[] leftWallY = {500,499,402,402,341,324,227,191,157,141,135,123,116,109,86,1,1};
      private static final int[] playAreaX = {204,204,149,149,162,162,243,260,235,259,232,260,230,207,207,263,263,245,282,262,274,257,273,250,184,184,170,170,208,216,216};
      private static final int[] playAreaY = {499,402,402,341,324,227,191,157,141,135,123,116,109,86,1,1,86,103,115,129,138,147,155,201,230,323,340,384,384,402,499};
      private static final int[] rightWallX = {500,500,263,263,245,282,262,274,257,273,250,184,184,170,170,208,216,216};
      private static final int[] rightWallY = {500,0,1,86,103,115,129,138,147,155,201,230,323,340,384,384,402,499};
      private static final int START_X = 208;
      private static final int START_Y = 490;
      private Polygon leftWall = new Polygon(leftWallX, leftWallY, 17);
      private Polygon playerArea = new Polygon(playAreaX, playAreaY, 31);
      private Polygon rightWall = new Polygon(rightWallX, rightWallY, 18);
      private Rectangle rect = new Rectangle(3,3);
      private Rectangle goal = new Rectangle(207,0,55,25);
      private JFrame frame;
      private boolean listening = false;
      private boolean mouseInside = false;
      public MaxWallacesCollision() {
        super( (LayoutManager)null );
        this.addMouseListener(new MouseAdapter() {
          @Override
          public void mouseEntered(MouseEvent e) {
            //System.out.println("DEBUG: mouseEntered");
            mouseInside=true;
          @Override
          public void mouseExited(MouseEvent e) {
            //System.out.println("DEBUG: mouseExited");
            mouseInside=false;
        this.addMouseMotionListener(new MouseMotionListener() {
          @Override
          public void mouseMoved(MouseEvent e) {
            //System.out.println("DEBUG: mouseMoved"+e.getX()+" "+e.getY());
            //move the yellow square according to mouse position
            rect.setLocation(e.getX()-rect.width/2, e.getY()-rect.height/2);
            repaint();
          public void mouseDragged(MouseEvent e) {
        final JButton startButton = new JButton("Start");
        startButton.setBounds(START_X-25, START_Y-14, 50, 25);
        startButton.setMargin(new Insets(1,1,1,1)); // top, left, bottom, right
        startButton.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            listening=true;
            startButton.setVisible(false);
        super.add(startButton);
      public Dimension getPreferredSize() {
        return new Dimension(500,500);
      public void paintComponent(Graphics g2d) {
        super.paintComponent(g2d);
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0,0, (int)getSize().getWidth(), (int)getSize().getHeight() );
        g2d.setColor(Color.BLUE);
        g2d.fillPolygon(playerArea);
        g2d.setColor(Color.GREEN);
        g2d.fillRect(goal.x, goal.y, goal.width, goal.height);
        g2d.setColor(Color.RED);
        g2d.fillPolygon(leftWall);
        g2d.fillPolygon(rightWall);
        g2d.setColor(Color.YELLOW);
        g2d.setFont(new Font("Helvetica",Font.BOLD,16));
        if (mouseInside) {
          g2d.fillRect(rect.x, rect.y, rect.width, rect.height);
        } else {
          g2d.fillRect(START_X, START_Y, rect.width, rect.height);
        g2d.setColor(Color.BLACK);
        if (listening && mouseInside && (leftWall.intersects(rect)||rightWall.intersects(rect)) ) {
          listening = false;
          g2d.drawString("Crashed!", rect.x, rect.y);
          for ( MouseMotionListener l : getMouseMotionListeners() ) {
            removeMouseMotionListener(l);
          JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this), "Collision!", "Game Over", JOptionPane.INFORMATION_MESSAGE);
          System.exit(1);
      public static void main (String[] args) throws Exception {
        SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              JFrame frame = new JFrame("Add Text to List");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(new MaxWallacesCollision());
              frame.pack();
              frame.setVisible(true);
    }Any guidance would be appreciated.
    Thanx all. Keith.

    I tried the invokeLater thingummy... which seems to work... Still, What's going on here? I guess the modal-dialog blocked the EDT, so no part of the app could be repainted? Is that it?
    package forums;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MaxWallacesCollision extends JPanel
      private static final long serialVersionUID = 1L;
      private static final int[] leftWallX = {0,204,204,149,149,162,162,243,260,235,259,232,260,230,207,207,0};
      private static final int[] leftWallY = {500,499,402,402,341,324,227,191,157,141,135,123,116,109,86,1,1};
      private static final int[] playAreaX = {204,204,149,149,162,162,243,260,235,259,232,260,230,207,207,263,263,245,282,262,274,257,273,250,184,184,170,170,208,216,216};
      private static final int[] playAreaY = {499,402,402,341,324,227,191,157,141,135,123,116,109,86,1,1,86,103,115,129,138,147,155,201,230,323,340,384,384,402,499};
      private static final int[] rightWallX = {500,500,263,263,245,282,262,274,257,273,250,184,184,170,170,208,216,216};
      private static final int[] rightWallY = {500,0,1,86,103,115,129,138,147,155,201,230,323,340,384,384,402,499};
      private static final int START_X = 208;
      private static final int START_Y = 490;
      private Polygon leftWall = new Polygon(leftWallX, leftWallY, 17);
      private Polygon playerArea = new Polygon(playAreaX, playAreaY, 31);
      private Polygon rightWall = new Polygon(rightWallX, rightWallY, 18);
      private Rectangle rect = new Rectangle(3,3);
      private Rectangle goal = new Rectangle(207,0,55,25);
      private JFrame frame;
      private boolean listening = false;
      public MaxWallacesCollision() {
        super( (LayoutManager)null );
        this.addMouseListener(new MouseAdapter() {
          @Override
          public void mouseExited(MouseEvent e) {
            listening=false;
        this.addMouseMotionListener(new MouseMotionListener() {
          @Override
          public void mouseMoved(MouseEvent e) {
            //move the yellow square according to mouse position
            rect.setLocation(e.getX()-rect.width/2, e.getY()-rect.height/2);
            repaint();
          public void mouseDragged(MouseEvent e) {
        final JButton startButton = new JButton("Start");
        startButton.setBounds(START_X-25, START_Y-14, 50, 25);
        startButton.setMargin(new Insets(1,1,1,1)); // top, left, bottom, right
        startButton.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            listening=true;
            startButton.setVisible(false);
        super.add(startButton);
      public Dimension getPreferredSize() {
        return new Dimension(500,500);
      public void paintComponent(Graphics g2d) {
        super.paintComponent(g2d);
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0,0, (int)getSize().getWidth(), (int)getSize().getHeight() );
        g2d.setColor(Color.BLUE);
        g2d.fillPolygon(playerArea);
        g2d.setColor(Color.GREEN);
        g2d.fillRect(goal.x, goal.y, goal.width, goal.height);
        g2d.setColor(Color.RED);
        g2d.fillPolygon(leftWall);
        g2d.fillPolygon(rightWall);
        g2d.setColor(Color.YELLOW);
        g2d.setFont(new Font("Helvetica",Font.BOLD,16));
        if (listening) {
          g2d.fillRect(rect.x, rect.y, rect.width, rect.height);
        } else {
          g2d.fillRect(START_X, START_Y, rect.width, rect.height);
        g2d.setColor(Color.BLACK);
        if (listening && (leftWall.intersects(rect)||rightWall.intersects(rect)) ) {
          listening = false;
          g2d.drawString("Crashed!", rect.x, rect.y);
          SwingUtilities.invokeLater(new Runnable() {
            public void run() {
              crash();
      private void crash() {
        for ( MouseMotionListener l : getMouseMotionListeners() ) {
          removeMouseMotionListener(l);
        JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this), "You crashed!", "Game Over", JOptionPane.INFORMATION_MESSAGE);
        System.exit(1);
      public static void main (String[] args) throws Exception {
        SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              JFrame frame = new JFrame("Add Text to List");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(new MaxWallacesCollision());
              frame.pack();
              frame.setVisible(true);
    }The challend is to "move" the mouse-pointer automagically to the start position... sounds hard, coz I bet that ain't "normal"... Maybe Robot can do that?
    Cheers all. Keith.

  • Problem with refreshing JFrames and JDialogs

    My program is based on few JDialogs and one JFrame. I'm still changing them, one time one of the JDialogs is visible, other time JFrame. During this change I call dispose() for one window or frame and I create (if it wasn't created before) other component and call setVisible(true) for it. Problem is that sometimes (only sometimes! like 5% of calls) my windows appears but they are not refreshing (not showing new objects added to their lists or sth like that) until I resize my window by dragging mouse on the edge of it. Is there anyway to ensure that window will be displayed properly?

    I ran into this problem about a year ago...so I don't really remember but I think a call to validate(), or paint() or repaint() or something like that should do the trick (forgive me for not knowing the exact one but as I said it has been a while). Its been about that year since I stopped coding in java and moved to c#. You want the window to redraw its self what ever that is.

  • Bug: IconUIResource doesn't paint an animated ImageIcon

    I was recently playing with Icons and found that javax.swing.plaf.IconUIResource doesn't paint an ImageIcon that contains an animated GIF. Found the reason in these bug fixes.
    [http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4215118]
    [http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4215118]
    From that, I could arrive at a workaround: extend ImageIcon to implement the UIResource marker interface and use this class instead of wrapping an ImageIcon in a IconUIResource. Interestingly, NetBeans autocomplete revealed the existance of sun.swing.ImageIconUIResource which I determined to be a direct subclass of ImageIcon, with two constructors that take an Image and byte[] respectively.
    Test SSCCE: import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import javax.swing.UIManager;
    import javax.swing.plaf.IconUIResource;
    import javax.swing.plaf.UIResource;
    public class IconUIResourceBug {
      public static void main(String[] args) {
        try {
          URL imageURL = new URL("http://www.smiley-faces.org/smiley-faces/smiley-face-rabbit.gif");
          InputStream is = imageURL.openStream();
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          int n;
          byte[] data = new byte[1024];
          while ((n = is.read(data, 0, data.length)) != -1) {
            baos.write(data, 0, n);
          baos.flush();
          byte[] bytes = baos.toByteArray();
          ImageIcon imageIcon = new ImageIcon(bytes);
          Icon icon = new IconUIResource(imageIcon);
          UIManager.put("OptionPane.errorIcon", icon);
          JOptionPane.showMessageDialog(null, "javax.swing.plaf.IconUIResource", "Icon not shown",
                  JOptionPane.ERROR_MESSAGE);
          icon = new ImageIconUIResource(bytes);
          UIManager.put("OptionPane.errorIcon", icon);
          JOptionPane.showMessageDialog(null, "ImageIconUIResource", "Icon shown",
                  JOptionPane.ERROR_MESSAGE);
          icon = new sun.swing.ImageIconUIResource(bytes);
          UIManager.put("OptionPane.errorIcon", icon);
          JOptionPane.showMessageDialog(null, "sun.swing.ImageIconUIResource", "Icon shown",
                  JOptionPane.ERROR_MESSAGE);
        } catch (MalformedURLException ex) {
          ex.printStackTrace();
        } catch (IOException ex) {
          ex.printStackTrace();
    class ImageIconUIResource extends ImageIcon implements UIResource {
      public ImageIconUIResource(byte[] bytes) {
        super(bytes);
    }I can't see any alternative fix for the one carried out in response to the quoted bug reports, so have held off on making a bug report. Any ideas?
    Thanks for reading, Darryl
    I'm also posting this to JavaRanch for wider discussion, and shall post the link here as soon as possible. I'll also keep both threads updated with all significant suggestions received.
    edit [http://www.coderanch.com/t/498351/GUI/java/Bug-IconUIResource-doesn-paint-animated]
    Edited by: DarrylBurke

    Animated gif is working fine for me.
    You can check the delay time between the images in the gif, to see that it's not too short.
    Here's a simple example:import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.imageio.stream.ImageInputStream;
    import javax.swing.ImageIcon;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import com.sun.imageio.plugins.gif.GIFImageMetadata;
    import com.sun.imageio.plugins.gif.GIFImageReader;
    public class AnimatedGifTest {
        public static void main(String[] args) {
            try {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
                URL url = new URL("http://www.gifanimations.com/action/SaveImage?path=/Image/Animations/Cartoons/~TS1176984655857/Bart_Simpson_2.gif");
                frame.add(new JLabel(new ImageIcon(url)));
                frame.pack();
                frame.setVisible(true);
                // Read the delay time for the first frame in the animated gif
                GIFImageReader reader = (GIFImageReader) ImageIO.getImageReadersByFormatName("GIF").next();
                ImageInputStream iis = ImageIO.createImageInputStream(url.openStream());
                reader.setInput(iis);
                GIFImageMetadata md = (GIFImageMetadata) reader.getImageMetadata(0);           
                System.out.println("Time Delay = " + md.delayTime);
                reader.dispose();
                iis.close();
            } catch (Exception e) {e.printStackTrace();}
    }

  • IMAGE NOT DISPLAYED OVER JButton ON JDialog

    Hi,
    I am trying to display an image over a JButton inside a JDialog(pops up on button click from an applet). But it is invisible. But I am sure that it is drawn on the ContentPane since when i click partially/half at the position
    of the JButton I could see the JButton with the image. Actualy I am resizing the JDialog since I have two buttons, one to minimise and the other two maximise the size of the JDailog.
    All the buttons are in place but not visible neither at the first place nor when the JDialog is resized.
    The code is as follows:
    package com.dataworld.gis;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.print.*;
    import javax.swing.*;
    public class PrintThisPolygon extends JDialog {
         protected Image image;
         protected JButton print;
         protected JButton resize;
         protected JButton desize;
         private int pX=0, pY=0, pWidth=0, pHeight=0;
         public PrintThisPolygon(JFrame parent, Viewer viewer) {
              super(parent, "Print Polygon", true);
              this.setModal(false);
              getContentPane().setLayout(null);
              image = this.viewer.getScreenBuffer();
              pane = new Panel();
              print = new JButton("print", new ImageIcon("images/print.gif"));
              print.setBounds(0,5,50,20);
              print.setEnabled(true);
              print.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        print();
              resize = new JButton("+", new ImageIcon("images/print.gif"));
              resize.setBounds(55,5,50, 20);
              resize.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        resizePlus();
              desize = new JButton("-", new ImageIcon("images/print.gif"));
              desize.setBounds(105,5,50, 20);
              desize.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        resizeMinus();
              getContentPane().add(print);
              getContentPane().add(resize);
              getContentPane().add(desize);
    public String getAppletInfo() {
         return "Identify Polygon\n"
    public void paint(Graphics g){
         System.out.println("Paint : pX " + pX + " pY :" + pY);
         g.drawImage(image, pX, pY, pWidth, pHeight, getBackground(), this);
    protected void print() {
         ImagePrint sp = new ImagePrint(this.viewer);
    public void resizeMinus(){
         repaint();
    public void resizePlus(){
         repaint();
    Can anybody has any clue. Can anybody help me out.
    Thanx

    I added resize code for those buttons and ended up with repaint problems too. When you manually resized the window everything was fine again. After a bit of digging around I found you need to call validate on the dialog and then things work.
    IL,
    There is the new scaling version of the code I modified above:package forum.com.dataworld.gis;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class PanelPaintFrame extends JFrame {
         public static void main(String[] args) {
              PanelPaintFrame frame = new PanelPaintFrame ();
              frame.setVisible (true);
         public PanelPaintFrame ()  {
              setBounds (100, 100, 600, 600);
              setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              JButton showPrintDialogButton = new JButton ("Show Print Dialog...");
              JPanel buttonPanel = new JPanel ();
              buttonPanel.add (showPrintDialogButton);
              getContentPane ().add (buttonPanel);
              showPrintDialogButton.addActionListener (new ActionListener ()  {
                   public void actionPerformed (ActionEvent e)  {
                        PrintThisPolygon printDialog = new PrintThisPolygon (PanelPaintFrame.this);
                        printDialog.show();
              pack ();
         public class PrintThisPolygon extends JDialog {
              protected ImageIcon myOrigonalImage = null;
              protected Image image;
              protected JButton print;
              protected JButton resize;
              protected JButton desize;
              private int pX=0, pY=0, pWidth=0, pHeight=0;
              JPanel pane = null;
              public PrintThisPolygon(JFrame parent/*, Viewer viewer*/) {
                   super(parent, "Print Polygon", true);
    //               this.setModal(false);
                   getContentPane().setLayout(null);
                   //  Substitute my own image
                   myOrigonalImage = new ImageIcon (PrintThisPolygon.class.getResource ("images/MyCoolImage.jpg"));
                   //  Start off full size
                   pWidth = myOrigonalImage.getIconWidth();
                   pHeight = myOrigonalImage.getIconHeight();
                   image = myOrigonalImage.getImage ().getScaledInstance(pWidth, pHeight, Image.SCALE_DEFAULT);
    //               image = this.viewer.getScreenBuffer();
    //               pane = new Panel();
                   //  Create a JPanel to draw the image
                   pane = new JPanel(){
                        protected void paintComponent(Graphics g)  {
                             System.out.println("Paint : pX " + pX + " pY :" + pY);
                             g.drawImage(image, pX, pY, pWidth, pHeight, getBackground(), this);
                   pane.setBounds (0, 0, pWidth, pHeight);
                   //  Load the button image using a URL
                   print = new JButton("print", new ImageIcon(PrintThisPolygon.class.getResource ("images/print.gif")));
    //               print = new JButton("print", new ImageIcon("images/print.gif"));
                   print.setBounds(0,5,55,20);
                   print.setEnabled(true);
                   print.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent ae){
                             print();
                   resize = new JButton("+", new ImageIcon("images/print.gif"));
                   resize.setBounds(55,5,50, 20);
                   resize.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent ae){
                             resizePlus();
                   desize = new JButton("-", new ImageIcon("images/print.gif"));
                   desize.setBounds(105,5,50, 20);
                   desize.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent ae){
                             resizeMinus();
                   //  Setup a transparent glass panel with no layout manager
                   JPanel glassPanel = new JPanel ();
                   glassPanel.setLayout (null);
                   glassPanel.setOpaque (false);
                   //  Add the image panel to the dialog
                   getContentPane().add(pane);
                   //  Add the buttons to the glass panel
                   glassPanel.add(print);
                   glassPanel.add(resize);
                   glassPanel.add(desize);
                   //  Set our created panel as the glass panel and turn it on
                   setGlassPane (glassPanel);
                   glassPanel.setVisible (true);
                   setBounds (100, 100, pWidth, pHeight);
    //               setBounds (100, 100, 500, 300);
              public String getAppletInfo() {
                   return "Identify Polygon\n";
    //          public void paint(Graphics g){
    //          protected void paintComponent(Graphics g)  {
    //               System.out.println("Paint : pX " + pX + " pY :" + pY);
    //               g.drawImage(image, pX, pY, pWidth, pHeight, getBackground(), this);
              protected void print() {
                   //  Pretend to print
    //               ImagePrint sp = new ImagePrint(this.viewer);
                   System.out.println ("Print view...");
              public void resizeMinus(){
                   //  Scale the image down 10%
                   int scaledWidth = pWidth - (int)(pWidth * 0.1);
                   int scaledHeight = pHeight - (int)(pHeight * 0.1);
                   scaleImage (scaledWidth, scaledHeight);
              public void resizePlus(){
                   //  Scale the image up 10%
                   int scaledWidth = pWidth + (int)(pWidth * 0.1);
                   int scaledHeight = pHeight + (int)(pHeight * 0.1);
                   scaleImage (scaledWidth, scaledHeight);
              private void scaleImage (int scaledWidth, int scaledHeight)  {
                   //  Create a new icon for drawing and retrieve its actuall size
                   image = myOrigonalImage.getImage ().getScaledInstance (scaledWidth, scaledHeight, Image.SCALE_DEFAULT);
                   pWidth = scaledWidth;
                   pHeight = scaledHeight;
                   //  Resize
                   setSize (pWidth, pHeight);
                   pane.setSize (pWidth, pHeight);
                   validate();
    }

  • JDialog not displaying correctly

    Hi all,
    Im having this problem with displaying a JDialog. I have a lengthy delay in my app and want to display an animated GIF while the user is waiting. The below code is what im trying to run. The JDialog wil display, but the title text, message text and the ImageIcon are not displayed on the JDialog. Anyone know what is wrong? Do i have to wait on the Image to load before i .show the dialog? But that wouldn't explain why the text doesn't show. Any help appreciated
    Code im trying to run, RemoteAdminMain.java
        WaitingDialog dialog = new WaitingDialog(this, "Connection...", false, "Creating Connection");
        try {
          //Create the connection...
          dialog.show();
          RemoteAdminMain.nc = NetConnection.createNetConnection(nodeAddress, Global.sessionUsername, Global.sessionPassword);
          dialog.dispose();
        } catch (Exception e) {
          dialog.dispose();
          JOptionPane.showMessageDialog(null, "Error", "Error", JOptionPane.ERROR_MESSAGE);
          e.printStackTrace();
          return;
    The Dialog code: WaitingDialog.java
    public class WaitingDialog extends JDialog {
      private JPanel panel1 = new JPanel();
      private BorderLayout borderLayout1 = new BorderLayout();
      private JLabel jLabel1 = new JLabel();
      private JLabel jLabel2 = new JLabel();
      public WaitingDialog(Frame frame, String title, boolean modal, String message) {
        super(frame, title, modal);
        try {
          jLabel2.setText(message);
          jbInit();
          pack();
        catch(Exception ex) {
          ex.printStackTrace();
        //Center the window
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension dialogSize = getSize();
        if (dialogSize.height > screenSize.height) {
          dialogSize.height = screenSize.height;
        if (dialogSize.width > screenSize.width) {
          dialogSize.width = screenSize.width;
        setLocation((screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2);
      public WaitingDialog() {
        this(null, "", false, "");
      void jbInit() throws Exception {
        panel1.setLayout(borderLayout1);
        jLabel2.setToolTipText("");
        jLabel2.setHorizontalAlignment(SwingConstants.CENTER);
        jLabel2.setHorizontalTextPosition(SwingConstants.CENTER);
        jLabel2.setText("message");
        jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
        jLabel1.setHorizontalTextPosition(SwingConstants.CENTER);
        ImageIcon icon = new ImageIcon(com.tempo.netservice.RemoteAdminMain.class.getResource("swing.gif"));
        icon.setImageObserver(jLabel1);
        jLabel1.setIcon(icon);
        this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        this.setResizable(false);
        this.setTitle("");
        getContentPane().add(panel1);
        panel1.add(jLabel1, BorderLayout.CENTER);
        panel1.add(jLabel2,  BorderLayout.SOUTH);
    }

    I fear the problem isn't with the JDialog itself, everything is from from that point of view. I forgot to mention that if you set it as Modal, it will display fine (however, the modal method is blocking, meaning the createNetConnection method will not be executed until the dialog is closed, entirly defeating the purpose.
    I believe the problem is that the createNetConnection function stops the rest of the JDialog from loading. So i guess my question to begin with is, is there anyway to completly display and paint the JDialog before allowing it to continue onto the next function?

  • How to set the size of a class that extends JDialog

    Hi,
    I was trying to set the size of my dialog window to be 600 by 600, but couldn't change it. Here is my code:
    public class alii extends JDialog {
    /** Creates new form alii */
    public alii(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    private void initComponents() {
    Container contentPane = getContentPane();
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    closeDialog(evt);
    pack();
    public static void main(String args[]) {
    JFrame frame = new JFrame();
    alii a = new alii(new javax.swing.JFrame(), true);
    frame.setSize(600,500);
    frame.setLocation(200,200);
    frame.setVisible(true);}}
    Please help me with this and explain to me what is the problem and what needs to be changed.
    Cheers

    Hi,
    The code you sent me doesn't work, and the code I posted wasn't a complete, but there is the complete one. You can see now what the code does.
    * alii.java
    * Created on 15 November 2003, 13:31
    * @author Ali
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.util.*;
    import java.io.*;
    import java.applet.*;
    import java.net.*;
    public class sun extends JDialog {
    int x[] = new int[4];
    int y[] = new int[4];
    int w[] = new int[4];
    int h[] = new int[4];
    int Y_ax = 310;
    double DrawGraf[][] = new double[4][4];
    String line[] = new String[9];
    double Perc[] = new double[4];
    double Sum=0;
    GUICanvas can;
    double graphvalue[] = new double [5];
    /** Creates new form alii */
    public sun(Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    //setVisible(true);
    //setSize(600,500);
    //setLocation(200,200);
    /** 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() {
    //Container contentPane = getContentPane();
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    closeDialog(evt);
    //contentPane.setSize(700,700);
    //pack();
    public void drawthegraph(String s)
    /* try {
    URL url = new URL(
    "http://localhost:111/test/servlet/Compare?value="+s);
    BufferedReader in = new BufferedReader(
    new InputStreamReader(url.openStream()));
    for (int c = 0; c<9; c++)
    line[c] = in.readLine();
    in.close();
    }catch (Exception e){
    e.printStackTrace();
    graphvalue[0] = 200;
    graphvalue[1] = 200;
    graphvalue[2] = 100;
    graphvalue[3] = 300;
    graphvalue[4] = 20;
    //graphvalue[4] = can.d2i(graphvalue[4]);
    //System.out.println(line[8]);
    Sum = graphvalue[0]+graphvalue[1]+graphvalue[2]+graphvalue[3];
    Perc[0] = graphvalue[0]/Sum*200;
    Perc[1] = graphvalue[1]/Sum*200;
    Perc[2] = graphvalue[2]/Sum*200;
    Perc[3] = graphvalue[3]/Sum*200;
    System.out.println(Perc[0]);
    DrawGraf[0][0] = 130;
    DrawGraf[0][1] = Y_ax - Perc[0];
    DrawGraf[0][2] = 60;
    DrawGraf[0][3] = Perc[0];
    DrawGraf[1][0] = DrawGraf[0][0]+60;
    DrawGraf[1][1] = Y_ax - Perc[1];
    DrawGraf[1][2] = 60;
    DrawGraf[1][3] = Perc[1];
    DrawGraf[2][0] = DrawGraf[1][0]+60;
    DrawGraf[2][1] = Y_ax - Perc[2];
    DrawGraf[2][2] = 60;
    DrawGraf[2][3] = Perc[2];
    DrawGraf[3][0] = DrawGraf[2][0]+60;
    DrawGraf[3][1] = 310 - Perc[3];
    DrawGraf[3][2] = 60;
    DrawGraf[3][3] = Perc[3];
    for(int d=0;d<4;d++)
    x[d]=d2i(DrawGraf[d][0]);
    y[d]=d2i(DrawGraf[d][1]);
    w[d]=d2i(DrawGraf[d][2]);
    h[d]=d2i(DrawGraf[d][3]);
    repaint();
    static int d2i(double d) {return (int) Math.round(d);}
    public void paint (Graphics g)
    g.setColor(Color.red);
    for(int d=0;d<4;d++)
    g.fill3DRect(x[d],y[d],w[d],h[d],true);
    g.setColor(Color.blue);
    g.drawLine(130,130,130,310);
    g.drawLine(130,310,370,310);
    g.setColor(Color.black);
    g.drawString("WELCOME TO Ali",150,100);
    g.drawString("Region: Lambeth",430,150);
    g.drawString("Manger: ",430,170);
    g.drawString("Location: ",430,190);
    g.drawString("Number of Staff: "+graphvalue[4],430,210);
    g.drawString("Week1",135,345);
    g.drawString("Week2",195,345);
    g.drawString("Week3",255,345);
    g.drawString("Week4",315,345);
    g.drawString(" "+"20 -",100,295);
    g.drawString(" "+"40 -",100,255);
    g.drawString(" "+"60 -",100,215);
    g.drawString(" "+"80 -",100,175);
    g.drawString("100 -",100,135);
    g.setColor(Color.yellow);
    g.drawLine(130,290,370,290);
    g.drawLine(130,250,370,250);
    g.drawLine(130,210,370,210);
    g.drawLine(130,170,370,170);
    g.drawLine(130,130,370,130);
    /** Closes the dialog */
    private void closeDialog(java.awt.event.WindowEvent evt) {
    setVisible(false);
    dispose();
    * @param args the command line arguments
    public static void main(String args[]) {
    JFrame frame = new JFrame();
    sun sn = new sun(frame, true);
    frame.setSize(600,500);
    frame.getContentPane().add(sn);
    frame.setLocation(200,200);
    frame.setVisible(true);
    You were right that I am know to this, but getting there slowly and thanks for your help.
    Cheers

  • Adding image to JDialog in Applet

    Well.. I've decided to make my Applet load via a JDialog. Which I know is possible :). And to a start I'll make a very simple Applet in the JDialog, including a background picture, which I just can't add! So to make a long story short, I want an image in my JDialog, but my code gives me a nullPointerException during the Runtime.. Here's the exact Runtime error:
    Exception in thread "main" java.lang.NullPointerException
            at applet.<init>(applet.java:16)
            at applet.main(applet.java:100)And here's my exact applet.java file:
    import java.applet.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.imageio.*;
    import javax.swing.plaf.metal.*;
    public class applet extends Applet implements Runnable
        private ImagePanel panel;   
    public applet()
         panel.createGUI();
        public void init()
        public void run()
    public void start()
         Thread thread = new Thread(this);
         thread.start();
    public void stop()
    public void destroy()
    public void paint(Graphics g)
    private class ImagePanel extends JPanel
        BufferedImage buffered = null;
        public ImagePanel(String name)
            try
                buffered = ImageIO.read(new File(name));
                setPreferredSize(new Dimension(buffered.getWidth(), buffered.getHeight()));
            } catch(IOException ioe)
                ioe.printStackTrace();
        public void paintComponent(Graphics g)
            if (buffered == null)
                g.drawString("No Image", 10, 40);
            else
                g.drawImage(buffered, 0, 0, null);
        public void createGUI()
         MetalLookAndFeel.setCurrentTheme(new BlackTheme());
            JFrame.setDefaultLookAndFeelDecorated(true);
            JDialog.setDefaultLookAndFeelDecorated(true);
            JPopupMenu.setDefaultLightWeightPopupEnabled(false);
         JDialog dialog = new JDialog();
      dialog.setTitle("Applet loading via. JDialog");
      Container container = dialog.getContentPane();
      ImagePanel panel = new ImagePanel("background.gif");
      dialog.pack();
      dialog.setSize(1000, 1000);
      dialog.setVisible(true);
      dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        public static void main(String[] args)
         applet app = new applet();
    }And I don't see any errors, but still.. Runtime error.. -.-' So a little bit of help would really be appretaiced!

    Okay I guess I spoke to soon.. :O Now I have no Runtime error but my JDialog is completly empty.. And my BlackTheme stopped working.. Not It's a blue theme instead..
    Here take a look at my applet.java:
    import java.applet.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.imageio.*;
    import javax.swing.plaf.metal.*;
    public class applet extends Applet implements Runnable
        ImagePanel panel = new ImagePanel("background.gif");  
    public applet()
         panel.createGUI();
        public void init()
        public void run()
    public void start()
         Thread thread = new Thread(this);
         thread.start();
    public void stop()
    public void destroy()
    public void paint(Graphics g)
    private class ImagePanel extends JPanel
        BufferedImage buffered = null;
        public ImagePanel(String s)
            try
                buffered = ImageIO.read(new File(s));
                setPreferredSize(new Dimension(buffered.getWidth(), buffered.getHeight()));
            } catch(IOException ioe)
                ioe.printStackTrace();
        public void paintComponent(Graphics g)
            if(buffered == null)
                System.out.println("No image to display.");
            else
                g.drawImage(buffered, 0, 0, null);
        public void createGUI()
            MetalLookAndFeel.setCurrentTheme(new BlackTheme());
            JFrame.setDefaultLookAndFeelDecorated(true);
            JDialog.setDefaultLookAndFeelDecorated(true);
            JPopupMenu.setDefaultLightWeightPopupEnabled(false);
         JDialog dialog = new JDialog();
      dialog.setTitle("Applet loading via. JDialog");
      Container container = dialog.getContentPane();
      ImagePanel panel = new ImagePanel("background.gif");
      dialog.pack();
      dialog.setSize(1000, 1000);
      dialog.setVisible(true);
      dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        public static void main(String[] args)
         applet app = new applet();
    }

  • JDialog Non Modal....Default button remains

    I've created a non modal JDialog
    By doing the following
    1. Creating an object of JOptionPane(message, JOptionPane.ERROR_MESSAGE)
    2. Adding the JOptionPane object to the ContentPane
    3. Creating a button
    4. Adding button("End Application") to ContentPane
    5. Adding listeners to window and button
    The result is a dialog
    Message
    ICON "OK" Button...............................NOT REQUIRED
    "End Application" Button
    I don't require the "OK" Button. Is there a way of removing this button. I need the dialog box to be modal so can't use showMessageDialog, rename "Ok" button to "End Application" etc.
    Should I be taking a different approach ie Not adding JOptionPane to JDialog??
    If the above isn't possible. Do you know where I can find the default error gif on error dialog boxes?
    Kind regards,
    Jean

    Get the error icon with UIMananger.getIcon("OptionPane.errorIcon"). It might throw exceptions while painting because it's expecting to be painting in a JOptionPane. Just catch and ignore the exceptions and it will paint alright.

  • Resize jdialog without flicker effect

    I made a vertical tool palette with a JDialog : I have "setcontentpane" a JPanel with vertical boxlayout.
    This JPanel contains other JPanels (class PaletteZone extends JPanel) that act like tool zones : they can be collapse or expand. If you want to have look of what i'm talking about, there is an image here of the palette :
    http://db-maths.nuxit.net/im1.png
    Here is my problem... I have a PaletteZone method used to collapse the tool zone :
    public void collapse(){
            ContentVisible=false;
            ZoneTitle.title.setIcon(rightTriangle);
    // component 0 is the zone title bar, component 1 an icon set (within a JPanel) :
            this.remove(1);
            JP.validate();
    }******* 1) When I use JP.validate, there is no flickering at all and the zone collapse nicely. BUT the JDialog isn't set to the good size. If you want to have a look on what you get when you clic on "Construction" :
    http://db-maths.nuxit.net/im2.png
    ******* 2) If I use JP.pack(), of course the dialog is correctly resized and redrawn. BUT there is a flickering effect : I've made some tries on JFrames and JDialogs and I saw that a pack() call clear immediatly the background and then send a paint call : this "clear/paint" sequence makes a bad flickering effect. I have a quite recent computer (G5 and OS X), and I use java 1.4.2 so I don't think the fact that I see this flicker is caused by hardware or software...
    ******* 3) If I use JP.setSize(), things behave exactly like if I do a pack() call...
    Do you know what I could do to avoid this flicker ? to set the size to the JDialog without this "clear/paint" sequence ?

    you will have to create a jpanel and place this in the dialog's NORTH.
    add a mouseListener to the panel and provide your own moving-handling.
    this.setLocation((int) (this.getX() + e.getX() - m_iOffset.getX()) ...
    this.repaint();you'll have to set m_iOffset wehen mousePressend, and call the moving method when mouseDragged.

  • How do JComboBoxes paint outside their bounds?

    I'm making a little widget That is essentially a text field, but as the user starts typing in it it does a query to a jdbc table and lists posible completions in a drop down box. Rather like a combobox really, except I tried doing this as an extension of the JComboBox class, but then the combobox feel interfered with the feel I wanted for this widget. (Focus issues, issues with the ComboBoxEditor and how it handles values as items.)
    I started with an implementation where I kept the list of completions in an undecorated JDialog that positioned itself nicely under the text field whenever it was shown, however there were problems when moving the window the field was in, and if the size of the list changed, and much trouble in general.
    I've now got an implementation where I've made a custom LayoutManager to position the list correctly, and it works perfectly except that the list isn't "floating". That is, I must add it to the widget component and when I want to draw it I must make sure the widget's bounds are large enough to hold the list. This doesn't really work since this leaves a large blank area under the text field when the list is hidden.
    So what I really want to know is: How do JComboBoxes do their popups? How do they keep the bounds of the actual component small, and yet allow the popup to paint over other components? I tried overriding the paintComponent() method and changing the Graphics object's clipRect before painting the popup, still didn't work.
    First a screenshot of what it looks like if I inflate the preferredSize of the widget in the layout manager: (Sorry about norwegian text on labels)
    http://img238.imageshack.us/my.php?image=indexbrowserwidget5gw.jpg
    You can see that the drop down list gets cut off where the bounds of the widget ends.
    Here's the code for what I've got now:
    (I just noticed while previewing that this ended up VERY long. Sorry about that. The interesting bit is the actual LayoutManager.)
    package no.fldt.sdb.swing;
    import java.awt.*;
    import java.awt.event.*;
    import java.math.BigDecimal;
    import java.sql.*;
    import java.util.*;
    import java.util.Timer;
    import javax.swing.*;
    import javax.swing.event.*;
    import no.fldt.sdb.sql.SVDatabaseManager;
    @SuppressWarnings("serial")
    public class SVIndexBrowserOriginal extends JPanel {
         private int numDesc;
         private final String stringSQL;
         private final String pkSQL;
         private PreparedStatement selectStringStatement;
         private PreparedStatement selectPKStatement;
         private SearchableCache cache = new SearchableCache();
         private Value value;
         private JTextField field = new JTextField();
         private FieldKeyListener keyListener = new FieldKeyListener();
         private JButton browseButton = new JButton();
         private JList popupList = new JList();
         private JScrollPane popupPane = new JScrollPane(popupList);
         public SVIndexBrowserOriginal(String tableName, String pkName, String ... descriptionNames) {
              super.setLayout(new BrowserLayout(field,browseButton,popupPane));
              super.add(field);
              super.add(browseButton);
              super.add(popupPane);
              popupPane.setVisible(false);
              field.addFocusListener(new FocusAdapter(){
                   public void focusLost(FocusEvent e) {
                        if(e.getOppositeComponent() == popupList) return; //OK to yield to this
                        if(popupPane.isVisible()) hideHintPopup();
              browseButton.setFocusable(false);
              browseButton.setMargin(new Insets(0,1,0,0));
              browseButton.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e) {
                        keyListener.cancel();
                        if(populateHintList() == -1)
                             hideHintPopup();
                        else
                             displayHintPopup();
              field.addKeyListener(keyListener);
              field.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e) {
                        if(popupPane.isVisible()){
                             doPopupSelection();
              popupList.addKeyListener(new KeyAdapter(){
                   boolean loopedThrough = false;
                   public void keyPressed(KeyEvent e) {
                        switch(e.getKeyCode()){
                             case KeyEvent.VK_ESCAPE:
                                  cancelPopupSelection();
                                  break;
                             case KeyEvent.VK_ENTER:
                             case KeyEvent.VK_TAB:
                                  doPopupSelection();
                                  break;
              this.stringSQL = generateStringSQL(tableName, pkName, descriptionNames);
              this.pkSQL = generatePKSQL(tableName, pkName, descriptionNames);
              this.numDesc = descriptionNames.length;
              try {
                   this.selectStringStatement = SVDatabaseManager.prepareStatement(stringSQL);
                   this.selectPKStatement = SVDatabaseManager.prepareStatement(pkSQL);
                   reBuildStringCache();
              } catch (SQLException ex) {
                   // ex.printStackTrace();
         // The hint popup:
         private Vector<Value> displayList = new Vector<Value>();
         private int populateHintList() {
              popupList.setForeground(Color.BLACK);
              String start = field.getText();
              int sStart = field.getSelectionStart();
              start = start.substring(0,sStart);
              displayList.clear();
              if(start.length() > 0){
                   try {
                        Long.parseLong(start);
                        displayList.addAll(getPossibleMatchesForPK(start));
                   } catch (Exception ex) {
                        displayList.addAll(cache.getPossibleMatchesForDesc(start));
              if(displayList.size() == 1){
                   setValue(displayList.get(0));
                   return 1;
              if(displayList.isEmpty() && start.length() > 0){
                   displayList.add(NO_VALUE);
                   popupList.setForeground(Color.GRAY);
              popupList.setModel(new DefaultComboBoxModel(displayList));
              popupList.setSelectedIndex(0);
              if(displayList.size() > 0){
                   Value v = displayList.get(0);
                   if(!v.isNoValue()){
                        int cp = start.length();
                        field.setText(v.desc);
                        field.setCaretPosition(v.desc.length());
                        //To select the text that is suggested so if the user continues typing it will be overwritten.
                        field.moveCaretPosition(cp);
              int retVal = displayList.size() == 1 ? 0 :
                   displayList.size() == 0 ? -1 : displayList.size();
              return retVal;
         public void displayHintPopup() {
              if(popupPane.isVisible()) return;
              popupPane.setVisible(true);
              field.requestFocus();
         public void hideHintPopup(){
              popupPane.setVisible(false);
         public void doPopupSelection() {
              Value nv = null;
              int i = popupList.getSelectedIndex();
              if(i != -1)
                   nv = displayList.get(i);
              if(nv != null && ! nv.isNoValue()){
                   setValue(nv);
              hideHintPopup();
              field.requestFocusInWindow();
         public void cancelPopupSelection(){
              hideHintPopup();
              field.requestFocusInWindow();
         // The layout
         private class BrowserLayout implements LayoutManager {
              private JTextField field;
              private JButton button;
              private JScrollPane listPane;
              BrowserLayout(JTextField field, JButton button, JScrollPane listPane){
                   this.field = field;
                   this.button = button;
                   this.listPane = listPane;
              public void addLayoutComponent(String name, Component comp) {
              public void removeLayoutComponent(Component comp) {
              public Dimension preferredLayoutSize(Container parent) {
                   return new Dimension(
                             button.getPreferredSize().width+field.getPreferredSize().width,
                             field.getPreferredSize().height
              public Dimension minimumLayoutSize(Container parent) {
                   return new Dimension(
                             button.getMinimumSize().width+field.getMinimumSize().width,
                             field.getMinimumSize().height
              public void layoutContainer(Container parent) {
                   Dimension size = parent.getSize();
                   Rectangle bounds = new Rectangle();
                   bounds.setSize(button.getPreferredSize().width,size.height);
                   bounds.setLocation(size.width,0);
                   bounds.translate((-1 * bounds.width),0);
                   button.setBounds(bounds);
                   bounds.width = size.width - bounds.width;
                   bounds.setLocation(0,0);
                   field.setBounds(bounds);
                   bounds.translate(0,bounds.height);
                   bounds.width = size.width-1;
                   bounds.height = listPane.getPreferredSize().height;
                   listPane.setBounds(bounds);
         // SQL stuff:
         private void reBuildStringCache() throws SQLException {
              //Not so important for the forum
         private Vector<Value> getPossibleMatchesForPK(String start)
                   throws SQLException {
              //Not so important for the forum
         private String generateStringSQL(String tableName, String pkName,
                   String[] descriptionNames) {
              //Not so important for the forum
         private String generatePKSQL(String tableName, String pkName,
                   String[] descriptionNames) {
              //Not so important for the forum
         // Keylistener:
         private class FieldKeyListener extends KeyAdapter {
              private TimerTask popupTask = null;
              private Timer popupTimer = new Timer();
              public void cancel() {
                   if (popupTask != null) {
                        popupTask.cancel();
                        popupTask = null;
              public void keyTyped(KeyEvent e) {
                   cancel();
                   if(e.getKeyChar() == 27) return; //VK_ESCAPE
                   popupTask = new TimerTask() {
                        public void run() {
                             if(Math.abs(populateHintList()) == 1){
                                  hideHintPopup();
                                  return;
                             displayHintPopup();
                   popupTimer.schedule(popupTask, 1000);
              public void keyPressed(KeyEvent e) {
                   if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                        cancel();
                        if(Math.abs(populateHintList()) == 1){
                             hideHintPopup();
                             return;
                        displayHintPopup();
                        popupList.requestFocus();
                   }else if(e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                        cancel();
                        hideHintPopup();
         // Cache:
         private class SearchableCache {
              public void put(String key, BigDecimal value) {
                   //Not too important for the forum
              public BigDecimal get(String key) {
                   //Not too important for the forum
              public Vector<Value> getPossibleMatchesForDesc(String start) {
                   //Not too important for the forum
         public static final Value NO_VALUE = new Value(){{desc = "<No matches>"; pk = null;}};
         public static class Value {
              public BigDecimal pk = null;
              public String desc;
              public String toString(){
                   return desc;
              public boolean equals(Object other){
                   if (other != null && other instanceof Value) {
                        return this.pk.equals(((Value)other).pk);
                   return false;
              public boolean isNoValue(){
                   return this.pk == null;
         public void clearValue(){
              this.value = null;
              this.field.setText("");
         public Value getValue() {
              return this.value;
         public void setValue(Value value) {
              this.value = value;
              field.setText(value.desc);
         @Override
         public void setBackground(Color bg) {
              if(field != null)
                   field.setBackground(bg);
    }Any help with getting the popup to paint correctly or any hints towards a different approach woule be greatly appreciated.

    I can think of three possible choices for a solution:
    1) Use JWindow. But that is very like your first try with an undecorated JDialog.
    I would assume that you will get similar problems as you describe
    2) Use the PopupFactory (in javax.swing). With this you get real popups.
    When the bounds of the popup fits in the parent window it will show as
    a medium-weight component (AWT-component!). When the bounds
    doesn't fit it will show as a heavy-weight component (own window).
    3) Another possibility is JPopupMenu! You can add any Swing-Component
    in a JPopupMenu! :-)
    And the answer for your initial question: how is it done in JComboBox: if you have a look in javax.swing.plaf.basic.BasicComboBoxUI and the BasicComboPopup-class you will see, that it is 3) -> the JPopupMenu that is used here!

Maybe you are looking for

  • Installing the Java Add-In for an existing abap system

    Hi, Currently we are Installing the Java Add-In for an existing abap system. Following the steps (Installation guide): 1) We sucessfully installed the Central Services Instance (SCS) 2) We sucessfully Installed the Database Instamce Java Add-In Our p

  • DestroyJavaVM does not completely shut the VM

    Hi All, I'm using JDK 1.4.2. The platforms used are WindowsXP and MacOSX. In my Native Application after setting up the JVM using JNI_CreateJavaVM, i use the same to load some jar files using URLClassLoader. After all is done i need to shut the VM an

  • Workspace error!

    Sometime my workspace environment got freezed when i try to close the opened PDF form without completing it (without pressing submit button). See the attached screenshot. Is this related to flash player? scriting inside PDF or something else? Thanks,

  • Dual g5 Strange behaviour: since 10.4.4 fans come on then it sleeps!

    a couple of times over past 24hrs the fans have started up along with red glow from lights just behind grill on front of box, Activity Monitor doesn't show much going on..... next minute, right in the middle of working on stuff, the comp goes to slee

  • Encoding DV to ProRes 422 while capture from camera

    Is It possible to capture a DV tape encoding with ProRess 444?