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 ofJDialog
on theX
-axis? - How to set the size of the
JDialog
relative to the size of the text as inJOptionPane.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;
}