Java_ActionListener_Test

来源:互联网 发布:网络云音乐 编辑:程序博客网 时间:2024/04/29 17:13
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4. public class ActionTest
  5. {
  6.     public static void main(String[] args)
  7.     {
  8.         ActionFrame aFrame = new ActionFrame();
  9.         aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  10.         aFrame.setVisible(true);
  11.     }
  12. }
  13. class ActionFrame extends JFrame 
  14. {
  15.     public ActionFrame()
  16.     {
  17.         Toolkit t = Toolkit.getDefaultToolkit();
  18.         Dimension d = t.getScreenSize();
  19.         
  20.         int screenWidth = (int)d.getWidth();
  21.         int screenHeight = (int)d.getHeight();
  22.         
  23.         setSize(screenWidth/2,screenHeight/2);
  24.         setLocation(screenWidth/4,screenHeight/4);
  25.         setTitle("ActionTest_InnerClass");
  26.         
  27.         ActionPanel aPanel = new ActionPanel();
  28.         Container content = getContentPane();
  29.         content.add(aPanel);        
  30.     }
  31. }
  32. class ActionPanel extends JPanel
  33. {
  34.     public ActionPanel()
  35.     {
  36.         makeButton("YellowButton",Color.YELLOW);
  37.         makeButton("BlueButton",Color.BLUE);
  38.         makeButton("GreenButton",Color.GREEN);
  39.     }
  40.     
  41.     public void makeButton(String buttonName,final Color c)
  42.     {
  43.         JButton aButton = new JButton(buttonName);
  44.         aButton.addActionListener(
  45.             new ActionListener()
  46.                 {
  47.                     public void actionPerformed(ActionEvent e)
  48.                     {
  49.                         setBackground(c);
  50.                     }   
  51.                 }
  52.         );
  53.         add(aButton);
  54.     }
  55. }

    代码中的黑体部分就是对编译错误的修改,Color c必须是final类型的。当时也在想String buttonName前面也没有final修饰,为什么不出编译错误呢?是因为Java中的String类是final类型的。所以说String类是不能被继承的!!!

原创粉丝点击