需求说明:
使用JTable组件显现人员信息列表
实现思路:
- 创建一个JTable对象。
- 创建一个JScrollPane对象(显示横向和纵向滚动条)。
- 将表格添加到滚动面板。
- 将滚动面板添加到JFrame的内容窗格中
实现代码:
import java.awt.BorderLayout; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ScrollPaneConstants; public class Test extends JFrame { private JTable jTable; public void init(){ BorderLayout bl=new BorderLayout(); this.setLayout(bl); //定义表格的表头信息 String[] heads={"姓名","年龄","电话"}; //定义表格中显示的信息 Object[][] data={ {"丘处机","33","13870943994"},{"徐世绩","28","18062795496"}, {"杜如晦","29","18600158798"},{"方孟傲","35","13836188388"}, {"杜小月","19","15248779908"},{"余国荔","25","13238112922"}, {"罗士信","29","15927271222"},{"林徽因","34","15108235082"}, {"陈永华","39","13296693349"},{"萧漩语","34","15847006955"}}; //创建JTable对象 jTable=new JTable(data,heads); int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; //创建滚动条面板对象,将JTable加入滚动条中,显示横向和垂直滚动条 JScrollPane jsp=new JScrollPane(jTable,v,h); //将滚动面板添加至JFrame中 this.add(jsp); this.setSize(450, 200); this.setVisible(true); } public static void main(String[] args) { Test test = new Test(); test.init(); } }