Java如何创建消息对话框?
本示例演示如何使用JOptionPane类方法创建消息对话框。在下面的代码,你会看到使用的JOptionPane.showMessageDialog(),JOptionPane.showInputDialog()和JOptionPane.showConfirmDialog()。
package org.nhooo.example.swing;import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MessageDialogDemo extends JFrame {
public MessageDialogDemo() throws HeadlessException {
initialize();
}
private void initialize() {
setSize(200, 200);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JButton button1 = new JButton("Click Me!");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 显示带有文本消息的消息对话框
JOptionPane.showMessageDialog((Component) e.getSource(),
"Thank you!");
}
});
JButton button2 = new JButton("What is your name?");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 显示一个输入对话框,要求您输入一些文本
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(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 显示一个确认对话框,要求输入是或否
// 按钮。
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) {
// 不执行任何操作,继续运行应用程序
}
}
});
setLayout(new FlowLayout(FlowLayout.CENTER));
getContentPane().add(button1);
getContentPane().add(button2);
getContentPane().add(button3);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MessageDialogDemo().setVisible(true);
}
});
}
}
以上是 Java如何创建消息对话框? 的全部内容, 来源链接: utcz.com/z/343197.html