Java GUI之事件監聽與處理的匿名類實現方法:
- package com.sinosuperman.driver;
-
- import java.awt.Dimension;
- import java.awt.FlowLayout;
- import java.awt.Toolkit;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
-
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JOptionPane;
- import javax.swing.JPanel;
-
- public class MainBench {
- public static void main(String[] args) {
- JFrame frame = new MyFrame();
- }
- }
-
- class MyFrame extends JFrame {
- private static final long serialVersionUID = 1L;
- Toolkit tk = Toolkit.getDefaultToolkit();
- Dimension d = tk.getScreenSize();
- JPanel panel;
- public MyFrame() {
- panel = new MyPanel();
- this.add(panel);
- this.setSize((int) d.getWidth() / 2, (int) d.getHeight() / 2);
- this.setLocation((int) (d.getWidth() - this.getWidth()) / 2, (int) (d.getHeight() - this.getHeight()) / 2);
- this.setResizable(false);
- this.setVisible(true);
- }
- }
-
- class MyPanel extends JPanel {
- private static final long serialVersionUID = 5263963243638550398L;
- JButton okBtn;
- JButton exitBtn;
- public MyPanel() {
- this.setLayout(new FlowLayout(FlowLayout.CENTER));
- okBtn = new JButton("OK");
- exitBtn = new JButton("Exit");
- okBtn.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- JOptionPane.showConfirmDialog(null, "Are you sure?");
- }
- });
- exitBtn.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- int result = JOptionPane.showConfirmDialog(null, "Are you sure to exit?");
- if (result == JOptionPane.YES_OPTION) {
- System.exit(0);
- }
- }
- });
- this.add(okBtn);
- this.add(exitBtn);
- }
- }