JDialog position

Hello,
I wonder how the position of a JDialog is decided.
In the following code it is positioned below the parent frame. But when using the commented line with setLocationRelativeTo(DialogTest.this), the dialog is nicely placed in the parent's center.
Quite often I had also dialogs with the top left corner centered in the parent. Is there any rule as for what happens when?
Greetings
Jörg
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DialogTest extends JFrame {
  DialogTest dt;
  public DialogTest() {
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setSize(300,300);
    setLocation(300,100);
    Container cp= getContentPane();
    JButton b= new JButton("Show dialog");
    b.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
     JDialog dlg= new JDialog(DialogTest.this);
//     JDialog dlg= new JDialog(dt);
     dlg.setSize(200,100);
     dlg.setModal(true);
//     dlg.setLocationRelativeTo(DialogTest.this);
     dlg.setLocationRelativeTo(dt);
     dlg.setResizable(false);
     dlg.setTitle("The dialogue");
     dlg.setVisible(true);
    cp.add(b, BorderLayout.SOUTH);
    setVisible(true);
  public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
     DialogTest dt= new DialogTest();
//     new DialogTest();
}

dlg.setLocationRelativeTo(dt);well dt is "null" so you are really saying
dlg.setLocationRelativeTo(null);which means center the dialog in the center of the screen.
Quite often I had also dialogs with the top left corner centered in the parentThe location of the dialog is determined at the time the method is invoked, not at the time the dialog is made visible. So this would happen if the size of the frame is (0, 0) when the method is invoked.
However, this may be in older versions of Java. It does not appear to happen in JDK6 on XP:
import javax.swing.*;
public class DialogTest5
  public static void main(String args[])
       JFrame frame1 = new JFrame();
     frame1.setVisible(true);
     JDialog dialog1 = new JDialog(frame1, false);
     dialog1.setLocationRelativeTo(frame1);
//     frame1.setSize(200, 200); // has no effect on dialog location
     dialog1.setVisible(true);
       JFrame frame2 = new JFrame();
       frame2.setBounds(500, 500, 200, 200);
       frame2.setVisible(true);
     JDialog dialog2 = new JDialog(frame2, false);
//     dialog2.setSize(150, 100); // uncomment to see how this affects placement
     dialog2.setLocationRelativeTo(frame2);
     dialog2.setVisible(true);
}

Similar Messages

  • How to make a JDialog scrolling from one position to the other.

    Hi all,
    I want to move a JDialog from one position to the other(actually I want to scrolling/moving as messenger notification appear on top of the system tray) on the desktop.
    Anyone of you can give me a clue.
    Thanks

    Ok here what I have try up to now. First make the initial position of the JFrame as follows.
        private void SetWindowLocation()
            final int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
            final int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
            final int frameHeight = this.getHeight();
            final int frameWidth = this.getWidth();
            int _y = (screenHeight - frameHeight - 32);
            int _x = (screenWidth - frameWidth);
    // Initial location
            this.setLocation(_x, _y); 
    }This code place my Frame in the lower-right corner on top of the system-tray.
    Then as you guys says, try to work on a Timer. Now I'm stuck with the action listener. I try to move the frame to upper-right corner.
        private void SetWindowLocation()
            final int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
            final int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
            final int frameHeight = this.getHeight();
            final int frameWidth = this.getWidth();
            int _y = (screenHeight - frameHeight - 32);
            int _x = (screenWidth - frameWidth);
    // Initial location
            this.setLocation(_x, _y); 
            _timer = new javax.swing.Timer(100, incrementYPosition);
    ActionListener incrementYPosition = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                       while(_y > 0){
                            // do the processing here.
                            // reduce the _y value and set the new location with _x
                    };I'm stuck with that how to involve with the ActionListener here. :(:( After set the initial location how to deal with the ActionListener.
    Any help.

  • Positioning a JDialog

    Hello, I have created a custom dialog box extending JDialog, but it doesn't display where the application frame area is, but at the upper left corner. How could I specify the position of the JDialog relative to the parent frame?

    dialog.setLocation(x + parent.getLocation().x, y + parent.getLocation().y);
    Or you could center the dialog relative to the parent using:
    dialog.setLocationRelativeTo( parent );

  • 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();
    }

  • Positioning of objects

    i have a JDialog and want to position the components so that they pass exactly . for example i have a JLabel but only part of it seen ,
    should i give the size of any component maually
    the other problem is that the user should be able to enter data in JTextfield but only figures , how can i forbid entering of figures
    thanks in advance

    Do you know how can i set the size of the objects
    .setSize(new Dimension(x, y))and look at
    .setMinimumSize()
    .setMaximumSize()
    how can i set the JDialog unresizable ?Look at http://java.sun.com/j2se/1.4.1/docs/api/java/awt/Dialog.html#setResizable(boolean)

  • Drag and drop an image over a JPanel (only change position on same JPanel)

    Hi all,
    there is JPanel added to a JDialog.
    There is a BufferedImage on the JPanel: I need to let the image be dragged and dropped in another position over the same JPanel and read the new position's coordinates.
    (Maybe the image has to be wrapped in a JComponent?)
    Thanks in advance for any suggestions.
    Ludovico

    (Maybe the image has to be wrapped in a JComponent?)Just add the image to a JLabel and add the label to the panel.

  • JTree in JDialog .... addTreeSelectionListener doesn't work ????

    Hi friends,
    jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
    public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
    jTree1ValueChanged(evt);
    i was trying to display the node position when user selects a node in the JTree.
    but i'm able to do it in JFrame but i'm in need to do it in a JDialog. Please do help me.
    public class Dialog extends JDialog implements TreeSelectionListener
    jTree1 = new JTree(xTn);
    jScrollPane1.setViewportView(jTree1);
    private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt) {
    System.out.println("1");
    private void initComponents()
    jScrollPane1 = new javax.swing.JScrollPane();
    jTree1 = new javax.swing.JTree();
    jLabel1 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jTabbedPane1 = new javax.swing.JTabbedPane();
    jPanel1 = new javax.swing.JPanel();
    jScrollPane2 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jPanel2 = new javax.swing.JPanel();
    jScrollPane3 = new javax.swing.JScrollPane();
    jEditorPane1 = new javax.swing.JEditorPane();
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
    public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
    jTree1ValueChanged(evt);
    }// </editor-fold>
    public void valueChanged(TreeSelectionEvent e) {
    System.out.println("2");
    I want to print either "1" or "2"....
    Thanks for the help :-)

    Anandababu_Babu wrote:
    Thanks for the feedback thompson , here is my SSCCE, hope this will help me in better result.You learn quickly. That bodes well. Try this code, note the comments.
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JTree;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class Test_Dialog extends JDialog implements TreeSelectionListener
        public Test_Dialog(JFrame frame, boolean modal)
            super(frame, modal);
            jScrollPane1 = new javax.swing.JScrollPane();
            // effectively, the code is instatiating TWO JTrees
            //jTree1 = new javax.swing.JTree();
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            getContentPane().setLayout(new java.awt.FlowLayout());
            jScrollPane1.setAutoscrolls(true);
            getContentPane().add(jScrollPane1);
            pack();
            // here is no point calling this twice
            // pack();
            // if a GUI can be shown to break at 800x600, why make it so HUGE?
            //this.setBounds(0, 0, 1025, 735);
            setBounds(0, 0, 800, 600);
            this.setResizable(false);
            DefaultMutableTreeNode xTn = new DefaultMutableTreeNode("Sample");
            for(int i=0; i< 10;i++)
                xTn.add(new DefaultMutableTreeNode("Click "+i));
            jTree1 = new JTree(xTn);
            jScrollPane1.setViewportView(jTree1);
            // this will output "Method 1"
            jTree1.addTreeSelectionListener(this);
            // this will output "Method 2"
            jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
                public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                    jTree1ValueChanged(evt);
            jScrollPane1.setViewportView(jTree1);
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTree jTree1;
        private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt) {
            System.out.println("Method 1");
        public void valueChanged(TreeSelectionEvent e) {
           System.out.println("Method 2");
        public static void main(String aregsadf[])
            // these changes ensure the user is able to end the
            // JVM easily when running from the command line
            JFrame frame = new JFrame();
            frame.setSize(400,300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
            // end 'easy end' changes
            new Test_Dialog(frame, true).setVisible(true);
    }

  • Clicking mouse after closing JDialog sends event to last component (1.1.8)

    There seems to be a bug in Java 1.1.8 that I'm looking for a workaround.
    I have a JButton on a JFrame that brings up a modal JDialog when you click it. After closing the dialog, if you click on the JFrame without moving the mouse, it will click the button on the frame that was last clicked, even if the mouse is not over the button.
    Steps to reproduce:
    1. Use the mouse to click on the button on the frame to bring up the dialog.
    2. Close the dialog with the mouse or keyboard and don't move the mouse at all. (Note that the mouse should be over the JFrame at this point, but not over the frame's button.)
    3. Click the mouse again.
    Result:
    This causes the button on the frame to be clicked.
    It seems as if the frame thinks that the mouse pointer is located where it was when the dialog came up.
    Does anyone know how to prevent this from happening or a workaround?

    We are using 1.1.8 because our product has to run on Mac OS 8.x - 9.x (and this is the latest JRE supported by these platforms).
    When I say don't move the mouse, what I mean is when closing the dialog, if you don't move the mouse, it doesn't matter where the mouse pointer is, as long as it's over the frame. When you click it, the last button to get clicked will be clicked again. It's as if the frame thinks that the mouse hasn't moved since the dialog came up. This isn't a focus problem because if I set the focus on another control after opening the dialog (by calling requestFocus()), this problem still happens. I can also tab to another control after closing the dialog, but when clicking the mouse it still clicks the last button that was clicked. It's as if the frame needs to reset where the mouse position is when it becomes activated.

  • JDialog

    Hello all,
    I have JDialog window needs to on fixed position on screen. It should not be resized or moved to new location by user.
    Help is needed.....
    THanks

    Uhm, read the API docs?
    setResizable and setLocation
    As far as always in the same place, setAlwaysOnTop will help some, and maybe a FocusListener that sets the location anew every time the window gets Focus? (Although I find this to be a very bogus requirement).
    Once you've tried all those out, if it doesn't work the way you want, post your code and state your exact problem.

  • Popup a JDialog without it gaining focus. Can it be done?

    Can it be done?
    I have thought about having a JDialog already on screen but positioned off screen and move it onscreen when needed but seems a ugly idea. Any one got a nicer solution?

    setFocusableWindowState(false) sort of works but the jDialog does gain focus then focus is given back to whatever window had focus before the JDialog was shown.

  • Changing Position of JScrollBar in a JScrollPane

    Hi,
    I am having a JList in a JScrollPane, and wanna to display JScrollBar on the left of JList (by default its at Right).Can I change the position of JScrollBar in a JScrollPane?
    Pl. Help
    Manoj

    Use setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT)
    IMHO, unless you are writing an application for Arabic/Hebrew, it's not a Good Idea (even if it's for the Lefties Guild Of America). And if it's for Arabic/Hebrew the whole display has to be swapped, and for this there is an applyComponentOrientation() method for JFrame/JDialog which acts on all components.

  • Jumping JDialog

    Ive read some posts about this but neither of them really answer the question about why this is happening and how do i solve it, so i will throw it out to all of you geniuses for help.
    The problem is that when I create the undecorated jdialog and try to drag it using my own mouse handler. When you drag it for long periods of time it starts to flicker and jump all over the screen. Here's the code, try it out and let me know if you figure anything out.
    Compile and run, and then click the large button. A small bordered panel will appear somewhere near the middle of the screen. Grab an area with the mouse not far from the northern part of the new little panel. Start to drag it for a bit, all over the screen. After a short while, the box will begin to fly all over the place uncontrollably. Therein lies the problem.
    Thanks in advance
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.awt.image.BufferedImage;
    import javatest.components.BlankFrame.BlankRootPane;
    import javax.swing.AbstractAction;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import javax.swing.border.LineBorder;
    * @author atom
    public class JumpingJDialog extends JDialog
        private static int xLocation = 400;
        private static int yLocation = 400;
         * Creates a new instance of JumpingJDialog
        public JumpingJDialog(JFrame parent)
            super(parent, "", false);
            setUndecorated(true);
            setFocusable(false);
            setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            setAlwaysOnTop(true);
            setResizable(false);
            setLocation(xLocation, yLocation);
            setSize(300, 75);
            panel.setLayout(new BorderLayout());
            panel.setBorder(new LineBorder(Color.BLACK, 1));
            panel.add(new TitleBar(), BorderLayout.NORTH);
            add(panel);
        JPanel panel = new JPanel();
        private class TitleBar extends JPanel
            public TitleBar()
                setPreferredSize(new Dimension(getWidth(), 7));
                setOpaque(false);
                addMouseListener(ml);
                addMouseMotionListener(ml);
            TitleBarMouseListener ml = new TitleBarMouseListener();
            private class TitleBarMouseListener extends MouseAdapter implements MouseMotionListener
                double oldX, oldY;
                 * Invoked when a mouse button is pressed on a component and then
                 * dragged.  <code>MOUSE_DRAGGED</code> events will continue to be
                 * delivered to the component where the drag originated until the
                 * mouse button is released (regardless of whether the mouse position
                 * is within the bounds of the component).
                 * <p>
                 * Due to platform-dependent Drag&Drop implementations,
                 * <code>MOUSE_DRAGGED</code> events may not be delivered during a native
                 * Drag&Drop operation.
                public void mouseDragged(MouseEvent e)
                    Point p = JumpingJDialog.this.getLocation();
                    Point mp = e.getPoint();
                    SwingUtilities.convertPointToScreen(mp, TitleBar.this);
                    if (oldX < 0 || oldY < 0)
                        oldX = mp.x;
                        oldY = mp.y;
                    else
                        if (mp.x >= 0 && mp.y >= 0)
                            Toolkit.getDefaultToolkit().sync();
                            double deltax = mp.x - oldX;
                            double deltay = mp.y - oldY;
                            oldX = mp.x + deltax;
                            oldY = mp.y + deltay;
                            Rectangle bounds = JumpingJDialog.this.getBounds();
                            if (bounds.contains(mp))
                                JumpingJDialog.this.setLocation((int)(mp.x-pressedX), (int)(mp.y-pressedY));
                            else
                                JumpingJDialog.this.setLocation((int)mp.x-pressedX, (int)mp.y-pressedY);
                public void mouseMoved(MouseEvent e)
                int pressedX, pressedY;
                public void mousePressed(MouseEvent e)
                    pressedX = e.getX();
                    pressedY = e.getY();
        public static void main(String[] args)
            SwingUtilities.invokeLater(new Runnable()
                public void run()
                    final JFrame frame = new JFrame();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setSize(640, 480);
                    frame.setVisible(true);
                    frame.add(new JButton(new AbstractAction("New Dialog")
                        public void actionPerformed(ActionEvent e)
                            JumpingJDialog fd = new JumpingJDialog(frame);
                            fd.setVisible(true);
    }

    Here is the code for anyone who is interested
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.awt.image.BufferedImage;
    import javax.swing.AbstractAction;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JWindow;
    import javax.swing.SwingUtilities;
    import javax.swing.border.LineBorder;
    * @author atom
    public class JumpingJDialog extends JWindow
        private static int xLocation = 400;
        private static int yLocation = 400;
         * Creates a new instance of JumpingJDialog
        public JumpingJDialog(JFrame parent)
            super(parent);
            setFocusable(false);
            setAlwaysOnTop(true);
            setLocation(xLocation, yLocation);
            setSize(300, 75);
            panel.setLayout(new BorderLayout());
            panel.setBorder(new LineBorder(Color.BLACK, 1));
            panel.add(new TitleBar(), BorderLayout.NORTH);
            add(panel);
        JPanel panel = new JPanel();
        private class TitleBar extends JPanel
            public TitleBar()
                setPreferredSize(new Dimension(getWidth(), 7));
                setOpaque(false);
                addMouseListener(ml);
                addMouseMotionListener(ml);
            TitleBarMouseListener ml = new TitleBarMouseListener();
            Point location;
            MouseEvent pressed;
            private class TitleBarMouseListener extends MouseAdapter implements MouseMotionListener
                 * Invoked when a mouse button is pressed on a component and then
                 * dragged.  <code>MOUSE_DRAGGED</code> events will continue to be
                 * delivered to the component where the drag originated until the
                 * mouse button is released (regardless of whether the mouse position
                 * is within the bounds of the component).
                 * <p>
                 * Due to platform-dependent Drag&Drop implementations,
                 * <code>MOUSE_DRAGGED</code> events may not be delivered during a native
                 * Drag&Drop operation.
                public void mousePressed(MouseEvent me)
                    pressed = me;
                public void mouseDragged(MouseEvent me)
                    location = JumpingJDialog.this.getLocation(location);
                    int x = location.x - pressed.getX() + me.getX();
                    int y = location.y - pressed.getY() + me.getY();
                    JumpingJDialog.this.setLocation(x, y);
                    Toolkit.getDefaultToolkit().sync();
                public void mouseMoved(MouseEvent e)
            public void mouseMoved(MouseEvent e)
            int pressedX, pressedY;
            public void mousePressed(MouseEvent e)
                pressedX = e.getX();
                pressedY = e.getY();
        public static void main(String[] args)
            SwingUtilities.invokeLater(new Runnable()
                public void run()
                    final JFrame frame = new JFrame();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setSize(640, 480);
                    frame.setVisible(true);
                    frame.add(new JButton(new AbstractAction("New Dialog")
                        public void actionPerformed(ActionEvent e)
                            JumpingJDialog fd = new JumpingJDialog(frame);
                            fd.setVisible(true);
    }

  • Smooth animated moving/resizing of JDialog

    Greetings all,
    I'm not sure if this belongs here or in the Java 2D subforum, but whatever. I'm working on a Swing desktop application whose main frame is laid out in a 3x3 GridLayout. Some of the panels in this grid have JLists with very long entries in them, and our users frequently complain that these panels are too small, so we'd like to implement the ability for them to "pop out" into bigger panels temporarily. We did this by simply removing the panel from the grid and dropping it in a JDialog of suitable size.
    Now, it may seem pedantic, but I'm interested in making this as pretty as technologically possible. My approach thus far has been to make the JDialog undecorated and initially position it directly where the original panel was, then animate it growing by having a Timer call SetBounds with increasing parameters until the desired maximum size is reached. This looks pretty nice, but it's kind of jaggy and flickery. Is there a better way of doing this that takes advantage of Java's graphics capabilities?
    Thanks!

    We did this by simply removing the panel from the grid and dropping it in a JDialog of suitable size.It would probably be better to simply grab the model from the list and use it to create a new JList that you add to the dialog, that way you don't need to worry about replacing the list after the dialog is closed, because a component can only have a single parent.
    then animate it growing by having a Timer call SetBounds with increasing parameters until the desired maximum size is reached. This looks pretty nice, but it's kind of jaggy and flickerySounds reasonable to me, I don't see why it would be jaggy and flickery.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • How to have a box layout on a JDialog, with an image set as background

    Hi,
    I need to have a JDialog in which there is a background image set (I already did this part, but only with the default layout). I further need to add text to the lower part of the JDialog. (For this, I guess I need to have a box layout.). I am not able to do so, because if I do so, I wont be able to set image background to the entire JDialog. Please help me out with how to solve this issue?
    Thanks,
    Joby

    Hi jduprez,
    Thanks for the reply. I checked Rob Camick's blog. It gives a nice way to add an image to a panel (*master panel*) and to use it.
    I still have my problem open. The above solution gives panel that I can add to my JDialog. But on the bottom half of the image (as you said, BorderLayout.South), I need to add another structured set of components using a Border Layout again.!, ie, one more panel with a BorderLayout. So when I add
    this panel, to the master panel containing the image, then the image gets cut off, at that point. I tried using component.setOpaque(false) on my sub-panel, still it does not work. Any idea, how to achieve this...?
    Following is the code I have adapted.
    public class BackgroundPanel extends JPanel
         public static final int SCALED = 0;
         public static final int TILED = 1;
         public static final int ACTUAL = 2;
         private Paint painter;
         private Image image;
         private int style = SCALED;
         private float alignmentX = 0.5f;
         private float alignmentY = 0.5f;
         private boolean isTransparentAdd = true;
         public static void main(String[] args) {
              Image img = getImage("D:/imgs/Snowdrop.jpg");
              BackgroundPanel panel = new BackgroundPanel(img);
              JDialog dlg = new JDialog();
              dlg.setLayout(new BorderLayout());
              dlg.add(panel);
              panel.setTransparentAdd(true);
              Panel nPanel = new Panel();
              nPanel.setLayout(new BorderLayout());
              JLabel label = new JLabel();
              //label.set
              label.setText("<html>HI<br>This is another line<br><br><br><br><br><br><br><br><br><br></html>");
              nPanel.add(label, BorderLayout.NORTH);
              panel.add(nPanel/*label*/,BorderLayout.SOUTH);
              dlg.setSize(600, 500);
              dlg.setVisible(true);
         private static Image getImage(String fileName){
              File file = new File(fileName);
             Image image = null;
             try{
                  image = ImageIO.read(file);     
             catch(IOException ioe){
                  /*JOptionPane.showMessageDialog(dlg, "Error in loading image file",
                            "Error", JOptionPane.ERROR_MESSAGE, null);*/
             return image;
          *  Set image as the background with the SCALED style
         public BackgroundPanel(Image image)
              this(image, SCALED);
          *  Set image as the background with the specified style
         public BackgroundPanel(Image image, int style)
              this(image,style,-1,-1);
          *  Set image as the backround with the specified style and alignment
         public BackgroundPanel(Image image, int style, float alignmentX, float alignmentY)
              setImage( image );
              setStyle( style );
              if (alignmentX  > 0){
                   setImageAlignmentX( alignmentX );     
              if (alignmentY  > 0){
                   setImageAlignmentY( alignmentY );     
              setLayout( new BorderLayout() );
          *  Use the Paint interface to paint a background
         public BackgroundPanel(Paint painter)
              setPaint( painter );
              setLayout( new BorderLayout() );
          *     Set the image used as the background
         public void setImage(Image image)
              this.image = image;
              repaint();
          *     Set the style used to paint the background image
         public void setStyle(int style)
              this.style = style;
              repaint();
          *     Set the Paint object used to paint the background
         public void setPaint(Paint painter)
              this.painter = painter;
              repaint();
          *  Specify the horizontal alignment of the image when using ACTUAL style
         public void setImageAlignmentX(float alignmentX)
              this.alignmentX = alignmentX > 1.0f ? 1.0f : alignmentX < 0.0f ? 0.0f : alignmentX;
              repaint();
          *  Specify the horizontal alignment of the image when using ACTUAL style
         public void setImageAlignmentY(float alignmentY)
              this.alignmentY = alignmentY > 1.0f ? 1.0f : alignmentY < 0.0f ? 0.0f : alignmentY;
              repaint();
          *  Override method so we can make the component transparent
         public void add(JComponent component)
              add(component, null);
          *  Override method so we can make the component transparent
         public void add(JComponent component, Object constraints)
              if (isTransparentAdd)
                   makeComponentTransparent(component);
              super.add(component, constraints);
          *  Controls whether components added to this panel should automatically
          *  be made transparent. That is, setOpaque(false) will be invoked.
          *  The default is set to true.
         public void setTransparentAdd(boolean isTransparentAdd)
              this.isTransparentAdd = isTransparentAdd;
          *     Try to make the component transparent.
          *  For components that use renderers, like JTable, you will also need to
          *  change the renderer to be transparent. An easy way to do this it to
          *  set the background of the table to a Color using an alpha value of 0.
         private void makeComponentTransparent(JComponent component)
              component.setOpaque( false );
              if (component instanceof JScrollPane)
                   JScrollPane scrollPane = (JScrollPane)component;
                   JViewport viewport = scrollPane.getViewport();
                   viewport.setOpaque( false );
                   Component c = viewport.getView();
                   if (c instanceof JComponent)
                        ((JComponent)c).setOpaque( false );
          *  Add custom painting
         protected void paintComponent(Graphics g)
              super.paintComponent(g);
              //  Invoke the painter for the background
              if (painter != null)
                   Dimension d = getSize();
                   Graphics2D g2 = (Graphics2D) g;
                   g2.setPaint(painter);
                   g2.fill( new Rectangle(0, 0, d.width, d.height) );
              //  Draw the image
              if (image == null ) return;
              switch (style)
                   case SCALED :
                        drawScaled(g);
                        break;
                   case TILED  :
                        drawTiled(g);
                        break;
                   case ACTUAL :
                        drawActual(g);
                        break;
                   default:
                     drawScaled(g);
          *  Custom painting code for drawing a SCALED image as the background
         private void drawScaled(Graphics g)
              Dimension d = getSize();
              g.drawImage(image, 0, 0, d.width, d.height, null);
          *  Custom painting code for drawing TILED images as the background
         private void drawTiled(Graphics g)
                 Dimension d = getSize();
                 int width = image.getWidth( null );
                 int height = image.getHeight( null );
                 for (int x = 0; x < d.width; x += width)
                      for (int y = 0; y < d.height; y += height)
                           g.drawImage( image, x, y, null, null );
          *  Custom painting code for drawing the ACTUAL image as the background.
          *  The image is positioned in the panel based on the horizontal and
          *  vertical alignments specified.
         private void drawActual(Graphics g)
              Dimension d = getSize();
              Insets insets = getInsets();
              int width = d.width - insets.left - insets.right;
              int height = d.height - insets.top - insets.left;
              float x = (width - image.getWidth(null)) * alignmentX;
              float y = (height - image.getHeight(null)) * alignmentY;
              g.drawImage(image, (int)x + insets.left, (int)y + insets.top, this);
    }Thanks,
    Joby

  • Locating a JDialog in a JApplet

    My applet displays a JDialog object but, I can't locate the dialog at the center of the applet. Here is what I do:
    // this is call from the applet.
    MyDialog dialog = new MyDialog(this);
    // this is the constructor for my dialog
    MyDialog(JApplet owner) {
      super(owner,"Hello...",true);  // the compiler doesn't accept a JApplet, a Component nor any other type of object I try.
    }I have also tried to call the dialogs setLocation() method. The trouble here is that I can't find the center of the applet. I hope you can point my nose in the right direction.
    Thanks.

    If you pass the Applet as the parent, you will find a problem with your Dialog if you bring up another application window over the browser window while the Dialog is visible: on refocusing the browser window, the Dialog will still have the focus but will be hidden behind the browser window.
    Use the following to get a Frame for a Dialog. This prevents the above from happening and ensure the Dialog will always be centred over the applet:
         public Frame getDialogFrame()
              /* CREATES AND POSITIONS A FRAME USED BY DIALOGS
                 TO ENSURE THAT DIALOG MODAL AND CENTRED OVER APPLET*/
              Object parent = this.getParent();
              while(!(parent instanceof Frame)) parent=((Component)parent).getParent();
              Frame dialogFrame = (Frame) parent;
              Point p = this.getLocationOnScreen();
              dialogFrame.setLocation(p.x, p.y);
              return dialogFrame;
         }

Maybe you are looking for