图形界面
第一步. 一定要继承Jframe
第二步.在构造函数里写实现代码
第三步. 要在main()方法中生成Jframe对象:
JframeTestft=new JframeTest();
注:
1. 图形变量一般定义为全局变量
String定义为全局变量时不用写null
String h;
String定义为局部变量时要写null
String h=null;
2.setSize(600,500); //设置宽,高
setVisible(true); //可见
一般写在构造函数的尾部
且两者的顺序不能颠倒
3.设置主窗体在屏幕上显示的位置
setLocation(200, 200);
4. 在屏幕中间显示
double width= Toolkit.getDefaultToolkit().getScreenSize().getWidth();
double height = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
setLocation((int)(width-this.getWidth())/2,(int)(height-this.getHeight())/2);
5. 设置关闭按钮可用:
setDefaultCloseOperation(EXIT_ON_CLOSE);
不设置的话è窗口虽然关闭,但程序依然在后台运行
6.设置标题的内容:
setTitle("第一个界面");
7. 每创建完一个标签之类的,要使用add添加
例如:JLabel lab_name;
lab_name=new JLabel("姓名:");
//把控件加入窗体
add(lab_name);
标签Jlabel
JLabel lab_name;
//生成控件对象
lab_name=new JLabel("姓名:");
//分别设置控件距左边距离、距上边的距离、以及控件的宽、高
lab_name.setBounds(30,30,80,30);
//分别设置字体,粗体,字号
lab_name.setFont(new Font("宋体",Font.BOLD,22));
//把控件加入窗体
add(lab_name);
文本框JTextField
JTextField tf;
tf=new JTextField();
tf.setBounds(120,30,120,30);
add(tf);
文本JtextArea
1. 没有加动条时:
JTextAreata;
ta=new JTextArea();
ta.setLineWrap(true); //自动换行
à①ta.setBounds(120,80,120,90);
à②add(ta);
2. 加入滚动条时:
JTextArea ta;
JScrollPane sp;
ta=new JTextArea();
ta.setLineWrap(true); //自动换行
//加入滚动条后, à①②语句不用再写了
sp=new JScrollPane(ta);
sp.setBounds(120,80,120,90);
add(sp);
单选框JradioButton
1. 普通加入主窗体
JRadioButtonrb_man;
rb_man=new JRadioButton("男");
rb_man.setSelected(true); //设置默认选择男的
rb_man.setBounds(120,180,120,40);
JRadioButton rb_female=new JRadioButton("女");
rb_female.setBounds(140,180,120,40);
add(rb_man);
★add(rb_female);
2.使用面板加入主窗体
JPanel p1;
p1=new JPanel();//创建面板对象
JRadioButton rb_man;
rb_man=new JRadioButton("男");
//设置面板的边框,颜色为蓝色
p1.setBorder(BorderFactory.createLineBorder(Color.blue));
p1.add(rb_man); //把控件加入面板
p1.setBounds(120,180,120,40); //设置面板的位置以及面板的宽高
★add(p1); //把面板加入主窗体
注:使单选框互斥,直接加在★后面
ButtonGroup bg;
bg=new ButtonGroup();
bg.add(rb_female);
bg.add(rb_man);
下拉列表JcomboBox
JComboBox cb_xueli;
cb_xueli.addItem("初中");
cb_xueli.addItem("高中");
cb_xueli.addItem("大学");
cb_xueli.setBounds(420,30,120,30);
add(cb_xueli);
多选框JcheckBox
JPanel p2;
JCheckBox cb_sing;
JCheckBox cb_dance;
cb_sing=new JCheckBox("唱歌");
cb_dance=new JCheckBox("跳舞");
p2=new JPanel();
p2.setBorder(BorderFactory.createLineBorder(Color.blue));
p2.add(cb_sing);
p2.add(cb_dance);
p2.setBounds(420,80,80,110);
add(p2);
按钮Jbutton
JButton btn_add;
btn_add=new JButton("添加");
btn_add.setBounds(200,300,80,30);
add(btn_add);
接口可以new必须立即实现方法