0

Good afternoon, everyone. I have such a question, I'm creating my own messageBox, because I can't completely change the standard JOptionPane.showMessageDialog(), for example, the style of the OK, CANCEL button, or you can, but it takes more time. In general, I do not understand:

  • How to set JLabel, in the center of JDialog on the X-axis?
  • How to set the size of the JDialog relative to the size of the text as in JOptionPane.showMessageDialog()?

My messageBox:

public static void messageBox(JFrame parent, String title, String message, int type) {
        JDialog dialog = new JDialog(parent, title, true);
        dialog.setComponentOrientation(parent.getComponentOrientation());
        dialog.setSize(600, 150); 
        dialog.setResizable(false);
        dialog.setLocationRelativeTo(parent);

        JLabel label = new JLabel(message, SwingConstants.CENTER);
        label.setFont(Utils.DEFAULT_AWT_FONT);
        label.setSize(7 * message.length(), 20);  
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setVisible(true);
        
        JButton okButton = createStyledJButton("OK", dialog.getWidth() / 2 - 70, 70, 120, 25);
        okButton.setVisible(true);
        okButton.addActionListener((ActionEvent e) -> {
            dialog.setVisible(false);
        });
        
        Container pane = dialog.getContentPane();
        pane.setLayout(null);
        pane.add(label, BorderLayout.CENTER);
        pane.add(okButton, BorderLayout.CENTER);
    
        dialog.setVisible(true);
        dialog.dispose();
    }

public static JButton createStyledJButton(String label, int x, int y, int width, int height) {
        JButton button = new JButton(label);
        button.setFocusable(false);
        button.setBounds(x, y, width, height);
        button.setBackground(Color.WHITE);
        button.setFont(Utils.DEFAULT_AWT_FONT);
        button.setForeground(Color.BLACK);
        button.setBorder(BorderFactory.createEtchedBorder());
        return button;
    }
Kenny
  • 113
  • 9
  • 2
    1) Get rid of all the `setSize` calls. They're pointless at best (ignored), counterproductive otherwise (they're just a guess, and will be wrong on every other PLAF, OS, ..). Swing components know how big they should be, `pack()` will size the top level container (`JFrame`, `JDialog` etc) appropriately. 2) See [this answer](https://stackoverflow.com/a/7181197/418556) for centering a component within a container. – Andrew Thompson Jul 06 '21 at 20:17
  • BTW - it's best to focus on a *single* question per thread. As it happens, I *did* answer both 'questions' in 2 comments before I even realized there were two questions - but don't rely on that to happen. – Andrew Thompson Jul 06 '21 at 20:20

0 Answers0