Advertisement
KuoHsiangYu

ActionEvent2_GUI視窗程式

Aug 23rd, 2019
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.65 KB | None | 0 0
  1. //https://www.facebook.com/groups/1403852566495675/permalink/2397128547168067/
  2. package com.sample;
  3.  
  4. import java.awt.Button;
  5. import java.awt.Color;
  6. import java.awt.FlowLayout;
  7. import java.awt.Frame;
  8. import java.awt.event.ActionEvent;
  9. import java.awt.event.ActionListener;
  10. import java.awt.event.WindowAdapter;
  11. import java.awt.event.WindowEvent;
  12.  
  13. public class ActionEvent2 {
  14.     private static Frame frame = new Frame();
  15.     private static Action action = new Action();
  16.     private static Button btn1 = new Button("Blue");
  17.     private static Button btn2 = new Button("Green");
  18.     private static Button btn3 = new Button("Red");
  19.     private static Button btn4 = new Button("Exit");
  20.  
  21.     public static void main(String args[]) {
  22.         btn1.addActionListener(action);
  23.         btn2.addActionListener(action);
  24.         btn3.addActionListener(action);
  25.         btn4.addActionListener(action);
  26.  
  27.         frame.setTitle("Action Event");
  28.         frame.setLayout(new FlowLayout(FlowLayout.LEFT));
  29.         frame.setSize(400, 250);
  30.         frame.setLocation(350, 250);
  31.         frame.add(btn1);
  32.         frame.add(btn2);
  33.         frame.add(btn3);
  34.         frame.add(btn4);
  35.         frame.addWindowListener(new WindowAdapter() {
  36.             @Override
  37.             public void windowClosing(WindowEvent e) {
  38.                 System.exit(0);
  39.             }
  40.         });
  41.         frame.setVisible(true);
  42.     }
  43.  
  44.     private static class Action implements ActionListener {
  45.         @Override
  46.         public void actionPerformed(ActionEvent e) {
  47.             Button button = (Button) e.getSource();
  48.             if (button == btn1) {
  49.                 frame.setBackground(Color.blue);
  50.             } else if (button == btn2) {
  51.                 frame.setBackground(Color.green);
  52.             } else if (button == btn3) {
  53.                 frame.setBackground(Color.red);
  54.             } else {
  55.                 System.exit(0);
  56.             }
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement