Swing程序设计Java----学习笔记整理

1.swing特点 
    原来的AWT组件来源于Java.awt包,含有AWT组件的Java应用程序在不同的平台上执行时,每个平台的GUI组件的显示有所不同

    在不同平台上运行Swing开发的应用程序是,可以统一GUI组件的显示风格,因为Swing组件允许编程人员在跨平台是指定统一的外观和风格
  
    Swing组件被称之为轻量级组件

    swing由Java语言编写可以运行在不同平台上,所以称之为轻量级

    由其他语言编写,不能运行于其他平台上组件,称为重量级组件

   awt是swing组件的前身,是重量级组件

2.swing包
    为了有效的学习Swing组件,必须了解Swing包的层次结构和继承关系
 
    swing组件重要的类是Component类,Container类和JComponent类
    

   继承关系
   Java.lang.object类
        Java.awt.Component类
             java.awt.Container类
                  Java.swing.JComponent类

3.常用swing组件概述()

     JButton      代表Swing按钮,按钮可以带一些图片或文字
     JcheckBox    代表Swing中复选框组件
     JcomBox      代表下拉列表框,可以在下拉显示区域显示多个选项
     JFrame       代表Swing的框架类
     Jdialog      代表Swing版本的对话框
     JLabel       代表Swing中的标签组件
     JRadioButton 代表Swing的单选按钮
     JList        代表能够在用户界面中显示一系列条目的组件
     JTextField   代表文本框
     JpasswordField  代表密码框
     JTextArea       代表Swing中的文本区域
     JOptionPaen     代表Swing中的一些对话框     
常用窗体
4.JFrame窗体
  JFrame窗体是一个容器,它是Swing程序各个组件的载体,可以将JFrame看作是承载这些Swing组件的容器

  在开发应用程序时可以通过继承Java.Swing.JFrame类来创建一个窗体,在窗体中添加组件,同时为每个组件设置事件

  由于该窗体继承了JFrame类,所以它拥有一些最大化,最小化,关闭的按钮
JFrame常用的构造方法

  JFrame()无参数
  JFrame(String title) title JFrame的名字

 private static final long serialVersionUID = 1L;
   serialversionUID作用:  相当于Java的身份证,主要用于版本控制
 序列化时为了保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性。

有两种生成方式:
一个是默认的1L,比如:private static final long serialVersionUID = 1L;
一个是根据类名、接口名、成员方法及属性等来生成一个64位的哈希字段,比如:
private static final long serialVersionUID = xxxxL;
当你一个类实现了Serializable接口,如果没有定义serialVersionUID,Eclipse会提供这个
提示功能告诉你去定义 。在Eclipse中点击类中warning的图标一下,Eclipse就会
自动给定两种生成的方式。如果不想定义它,在Eclipse的设置中也可以把它关掉的,设置如下:
Window ==> Preferences ==> Java ==> Compiler ==> Error/Warnings ==>
Potential programming problems
  

      private static final long serialVersionUID = 1L;//java的身份证,用于版本的控制;版本升级时反序列化仍保持对象的唯一性
                  public void CreateJFrame(String title){//定义有参数的构造方法
                 JFrame jf  = new JFrame(title);//实例化一个JFrame对象
                 Container container = jf.getContentPane();//获取一个容器
                 JLabel jl = new JLable("这是一个JFrame窗体");//创建一个JLabel标签  
                //使标签上的文字居中
                 j1.setHorizontalAlignment(SwingConstants.CENTER);
                   container.add(jl);//将标签添加到容器中
                   container.setBackground(Color.white);//设置容器的背景颜色
                 jf.setVisible(true);//使窗体可视
                 jf.setsize(200,150);//设置窗体大小
              //设置窗体关闭方式
    jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
 
}

              //在main函数(主方法)中调用构造方法
              new Example1().CreateJFrame("JFrame窗体");


5.JDialog窗体
          功能:从一个窗体中弹出另外一个窗体,与IE浏览器弹出对话框类似
          实质:是另外一种类型的窗体,与JFrame窗体类似
          JDialog窗体在使用时也需要调用getContentPane()方法将窗体转化为容器,然后在容器中设置窗体的特性
 常用的JDialog构造方法
       JDialog()                               无参数的构造方法  他会创建一个没有标题的对话框
       JDialog(Frame owner)                    指定对话框的封装体
       JDialog(Frame owner,Boolean model)   指定对话框是否为model对话框
       JDialog(Frame owner,String title)    为对话框设置标题
       

 案例:
   

 //用于Java的版本的控制,版本升级时反序列化扔能保持对象的唯一性
     private static final long serialVersionUID1 =6500071369070027256l;
     //创建一个无参数的MyJDialog()方法
    public MyJDialog(){
        /*调用基类中的某一个构造函数,一般是构造函数的第一行
         * 
         * 设置父类窗体    窗体的标题  确定是model对话框
         * */
        super(new MyFrame(),"第一个JDialog窗体",true);
        //调用getContentPane()方法将窗体转化为容器
        Container container = getContentPane();
        //创建一个JLabel标签
        container.add(new JLabel("这是一个对话框"));
        //设置窗体大小
        setSize(100,100);  
        
    }
public static void main(String[] args) {
        new MyJDialog();
    }
    
    class MyFrame extends JFrame{
        private static final long serialVersionUID = -1337786324275247741L;
        public MyFrame(){
            Container container = getContentPane();
            //布局显示为null 当布局显示为null 需要设置窗体的显示位置
            container.setLayout(null);
            
            JLabel j1 = new JLabel("这是一个JFrame窗体");
            /*设置对齐方式
             * JLabel标签提供的两种对齐方式
             * #j1.setHorizontalAlignment  设置水平对齐方式; 
             * 三个参数
             *   SwingConstants.LEFT:左对齐;(默认值,也就是不设置时则左对齐)
             *   ¨ SwingConstants.CENTER:居中对齐;
             *  ¨ SwingConstants.RIGHT:右对齐; 
             *  
             *   #setVerticalAlignment:设置垂直对齐方式;
             *   三个参数
             *   ¨ SwingConstants.TOP:向上对齐;
             *   ¨ SwingConstants.CENTER:居中对齐;(默认值,也就是不设置时居中对齐)
             *   ¨ SwingConstants.BOTTOM:向下对齐;
             * */
            j1.setHorizontalAlignment(SwingConstants.CENTER);
            //将标签添加JDialog到窗体中
            container.add(j1);
            //创建以按钮
            JButton b1 = new JButton("弹出对话框");
            //设置窗体的显示位置
            b1.setBounds(10,10,100,21);
            //使用内部类 中的匿名类  使MyJDialog窗体可见
            b1.addActionListener(new ActionListener(){
            
                @Override
                public void actionPerformed(ActionEvent e) {
                    // TODO 自动生成的方法存根
                    new MyJDialog().setVisible(true);
                }
                
            });
          //将按钮添加到窗体中
            container.add(b1);
           //设置窗体的颜色
            container.setBackground(Color.white);
          //设置窗体的大小
            setSize(200,200); 
         //设置窗体的关闭方式
             setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
          //使窗体可见
              setVisible(true);  
         }
    }


标签组件与图标
6.      标签的使用
        标签由JLabel定义,它的父类为JComponent类
        标签可以显示一行只读文本,一个图片或带图片的文本,它并不能产生任何类型的事件,只是简单的显示文本和图片
        标签的特性可以指定标签上文本的对齐方式

 JLabel标签的构造方法
 JLabel()创建一个没有图片的JLabel实例,标题为空字符
 JLabel(Icon image)  使用指定图片创建一个JLabel实例
 JLabel(Icon image,int horizontalAlignment)创建一个具有指定图片和水平对齐的JLabel实例
 JLabel(String text)使用指定文本创建一个JLabel实例
 JLabel(String text,Icon icon,int horizontalAlignment)  创建一个JLabel文本,图像和水平对齐的JLabel实例
 JLabel(String text,int horizontalAlignment)            创建一个具有指定文本和水平对齐的JLabel实例
  
7.图标的使用
   
  Swing中的图标可以放置在按钮,标签等组件上,用于描述组件的用途
  图标可以使用Java支持的图片文件类型进行创建
  图标还可以用Java.awt.Graphics提供的方法创建   

 public class DrawIcon implements Icon {
     private int width;
     private int height;
     @Override//实现getIconHeight()方法
     public int getIconHeight() {
         // TODO 自动生成的方法存根
         return this.height;
     }
     @Override//实现getIconWidth()
     public int getIconWidth() {
         // TODO 自动生成的方法存根
         return this.width;
     }
     //定义构造方法
  public  DrawIcon(int width,int height){
    this.width = width;
    this.height= height;
      
  }
  //实现paintIcon方法
  public void paintIcon(Component arg0,Graphics arg1,int x,int y){
     //绘制一个圆
      arg1.fillOval(x, y, width, height);
      
  }
  public static void main(String[] args){
      //调用DrawIcon类
      DrawIcon icon = new DrawIcon(15,15);
      
      //创建一个标签,并设置标签上的文字在标签正中间
      JLabel j = new JLabel("测试",icon,SwingConstants.CENTER);
      //创建一个JFrame窗体
      JFrame jf = new JFrame();
      // 
      Container c = jf.getContentPane();
      //把JLabel标签添加到窗体中
      c.add(j);
      
     jf.setSize(100,100);
     jf.setVisible(true);
     jf.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
  }

}

     public class MyImageIcon extends JFrame{
    private static final long serialVersionUID = 1L;

    public MyImageIcon() {
        Container container = getContentPane();
        // 创建一个标签
        JLabel jl = new JLabel("这是一个JFrame窗体", JLabel.CENTER);
        // 获取图片所在的URL
        URL url = MyImageIcon.class.getResource("imageButton.jpg");
        Icon icon = new ImageIcon(url); // 实例化Icon对象
        jl.setIcon(icon); // 为标签设置图片
        // 设置文字放置在标签中间
        jl.setHorizontalAlignment(SwingConstants.CENTER);
        jl.setOpaque(true); // 设置标签为不透明状态
        container.add(jl); // 将标签添加到容器中
        setSize(250, 100); // 设置窗体大小
        setVisible(true); // 使窗体可见
        // 设置窗体关闭模式
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    
    public static void main(String args[]) {
        new MyImageIcon(); // 实例化MyImageIcon对象
    }
}


常用布局管理器
8.绝对布局
   硬性指定组件在容器中的位置和大小,通过绝对坐标的方式来实现
 绝对布局的步骤:
   1.使用Container.setLayout(null);方法取消布局管理器
   2.使用Component.setBounds();方法设置每个组件的大小和位置

 以窗体中的按钮为例  当该变窗体大小是,窗体中的按钮大写位置都不会发生变化,这就是绝对布局

 
9.流布布局管理器  Flowlayout

     流布管理器在整个容器中,从左到右摆放组件,直到占据这一行所有的空间,才向下移动一行。
     默认情况下每个组件都是居中排列但是通过设置也可以更改组件在每一行上的位置
     可以通过设置,设置组件在每一行上的位置


    FlowLayout类中具有以下常用的构造方法
    public Flowlayout()
    public FlowLayout(int alignment)
    public FlowLayout(int alignment,int horizGap,intvertGap)
在alignment参数表示使用流布局管理器后组件在每一行的具体摆放位置       

public class FlowLayoutPosition  extends JFrame{
    private static final long serialVersionUID = -1337786324275247741L;
        public FlowLayoutPosition(){
        setTitle("本窗体为流布局管理器");//设置流布局管理器的标题
        Container c = getContentPane(); //获取一个Container容器
      setLayout(new FlowLayout(2,10,10));//设置布局管理器 为流布管理器

    for(int i =0;i<10;i++){
        c.add(new JButton("button"+i));
    }
    setSize(300,200);
    setVisible(true);
    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    
    }
    public static void main(String[] args) {
        new FlowLayoutPosition();
    }
}

10.边界布局管理器  BorderLayout
    在默认不指定窗体布局的情况下Swing组件的布局默认是BorderLayout布局管理器,
    
    边界布局管理器划分为东,西,南,北,中,五个区域,可以将组件添加到这五个区域中


    容器调用Container类的add()方法添加组件时可以设置此组件在边界布局管理器中的区域

    区域的控制可由BorderLayout类中的成员变量来决定,这些成员变量的具体含义如下:
    
    BorderLayout.NORTH         在容器添加组件时,组件置于顶端
    BorderLayout.SOUTH                         ,组件置于底端
    BorderLayout.EAST                          ,组件置于右端
    BorderLayout.WEST                          , 组件置于左端
    BorderLayout.CENTER                                  中间
   

 public class BorderLayoutPosition  extends JFrame{
    //用于Java的版本控制,与反序列化
    private static final long serialVersionUID =1L;
    //创建一个数组用于划分5个区域 
    String[] border ={BorderLayout.CENTER,BorderLayout.NORTH,BorderLayout.SOUTH,BorderLayout.WEST,BorderLayout.EAST};
    //创建一个数组 在其中定义五个按钮 
    String []buttonName ={"center button","north button","south button","west button","east button"};
     //创建一个构造方法
    public BorderLayoutPosition(){
        //设置窗体的标题
        setTitle("这个是边界布局管理理器");
        //获取一个Container容器
        Container c =getContentPane();
        //设置布局方式
        setLayout(new BorderLayout());
        //遍历数组
        for( int i=0;i<border.length;i++){
        c.add(border[i],new JButton(buttonName[i]))    ;
        //设置窗体大小
        setSize(350,200);
        //设置窗体为可见
        setVisible(true);
        //设置窗体关闭方式
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        
        }
        
    }
    
    public static void main(String[] args){
        new BorderLayoutPosition();
    }


}


11.网格布局管理器 GridLayout
  网格布局管理器将容器划分为网格,所以组件可以按列和行进行排列

   在网格布局管理器中每个组件的大小都相同,并且网格中的空格个数由网格的行数和列数决定

   例如一个两行两列的网格能产生4个大小相同的网格

   组件从网格的左上角开始,按照从左到右,从上到下的顺序加入到网格中

  每个组件都会被填满整个网格,改变窗体大小,组件也会随之改变 

 public class GridLayoutPosition extends JFrame{
    /**
     * 
     */
    private static final long serialVersionUID = -2960135100920888650L;
    public GridLayoutPosition(){
        //获取一个Container容器
        Container c = getContentPane();
        //设置布局方式   7行3列
        setLayout(new GridLayout(7,3,5,5));
        //创建20个按钮
        for(int i=0;i<20;i++){
            c.add(new JButton("button"+i));
            //设置窗体大小
            setSize(300,300);
            //设置窗体标题
            setTitle("网格布局管理器");
            setVisible(true);
            //设置关闭方式
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            
        }
        
    }
    public static void main(String[] args) {
        new GridLayoutPosition();
    }

}

常用面板
12.Jpanel面板
    固定的面板
 

 public class JPanetest extends JFrame {
     private static final long serialVersionUID=1L;
     public JPanetest(){
         Container c= getContentPane();
         //将容器设置成2行1列的网格布局
         c.setLayout(new GridLayout(2,1,10,10));
         //初始化JPanel
         JPanel p1 = new JPanel(new GridLayout(1,5,10,10));
         JPanel p2 = new JPanel(new GridLayout(1,2,10,10));
         JPanel p3 = new JPanel(new GridLayout(1,2,10,10));
         JPanel p4 =new JPanel(new GridLayout(2,1,10,10));
         //将按钮添加到容器中
         p1.add(new JButton("1"));
         p1.add(new JButton("1"));
         p1.add(new JButton("2"));
         p1.add(new JButton("3"));
         p2.add(new JButton("4"));
         p2.add(new JButton("5"));
         p4.add(new JButton("6"));
         p4.add(new JButton("7"));
         p3.add(new JButton("8"));
         p3.add(new JButton("9"));
         // 在容器中添加面板
            c.add(p1); // 在容器中添加面板
            c.add(p2);
            c.add(p3);
            c.add(p4);
            setTitle("在这个窗体中使用了面板");
            setSize(420, 200);
            setVisible(true);
            setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
         
     }
     public static void main(String[] args) {
            new JPanetest();
}
}

13.JScrollPane面板
       带滚动条的面板
   JScrollPane是一个容器,只能放置一个组件,并且不可以使用布局管理器   如果需要添加多个组件,需要将多个组件放置在JPanel面板上,然后将JPane面板作为一个整体添加到JScrollPane组件上
   

  public class JScrollPaneTest extends JFrame{
    private static final long serialVersionUID =1L;
    //定义构造函数
    public JScrollPaneTest(){
        //获取一个容器
        Container c = getContentPane();
        //定义一个行为20列为50的文本域
        JTextArea ta = new JTextArea(20,50);
        //将文本域添加到JScrollPane容器中
        JScrollPane sp = new JScrollPane(ta);
        //将面板添加到Container容器中
        c.add(sp);
        //设置Container容器的名字
        setTitle("带滚动条条的文字编译器");
        setSize(200,200);
        
        setVisible(true);
        
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JScrollPaneTest();
    }

}

按钮组件
14.提交按钮组件
  Swing中的提交按钮由JButton对象,其结构方法主要有:
     public JButton()    不带任何文本组件的对象和图标
     public JButton(String text)  指定文字
     public JButton(icon icon)     指定图标
     public JButton(string text,icon icon)  指定图标和文字

 public class JButtonTest extends JFrame {
    private static final long serialVersionUID = 1L;
    //定义一个无参数的JButtonTest方法
    public JButtonTest(){
        //获取图片路径
        URL url = JButtonTest.class.getResource("imageButton.jpg");
        //实例化路径
        Icon icon = new ImageIcon(url);
        //设置布局方式  为网格布局
        setLayout(new GridLayout(3,2,5,5));
        //创建一个容器
        Container c = getContentPane();
        for(int i =0;i<5;i++ ){
            //创建按钮,同时设置按钮文字和图标
            JButton J= new JButton("button"+ i);
            //把按钮添加到容器中
            c.add(J);
            if(i%2==0){
                //设置其中一些按钮不可用
                J.setEnabled(false);//设置按钮可用或不可用  false不可用   true可用
            }
        }
         //实例化一个没有图片文字的按钮 
        JButton jb = new JButton();
        //设置按钮与图片大小相同
      jb.setMaximumSize(new Dimension(90,30));
         //为按钮设置图标
         jb.setIcon(icon);
         
         jb.setHideActionText(true);
         jb.setToolTipText("图片按钮");//设置按钮提示文字
         jb.setBorderPainted(false);//设置按钮边界不显示
         jb.addActionListener(new ActionListener(){//为按钮添加监听事件
            public void actionPerformed(ActionEvent  e)  {
                //弹出确定对话框
                JOptionPane.showMessageDialog(null, "弹出对话框");
            }
             
         });
         //将按钮添加到容器
         c.add(jb);
         setTitle("创建带文字的图片按钮");
         setSize(150,150);
         setVisible(true);
      setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);    
    }
    public static void main(String args[]){
        new JButtonTest();
    }
   
}

15.单选按钮组件
     默认情况下,单选按钮显示为一个圆形的图标,通常情况下该图标旁会放置一些说明性文字

     在应用程序中,一般多个单选按钮放置在按钮组件中,使这些单选按钮表现出某种功能,
     当组件中的某个按钮被选中是,其他按钮自动取消选中

     单选按钮是Swing组件中JRadioButton类的对象该类是JToggleButton的子类
     JToggleButton类是AbstractButton类的子类,所以单选按钮的诸多方法都是AbstractButton类中的方法
                JRadioButton r1 = new JRadioButton();
                JRadioButton r2 = new JRadioButton();
                ButtonGroup group = new ButtonGroup();
                group.add(r1);
                group.add(r2);
16.复选框组件
       复选框在Swing组件中使用十分广泛,它具有一个方块图标,外加一段描述性文字。
  
       每一个复选框都有两个选择状态,选择  不选择  两种状态        复选框由JCheckBox类的对象表示,它继承于AbstractButton类,所以复选框组件的属性设置来源于AbstractButton类
   

 public class CheckBoxTest extends JFrame{
    
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JPanel panel1 = new JPanel();
    private JPanel panel2 = new JPanel();
    private JTextArea jt=new JTextArea(3,10);
    private JCheckBox jc1=new JCheckBox("1");
    private JCheckBox jc2=new JCheckBox("2");
    private JCheckBox jc3=new JCheckBox("3");
    public CheckBoxTest(){
        Container c=getContentPane();
        setSize(200,160);
        setVisible(true);
        setTitle("复选框的使用");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        c.setLayout(new BorderLayout());

        
        c.add(panel1, BorderLayout.NORTH);
        final JScrollPane scrollPane = new JScrollPane(jt);
        panel1.add(scrollPane);


        c.add(panel2, BorderLayout.SOUTH);
        panel2.add(jc1);
        jc1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                if(jc1.isSelected())
                jt.append("复选框1被选中\n");
            }
        });

        panel2.add(jc2);
        jc2.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                if(jc2.isSelected())
                jt.append("复选框2被选中\n");
            }
        });

        panel2.add(jc3);
        jc3.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                if(jc3.isSelected())
                jt.append("复选框3被选中\n");
            }
        });
    }
    
    public static void main(String[] args) {
        new CheckBoxTest();

    }

}

列表组件
17.下拉列表框组件。


     Swing中的下拉列表框不仅可以从中选择项目,同时也提供用户编辑项目中的内容     下拉列表框时一个带条状的显示区,它具有下拉功能,在下拉列表框的右方存在一个倒三角的按钮,当用户点击该按钮,
     下拉列表会以列表形式显示出来

public class JComboBoxModelTest extends JFrame {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    JComboBox<String> jc = new JComboBox<>(new MyComboBox());
    JLabel jl = new JLabel("请选择证件:");
    
    public JComboBoxModelTest() {
        setSize(new Dimension(160, 180));
        setVisible(true);
        setTitle("在窗口中设置下拉列表框");
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        Container cp = getContentPane();
        cp.setLayout(new FlowLayout());
        cp.add(jl);
        cp.add(jc);
    }
    
    public static void main(String[] args) {
        new JComboBoxModelTest();
    }
}

class MyComboBox extends AbstractListModel<String> implements ComboBoxModel<String> {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    String selecteditem = null;
    String[] test = { "身份证", "军人证", "学生证", "工作证" };
    
    public String getElementAt(int index) {
        return test[index];
    }
    
    public int getSize() {
        return test.length;
    }
    
    public void setSelectedItem(Object item) {
        selecteditem = (String) item;
    }
    
    public Object getSelectedItem() {
        return selecteditem;
    }
    
    public int getIndex() {
        for (int i = 0; i < test.length; i++) {
            if (test[i].equals(getSelectedItem()))
                return i;
        }
        return 0;
    }
}


18.列表框组件
public class JListTest extends JFrame {
  

  /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public JListTest() {
        Container cp = getContentPane();
        
        cp.setLayout(null);
        JList<String> jl = new JList<>(new MyListModel());
        JScrollPane js = new JScrollPane(jl);
        js.setBounds(10, 10, 100, 100);
        cp.add(js);
        setTitle("在这个窗体中使用了列表框");
        setSize(200, 150);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    }
    
    public static void main(String args[]) {
        new JListTest();
    }
}

class MyListModel extends AbstractListModel<String> {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String[] contents = { "列表1", "列表2", "列表3", "列表4", "列表5", "列表6" };
    
    public String getElementAt(int x) {
        if (x < contents.length)
            return contents[x++];
        else
            return null;
    }
    
    public int getSize() {
        return contents.length;
    }
}


文本组件
19.文本框组件
         文本框组件用来显示或编辑一个单行文本,在Swing中通过javax.swing.JTextField类对象创建,该类继承         javax.swing.text.JTextComponet类
    
     文本组件的构造方法
public JTextField()
public JTextField(String text)
public JTextField(int fieldwidth)
public JTextField(String text,int fieldwidth)
public JTextField(String Document docModel,String text,int fieldwidth)
   定义JTextField组件时,可以在初始化文本框时设置文本框的默认文字,文本框长度等

public class JTextFieldTest extends JFrame{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public JTextFieldTest(){
        setSize(250,100);
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        Container cp=getContentPane();
        getContentPane().setLayout(new FlowLayout());
        final JTextField jt=new JTextField("aaa",20);
        final JButton jb=new JButton("清除");
        cp.add(jt);
        cp.add(jb);
        jt.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {
                // TODO 自动生成方法存根
                jt.setText("触发事件");
            }
        });
        jb.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {
                jt.setText("");
                jt.requestFocus();
            }
        });    
        setVisible(true);
    }
    public static void main(String[] args) {
        new JTextFieldTest();
    }
}

20.密码框组件
     密码框组件与文本框组件定义语法基本相同,唯一不同是密码使用输入的字符串以某种字符进行加密。

     密码框对象是通过javax.swing.JPasswordField类创建

    JPasswordField类的构造方法与JTextField类的构造方法非常相似

     构造方法
public JPasswordField()
public JPasswordField(String text)
public  JPasswordField(int fieldwidth)
public  JPasswordField(String text,int fieldwidth)
public  JPasswordField(Document docModel,String text,int fieldWidth)

21.文本域组件
   Swing中任何一个文本区域都是JTextArea类型的对象,JTextArea常用的构造方法

  public JTextArea();
  public JTextArea(String text);
  public JTextArea(int rows,int columns)
  public JTextArea(Document doc)
  public JTextArea(Document doc,String Text ,int rows,int columns)
 在上述的构造方法中,可以在初始化文本是提供默认文本以及文本域的长与宽
  

常用事件监听器
22.监听事件简介
   在swing模型中由三个分离的对象完成对事件的处理,事件源,事件,监听程序


   事件源触发一个事件,他被一个或多个“监听器接收”

   事件监听器的实质是实现“特定类型的监听器接口”的类对象
    
   几乎所有的事件都可以用对象来表示

   事件源(按钮)会在用户做出相应动作(按下按钮)时产生事件对象

   例如动作事件对应ActionEvent类对象,通过编写一个事件监听器类来实现相应的接口,最后实现接口中的方法

   所有的事件源都具有addXXXListener()和removeXXXListener()方法(其中XXX方法表示事件监听类型)
23.动作事件监听器
    动作事件(ActionEvent)监听器是Swing中比较常见的事件监听器,很多组件动作都会使用它监听,如按钮被按下
24.焦点事件监听器
焦点事件FocusEvent 监听器在实际项目开发中应用也比较广泛,
如将光标焦点离开一个文本框是需要弹出一个对话框,或者将焦点返回给该文本框等

public class focusEventTest extends JFrame {
  private static final long serialVersionUID =1L;
  public focusEventTest(){
      setSize(250,100);
      
      setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      
      Container  cp = getContentPane();
      cp.setLayout(new FlowLayout());
      
      final JLabel jlabel = new JLabel();
      getContentPane().add(jlabel);
      
      JTextField jt = new JTextField("清单击其他文本框",10);
      JTextField jt2 = new JTextField("清单击我",10);
      
      cp.add(jt);
      cp.add(jt2);
      jt.addFocusListener(new FocusListener(){
   //组件获取焦点的调用方法
        @Override
        public void focusGained(FocusEvent arg0) {
            // TODO 自动生成的方法存根
            
        }
         //组件失去焦点的调用方法
        @Override
        public void focusLost(FocusEvent arg0) {
            // TODO 自动生成的方法存根
            JOptionPane.showMessageDialog(null,"文本失去焦点");
            
        }
          
      });
      setVisible(true);
  }
  public static void main(String[] args) {
    new focusEventTest();
}
}

当初学swing的时候,貌似好像记得老师说不做游戏开发稍作了解就行,现在都还给老师了,啥也不记得了,

 

整理之前的Java学习笔记,看看这三年学了些什么,毕业了,要找工作了感觉啥也没学清楚,顺便重温Java,在向后面学

猜你喜欢

转载自blog.csdn.net/RONG_YAO/article/details/89320482
今日推荐