This example demonstrate how to create a message dialog box using the JOptionPane
class methods. In the code below you’ll see the use of JOptionPane.showMessageDialog()
, JOptionPane.showInputDialog()
and JOptionPane.showConfirmDialog()
.
package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
public class MessageDialogDemo extends JFrame {
public MessageDialogDemo() throws HeadlessException {
initialize();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MessageDialogDemo().setVisible(true));
}
private void initialize() {
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JButton button1 = new JButton("Click Me!");
button1.addActionListener(e -> {
// Show a message dialog with a text message
JOptionPane.showMessageDialog((Component) e.getSource(),
"Thank you!");
});
JButton button2 = new JButton("What is your name?");
button2.addActionListener(e -> {
// Show an input dialog that will ask you to input some texts
String text = JOptionPane.showInputDialog((Component) e.getSource(),
"What is your name?");
if (text != null && !text.equals("")) {
JOptionPane.showMessageDialog((Component) e.getSource(),
"Hello " + text);
}
});
JButton button3 = new JButton("Close Application");
button3.addActionListener(e -> {
// Show a confirmation dialog which will ask to for a YES or NO
// button.
int result = JOptionPane.showConfirmDialog((Component) e.getSource(),
"Are you sure want to close this application?");
if (result == JOptionPane.YES_OPTION) {
System.exit(0);
} else if (result == JOptionPane.NO_OPTION) {
// Do nothing, continue to run the application
}
});
setLayout(new FlowLayout(FlowLayout.CENTER));
getContentPane().add(button1);
getContentPane().add(button2);
getContentPane().add(button3);
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024