@XQF
2016-08-11T21:34:36.000000Z
字数 2743
阅读 1153
J2SE核心开发-----实验楼
图形用户界面(Graphical User Interface,简称GUI,又称图形用户接口)是指采用图形方式显示的计算机操作用户界面
Swing便是Java中的一个GUI,是基于模型-视图-控制器
设计模式来进行设计的,通过事件
对用户的输入进行反应。即使是最简单的一个按钮,也是包含了他的外观(什么颜色,多大),内容(按钮上显示什么文字等)以及行为(对于用户按下时的反应)这三个要素。
Swing是在抽象窗口工具箱(AWT)的架构上发展而来的一个用户界面库,整个可视组件库的基础构造块是JCompontent
,它是所有组件的父类,为所有组件提供了绘制的基础架构。换言之,所有Swing组件都是由它派生而来。
基于Swing制作的Java程序就是由一个一个的组件构成的,开发的过程有点像组装积木。
JFrame类就是一个容器,允许把其他组件添加到它里面,把他们组织起来,并呈现给用户。JFrame在大多数的操作系统中是以窗口的形式注册的。这意味着可以对其进行最小化和最大化,甚至移动这个窗口
JFrame包含的一些方法:
代码演示:
public class MySwingWindow extends JFrame {
public MySwingWindow() {
// TODO Auto-generated constructor stub
// 在窗体的构造方法中设置窗体的各项属性
super();
// 使用super()来引用父类的成分,用this来引用当前对象
this.setSize(1000, 1000);//设置窗体大小
this.getContentPane().setLayout(null);//设置布局
this.setTitle("My first Swing Window");//设置窗体标题
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// 声明一个窗体对象
MySwingWindow mySwingWindow = new MySwingWindow();
mySwingWindow.setVisible(true);//设置对象可见
}
}
有了容器,我们就可以在上面添加各种各样的控件。Swing的控件数量是巨大的,但是他们的使用方法是相通的。
首先添加最基础的组件——————标签JLabel.JLabel可以用作文本描述和图片描述,常用的方法如下:
实例代码
public class MySwingWindow extends JFrame {
private JLabel myLabel;
private JTextField myTextField;
private JButton myButton;
public MySwingWindow() {
// TODO Auto-generated constructor stub
// 在窗体的构造方法中设置窗体的各项属性
super();
// 使用super()来引用父类的成分,用this来引用当前对象
this.setSize(400, 300);// 设置窗体大小
this.getContentPane().setLayout(null);// 设置布局
this.setTitle("My first Swing Window");// 设置窗体标题
this.add(getJButton(), null);
this.add(getJLabel(), null);
this.add(getJTextField(), null);
// this.add(myButton, null);
// this.add(myLabel, null);
// this.add(myTextField, null);
// 这种写法很直接为什么错了,因为我们添加进去的控件居然是null,没有进行任何的实例化,不带任何属性,系统应该是无法处理的
}
private JLabel getJLabel() {
if (myLabel == null) {
myLabel = new JLabel();
myLabel.setBounds(5, 10, 250, 30);
myLabel.setText("Hello !Welcome to my home");
}
return myLabel;
}
private JTextField getJTextField() {
if (myTextField == null) {
myTextField = new JTextField();
myTextField.setBounds(5, 45, 200, 30);
myTextField.setText("XQF");
}
return myTextField;
}
private JButton getJButton() {
if (myButton == null) {
myButton = new JButton();
myButton.setBounds(5, 80, 100, 40);
myButton.setText("Click me!");
//设置监听事件,好玩,要是学安卓之前学过这个的话,应该是很快就上手吧
myButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
myLabel.setForeground(Color.RED);
myTextField.setBackground(Color.BLUE);
}
});
}
return myButton;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// 声明一个窗体对象
MySwingWindow mySwingWindow = new MySwingWindow();
mySwingWindow.setVisible(true);// 设置对象可见
}
}