消息对话框(MessageDialog)
方法:
public static void showMessageDialog(Component parentComponent,Object message, String title, int messageType)
}
参数解释
Component parentComponent:决定了出现的对话框在哪个窗体里出现。
Object message:显示的信息(不一定是个String)
String title:对话框的标题
int messageType:消息类型,是JOptionPane的静态常量。
小栗子的功能:
模拟了输入密码提示错误的功能。
效果图:
package MyJOptionPane;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class myMessageDialog extends JFrame {
private static final long serialVersionUID = 1L;
// 定义组件
JPanel jp1, jp2, jp3;
JLabel jlb1, jlb2;
JButton jb1, jb2;
JTextField jtf1;
JPasswordField jpf1; //输密码的时候,看不到
public static void main(String[] args) {
myMessageDialog d = new myMessageDialog();
d.setVisible(true);
}
// 构造函数
public myMessageDialog() {
jp1 = new JPanel();
jp2 = new JPanel();
jp3 = new JPanel();
jlb1 = new JLabel("用户名");
jlb2 = new JLabel("密 码");
jb1 = new JButton("登录");
jb1.addActionListener(new btListener());
jb2 = new JButton("取消");
jtf1 = new JTextField(10);
jpf1 = new JPasswordField(10);
this.setLayout(new GridLayout(3, 1));
// 加入各个组件
jp1.add(jlb1);
jp1.add(jtf1);
jp2.add(jlb2);
jp2.add(jpf1);
jp3.add(jb1);
jp3.add(jb2);
// 加入到JFrame的面板上
Container pane = this.getContentPane();
pane.add(jp1);
pane.add(jp2);
pane.add(jp3);
this.setSize(400, 300);
this.setTitle("登录");
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
}
private class btListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null, "输入密码错误","忘记密码了吗?", JOptionPane.WARNING_MESSAGE);
}
}
}
确认对话框(ConfirmDialog)
方法:
public static int showConfirmDialog(Component parentComponent,Object message)
参数解释见上。
小栗子的功能:
下面的代码实现了在即将关闭窗口的时候,调出一个确认是否关闭的对话框。
效果图。
package MyJOptionPane;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class myConfirmDialog {
public static void main(String[] args) {
Frame frame = new Frame();
frame.setVisible(true);
}
}
class Frame extends JFrame
{
Frame()
{
this.setSize(300, 200);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
// DO_NOTHING_ON_CLOSE 就是啥也不做,交给监听器处理。
this.addWindowListener(new WindowCloserListener());
}
}
class WindowCloserListener extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
if(JOptionPane.showConfirmDialog(null,"Are you sure close the window?","",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION) {
// System.exit(0);
//这样是整个程序都结束运行了,而不是仅仅关闭窗口
((Frame)e.getSource()).dispose();
//事件源是 frame ,JFrame有dispose()方法,关闭当前窗体以及组件
}
}
}