package swing; import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.Vector; import javax.swing.event.*; import javax.swing.table.DefaultTableCellRenderer; public class table extends JFrame{ Container container; JTable table; table(){ container=this.getContentPane(); Vector vector=new Vector();//存放学生所有信息 Vector vector1=new Vector();//存放第一行内容 Vector vector2=new Vector();//存放第二行内容 vector1.add("张三"); vector1.add("23"); vector1.add("网络"); vector.add(vector1); vector2.add("李四"); vector2.add("21"); vector2.add("安全"); vector.add(vector2); Vector vc=new Vector(); vc.add("姓名"); vc.add("年龄"); vc.add("专业"); table=new JTable(vector,vc); table.setEnabled(false);//设置表格不可编辑 table.setPreferredScrollableViewportSize(new Dimension(0,120)); DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中 tcr.setHorizontalAlignment(SwingConstants.CENTER); // tcr.setHorizontalAlignment(JLabel.CENTER);这句和上句作用一样 table.setDefaultRenderer(Object.class, tcr); JScrollPane jsp=new JScrollPane(); jsp.setViewportView(table);//放置到滚动面板 jsp.setBorder(BorderFactory.createTitledBorder("学生信息"));//提示信息 container.add(BorderLayout.CENTER,jsp); validate();//刷新窗口 this.setTitle("表格练习"); this.setSize(600,450); this.show(); } public static void main(String []args) { new table(); } }
运行结果: