日期:2014-05-20 浏览次数:20724 次
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.table.*; public class JTableDemo2 extends JFrame { private JPanel contentPane; private JTextField textField; private JTable table; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { JTableDemo2 frame = new JTableDemo2(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public JTableDemo2() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel label = new JLabel("\u5F53\u524D\u70B9\u51FB\u7684\u5185\u5BB9\u4E3A\uFF1A"); label.setBounds(70, 216, 126, 15); contentPane.add(label); textField = new JTextField(); textField.setBounds(222, 213, 66, 21); contentPane.add(textField); textField.setColumns(10); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(60, 26, 271, 166); contentPane.add(scrollPane); table = new JTable(); table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { Object o=table.getValueAt(table.getSelectedRow(), table.getSelectedColumn()); textField.setText(o.toString()); } }); Object[][] cellData={ {new String("云长"),new Integer(61), new Integer(62), new Integer(63)}, {new String("翼德"),new Integer(64), new Integer(65), new Integer(66)}, {new String("子龙"),new Integer(67), new Integer(68), new Integer(69)}, {new String("汉升"),new Integer(70), new Integer(71), new Integer(72)}, {new String("孟起"),new Integer(73), new Integer(74), new Integer(75)}, {new String("凯哥"),new Integer(76), new Integer(77), new Integer(78)}, }; String[] headers= { "姓名","\u8BED\u6587", "\u6570\u5B66", "\u82F1\u8BED" }; scrollPane.setViewportView(table); final DefaultTableModel model = new DefaultTableModel(cellData, headers) ; table.setModel(model); JButton btnNewButton = new JButton("\u589E\u52A0\u5217"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { model.addRow(new Object[]{"什么名","语文分","数学分","英语分"});//里面的东西你可以动态怎么获取赋值即可。 } }); btnNewButton.setBounds(60, 0, 95, 25); contentPane.add(btnNewButton); JButton btnNewButton_1 = new JButton("\u5220\u9664\u5217"); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] selRowIndexs=table.getSelectedRows();// 用户所选行的序列 for(int i=0;i<selRowIndexs.length;i++){ model.removeRow(table.getSelectedRow()); } } }); btnNewButton_1.setBounds(165, 0, 95, 25); contentPane.add(btnNewButton_1); } }