JTable 实例
1 import java.awt.Dimension; 2 import java.awt.GridBagConstraints; 3 import java.awt.GridBagLayout; 4 5 import javax.swing.Box; 6 import javax.swing.BoxLayout; 7 import javax.swing.JFrame; 8 import javax.swing.JPanel; 9 import javax.swing.JScrollPane; 10 import javax.swing.JTable; 11 import javax.swing.table.DefaultTableModel; 12 13 public class main { 14 static JPanel middlePanel; 15 16 static void paint() { 17 middlePanel = new JPanel(); 18 String[] columnName = { "股票名字", "今日开盘价", "昨日收盘价", "当前价格", "今日最高价","今日最低价", "竞买价", 19 "竞卖价", "成交的股票数", "成交金额", "买一申请", "买一报价", "买二申请", "买二报价", "买三申请", 20 "买三报价","买四申请", "买四报价", "买五申请","买五报价","卖一申请", "卖一报价", "卖二申请", "卖二报价", 21 "卖三申请", "卖三报价","卖四申请", "卖四报价","卖五申请", "卖五报价", "日期", "时间"}; 22 String[][] rowData = { {"大秦铁路","27.55","27.25","26.91", "27.55", "26.20"," 26.91", "26.92","22114263" 23 ,"589824680","4695","26.91","57590","26.90","14700","26.89","14300","26.88","15100","26.87","3100","26.92","8900","26.93", 24 "14230","26.94","25150","26.95","15220","26.96","2008-01-11","15:05:32"}, 25 }; 26 27 // 创建表格 28 JTable table = new JTable(new DefaultTableModel(rowData, columnName)); 29 // 创建包含表格的滚动窗格 30 JScrollPane scrollPane = new JScrollPane(table); 31 scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); 32 // 定义 topPanel 的布局为 BoxLayout,BoxLayout 为垂直排列 33 middlePanel.setLayout(new BoxLayout(middlePanel, BoxLayout.Y_AXIS)); 34 // 先加入一个不可见的 Strut,从而使 topPanel 对顶部留出一定的空间 35 middlePanel.add(Box.createVerticalStrut(10)); 36 // 加入包含表格的滚动窗格 37 middlePanel.add(scrollPane); 38 } 39 40 public static void main(String[] args) { 41 paint(); 42 43 JPanel panelContainer = new JPanel(); 44 panelContainer.setLayout(new GridBagLayout()); 45 46 GridBagConstraints c2 = new GridBagConstraints(); 47 c2.gridx = 0; 48 c2.gridy = 10; 49 c2.weightx = 0.4; 50 c2.weighty = 0; 51 c2.fill = GridBagConstraints.HORIZONTAL ; 52 // 加入 middlePanel 53 panelContainer.add(middlePanel,c2); 54 55 56 JFrame frame = new JFrame("Table 演示"); 57 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); 58 panelContainer.setOpaque(true); 59 frame.setSize(new Dimension(2000, 600)); 60 frame.setContentPane(panelContainer); 61 frame.setVisible(true); 62 } 63 64 }