dialogexample.java

来自「Corejava」· Java 代码 · 共 63 行

JAVA
63
字号
//DialogExample.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class DialogExample
{  
	public static void main(String[] args)
	{  
		DialogFrame frame = new DialogFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.show();
	}
}

class DialogFrame extends JFrame
{
	public DialogFrame()
	{
		setTitle("DialogExample");
		setSize(WIDTH, HEIGHT);

		Container contentPane = getContentPane();

		//建立容器面板
		JPanel buttonPanel = new JPanel();

		logoutButton = new JButton("退出");
		//注册事件监听器
		logoutButton.addActionListener(new LogoutAction());
		buttonPanel.add(logoutButton);

		contentPane.add(buttonPanel,BorderLayout.SOUTH);
	}

	//实现事件监听器
	private class LogoutAction
		implements ActionListener
	{
		public void actionPerformed(ActionEvent event)
		{
			//新建确认型对话框
			int selection = JOptionPane.showConfirmDialog(
				DialogFrame.this,
				"Are you sure?", "Logout", 
				JOptionPane.OK_CANCEL_OPTION,
				JOptionPane.WARNING_MESSAGE);
			
			//如果选择了“确认”按钮,则退出
			if (selection == JOptionPane.OK_OPTION)
			{
				System.exit(0);
			}
		}
	}

	public static final int WIDTH = 200;
	public static final int HEIGHT = 120;

	private JButton logoutButton;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?