初学java之常用组件

时间:2022-05-05
本文章向大家介绍初学java之常用组件,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
 1  
 2   import javax.swing.*;
 3 
 4 import java.awt.*;
 5   class Win  extends JFrame
 6   {
 7       JTextField mytext;   // 设置一个文本区
 8       JButton mybutton;
 9       JCheckBox mycheckBox[];
10       JRadioButton myradio[];
11       ButtonGroup group;    //为一组按钮创建相坼的功能
12       JComboBox myComboBox;
13       JTextArea myText;
14       public Win(){} ;     //设置一个构造函数
15       public Win(String str ,int x,int y,int h,int w)     //设置一个自定义的构造函数
16       {
17           setinit(str);
18           setBounds(x,y,h,w);    //对其进行位置大小的更改
19           setVisible(true);      //设置其是否可见
20           setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //退出并关闭窗口
21       } 
22       void setinit(String str)
23       {
24            setTitle(str);    //跟文本加一个标题
25           //设置一个布局
26           setLayout(new FlowLayout(FlowLayout.LEFT));   //设置一个布局FlowLayout流布局,向左对齐
27           add(new Label("文本框"));   //添加一个label
28           mytext = new JTextField(10);
29           add(mytext);
30           add(new Label("按钮"));
31           mybutton = new JButton("确定");
32           add(mybutton);
33           mycheckBox = new JCheckBox [3]; //运用数组实现吧!
34           String title[] ={"音乐","旅游","篮球"};
35           add( new Label("选择框") );
36           for( int i=0 ; i<3 ; i++ )
37           {
38              mycheckBox[i] = new JCheckBox("喜欢"+title[i]);
39              add(mycheckBox[i]);
40           }
41           add( new Label("单选按钮"));
42           myradio =new JRadioButton [2];
43           group = new ButtonGroup();
44           String mystr[] = {"男","女"};
45           for(int i=0;i<2;i++)
46           {
47            myradio[i] = new JRadioButton( mystr[i] );
48            group.add(myradio[i]);
49            add(myradio[i]);
50           }
51           add( new Label("下拉列表"));
52           myComboBox = new JComboBox();  //创建一个下拉菜单
53           String substr[] ={"音乐天地","武术天地","象棋乐园"};
54           for(int i=0 ; i<3 ;i++)
55             myComboBox.addItem(substr[i]);
56           add(myComboBox);
57           add( new Label("文本区:"));
58           myText = new JTextArea(6,12);  
59           add( new JScrollPane(myText));
60       }
61   }
62  
63   public class gong
64   {
65       public static void main(String args[])
66       {
67         Win mywin = new Win("Demo",100,100,330,290);  
68       }
69   }