2

I have created a method to display message in a dialog but the size of the dialog changes each time I run my java swing application below is the link to screen shot of dailog:

Improrer Message Box Display
Proper Message Box Display

Below is the method (SetMSGDialog) I have created for JDialog Display

public class DemoClass
{
    private static JDialog MSGDialog;
    private static JPanel MSGPanel;
    private static JLabel MSGLabel;
    private static JButton MSGButton;

    DemoClass()
    {
        MSGDialog = new JDialog(MSGDialog,"Message",JDialog.ModalityType.APPLICATION_MODAL);
        MSGPanel = new JPanel(null);
        MSGLabel = new JLabel();
        MSGButton = new JButton("Close");
    }

    public static void SetMSGDialog(String MSG)
    {
        MSGDialog.setModal(true);
        MSGDialog.setSize(400,125);
        MSGDialog.setResizable(false);
        MSGDialog.setLocationRelativeTo(null);
        MSGLabel.setText(MSG);
        MSGButton.setText("Close");
        MSGLabel.setBounds(25, 25, 375, 30);
        MSGButton.setBounds(160,70,80,30);
        MSGPanel.add(MSGLabel);
        MSGPanel.add(MSGButton);
        MSGDialog.add(MSGPanel);
        MSGDialog.setVisible(true);
    }

    public static void main(String[] args)
    {
        DemoClass MsgBox = new DemoClass();
        MsgBox.SetMSGDialog("Please Login First");
    }
}

Please tell me what I am doing wrong. what I have to do inorder to display Jdialog correctly.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Abhishek
  • 139
  • 2
  • 13
  • 1
    1) get rid of `setSize(...)`, `setBounds(...)` and the like. 2) use layout managers to help size and position components. 3) pack before displaying the dialog. 4) don't over-static your program. – Hovercraft Full Of Eels Jul 11 '15 at 13:27
  • BTW - Ubuntu, Eclipse, Linux?? There is no need to tell us your OS and IDE, unless the code only fails under those specific conditions! And trust me, this code would fail on any system, using any IDE. – Andrew Thompson Jul 11 '15 at 14:39

2 Answers2

3

You ask why your JDialog is not displaying properly, and the main reason is that your code ignores the layout managers that your components already use. A quick and terrible solution is to use an absolute or null layout, but this is not recommended for component placement as this makes for very inflexible GUI's that while they might look good on one single platform and screen resolution, they look terrible on most other platforms or screen resolutions and are very difficult to update and maintain.

Suggestions:

  • Get rid of setSize(...), setBounds(...) and the like.
  • Use layout managers to help size and position components.
  • Pack before displaying the dialog.
  • Don't over-use the static modifier in your program.
  • You could do something like the code below, but having shown this, a JOptionPane would be the easiest way to display this type of message.

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class DemoClass2 extends JPanel {
   // constants
   private static final String TITLE = "Message";
   private static final float LABEL_POINTS = 24f;
   private static final int L_GAP = 15;
   private static final int B_GAP = 25;

   // static poor man's singlton instance
   private static DemoClass2 demoClass2;
   private JDialog dialog = new JDialog();
   private JLabel label = new JLabel("", SwingConstants.CENTER);

   public DemoClass2() {
      dialog.setModal(true);
      dialog.setTitle(TITLE);

      label.setFont(label.getFont().deriveFont(Font.BOLD, LABEL_POINTS));
      label.setBorder(BorderFactory.createEmptyBorder(L_GAP, L_GAP, L_GAP, L_GAP));

      JPanel btnPanel = new JPanel(new GridBagLayout());
      btnPanel.setBorder(BorderFactory.createEmptyBorder(B_GAP, B_GAP, B_GAP, B_GAP));
      btnPanel.add(new JButton(new DisposeAction("Close", KeyEvent.VK_C)));

      setLayout(new BorderLayout());
      //setBorder(border);
      add(label, BorderLayout.PAGE_START);
      add(btnPanel, BorderLayout.CENTER);

      dialog.getContentPane().add(this);
   }

   private void setMessage(String message) {
      label.setText(message);
   }

   private void display() {
      dialog.setResizable(false);
      dialog.pack();
      dialog.setLocationRelativeTo(null);
      dialog.setVisible(true);
   }

   public void setMessageAndDisplay(String message) {
      setMessage(message);
      display();
   }

   public static void displayMessage(String message) {
      if (demoClass2 == null) {
         demoClass2 = new DemoClass2();
      }
      demoClass2.setMessageAndDisplay(message);
   }

   private class DisposeAction extends AbstractAction {
      public DisposeAction(String name, int mnemonic) {
         super(name);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         Component c = (Component) e.getSource();
         if (c == null) {
            return;
         }
         Window win = SwingUtilities.getWindowAncestor(c);
         if (win == null) {
            return;
         }
         win.dispose();         
      }
   }

   private static void createAndShowGui() {
      DemoClass2.displayMessage("Fubars Rule!!!");

      DemoClass2.displayMessage("This is a bit of a longer message. The dialog should get bigger.");
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

Have you tried removing MSGDialog.setSize(400,125); and let Swing decide the size?

Sweder Schellens
  • 410
  • 1
  • 4
  • 14
  • Yes , I have tried that but then Dialog is very small which is hard to see – Abhishek Jul 11 '15 at 13:26
  • Tried calling `pack()`before calling `MSGDialog.setVisible(true)`? – Sweder Schellens Jul 11 '15 at 13:32
  • 1
    The trouble here is that the OP has already 'shot themselves in the foot' by not using layouts. When we call `pack()` usually it will reduce the frame to the size it needs to display the components, but since the layout is `null`, the container has no way to calculate its preferred or minimum size, and will return 0x0 for both. The solution, of course, is to **use layouts** (and padding/borders for white space) to add the components, *then* use `pack()` and `setVisible(true)` .. – Andrew Thompson Jul 11 '15 at 14:34