实训作业--窗口

import java.awt.BorderLayout;
import java.awt.Color;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
    import javax.swing.JButton;
 import javax.swing.JFrame;
 import javax.swing.JPanel;
public class Main {
 public static void main(String[] args) {
     JFrame frame = new JFrame();
     JPanel panel1 = new JPanel();
     JPanel panel2 = new JPanel();
     frame.setSize(300, 200);
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     JButton redButton = new JButton("Red");
     JButton greenButton = new JButton("Green");
     JButton blueButton = new JButton("Blue");
     @SuppressWarnings("serial")
  class Listener extends JPanel implements ActionListener {
       public void actionPerformed(ActionEvent event) {
         Color color;
         if (event.getSource() == redButton) {
           color = Color.red;
           redButton.setBackground(color);
           panel2.setBackground(color);
         } else if (event.getSource() == greenButton) {
           color = Color.green;
           greenButton.setBackground(color);
           panel2.setBackground(color);
         } else {
           color = Color.blue;
           blueButton.setBackground(color);
           panel2.setBackground(color);
         }
         setBackground(color);
         repaint();
       }
     }
     redButton.addActionListener(new Listener());
     greenButton.addActionListener(new Listener());
     blueButton.addActionListener(new Listener());
     panel1.add(redButton);
     panel1.add(greenButton);
     panel1.add(blueButton);
     frame.add(panel2);
     frame.add(panel1);
     frame.setVisible(true);
     frame.add(panel1,BorderLayout.NORTH);
     frame.add(panel2,BorderLayout.CENTER);
   }
 }

 

转载于:https://www.cnblogs.com/zhangyixing/p/11020602.html

你可能感兴趣的:(实训作业--窗口)