日期:2014-05-20 浏览次数:20640 次
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; public class TableDemo extends JFrame { private String[] columnNames = {"姓 名", "操作"};//记录表格的列名 JTable table; public TableDemo() { Container cp = this.getContentPane(); JPanel panel = new JPanel(); table = this.createJTable(columnNames); table.getColumnModel().getColumn(1).setCellRenderer(new PanelTableCellRender());//让第二列显示一个特定的面板 DefaultTableModel model = (DefaultTableModel) this.table.getModel(); model.addRow(new Object[] {"Zidane", new PanelDemo()}); model.addRow(new Object[] {"Henry", new PanelDemo()}); JScrollPane scrollPane = new JScrollPane(table); panel.setSize(300, 200); panel.add(scrollPane); cp.add(panel); setVisible(true); setBounds(300, 200, 500, 300); } /** * 新建一个JTable对象 * @param list * @param columnNames * @return */ public JTable createJTable(String columnNames[]) { DefaultTableModel model = new DefaultTableModel(); for(int i = 0; i < columnNames.length; i++) { model.addColumn(columnNames[i]); } JTable temporaryTable = new JTable(model); temporaryTable.setFont(new Font("微软雅黑", Font.ROMAN_BASELINE, 23)); temporaryTable.getTableHeader().setBackground(Color.MAGENTA); temporaryTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 20)); temporaryTable.setRowHeight(75); return temporaryTable; } /** * 该类实现了表格中“操作”那一列单元格的绘制 * @author lxb 2011-08-24 */ class PanelTableCellRender extends PanelDemo implements TableCellRenderer { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (hasFocus) setBorder(UIManager.getBorder("Table.focusCellHighlightBorder")); else setBorder(null); return this; } } /** * @param args */ public static void main(String[] args) { TableDemo demo = new TableDemo(); } }
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PanelDemo extends JPanel implements ActionListener { JButton button; JLabel viewLabel; public PanelDemo() { button = new JButton("编辑"); button.setFont(new Font("微软雅黑", Font.CENTER_BASELINE, 18)); button.addActionListener(this); viewLabel = new JLabel(); viewLabel.setFont(new Font("微软雅黑", Font.CENTER_BASELINE, 18)); viewLabel.setSize(80, 40); this.add(button); this.add(viewLabel); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == button) { button.setBackground(Color.magenta); viewLabel.setText("编辑!"); } } }