本题目来自于《java程序设计--基础篇》的第12章。编写一个程序,实现在四个标签上显示四行文本,在每个标签上添加一条边界。
思路分析:定义自己的类,这个类继承自JFrame,然后类的成员属性有:一个JPanel,四个JLabel.他们其实状态指向的地址都为空,在类的构造方法中再new出来。这四个标签都要添加到Panel里面!
import java.awt.*;
import javax.swing.*;
public class Ex12_5 extends JFrame {
//定义一个Panle和四个标签
JPanel jpanel = null;
JLabel jlb1 = null;
JLabel jlb2 = null;
JLabel jlb3 = null;
JLabel jlb4 = null;
public Ex12_5() {
//创建对象,
jpanel = new JPanel();
jlb1 = new JLabel("Department of Computer Science");
jlb2 = new JLabel("School of Computing");
jlb3 = new JLabel("Armstrong Atlantic State University");
jlb4 = new JLabel("Tel:(912)921-6440");
//让每个标签都显示出边框出来
jlb1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
jlb2.setBorder(BorderFactory.createLineBorder(Color.BLACK));
jlb3.setBorder(BorderFactory.createLineBorder(Color.BLACK));
jlb4.setBorder(BorderFactory.createLineBorder(Color.BLACK));
jpanel.setLayout(new GridLayout(4, 1));
//将标签添加到panel
jpanel.add(jlb1);
jpanel.add(jlb2);
jpanel.add(jlb3);
jpanel.add(jlb4);
//将panel添加到frame里面去
this.add(jpanel);
}
public static void main(String[] args) {
JFrame frame = new Ex12_5();
frame.setTitle("显示标签");
frame.setSize(250, 200);
frame.setLocation(500, 200);
frame.setVisible(true);
}
}
运行效果如图: