How to implement an anonymous class for event listening and processing in Java GUI

Source: Internet
Author: User
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);}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.