zoukankan      html  css  js  c++  java
  • 怎么在JTable表格中把列做成单选框

    1、重写一个单元格渲染类

    public class CheckBoxRenderer extends JCheckBox implements TableCellRenderer {
    		private static final long serialVersionUID = 1L;
    		Border border = new EmptyBorder(1, 2, 1, 2);
    		public CheckBoxRenderer() {
    			super();
    			setOpaque(true);
    			setHorizontalAlignment(SwingConstants.CENTER);
    			setBackground(Color.WHITE);
    		}
    		public CheckBoxRenderer(String text, boolean selected) {
    			super(text, selected);
    			setOpaque(true);
    			setHorizontalAlignment(SwingConstants.CENTER);
    			setBackground(Color.WHITE);
    		}
    		@Override
    		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
    				int row, int column) {
    			if (value instanceof Boolean) {
    				setSelected(((Boolean) value).booleanValue());
    			}
    			return this;
    		}
    	}
    

    2、重写单元格编辑类

    class CheckBoxCellEditor extends AbstractCellEditor implements TableCellEditor {
    		private static final long serialVersionUID = 1L;
    		protected JCheckBox checkBox;
    		public CheckBoxCellEditor() {
    			checkBox = new JCheckBox();
    			checkBox.setHorizontalAlignment(SwingConstants.CENTER);
    			checkBox.addActionListener(new ActionListener() {
    				@Override
    				public void actionPerformed(ActionEvent e) {
    
    				}
    			});
    		}
    		@Override
    		public Object getCellEditorValue() {
    			return Boolean.valueOf(checkBox.isSelected());
    		}
    		@Override
    		public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row,
    				int column) {
    			if (value != null) {
    				checkBox.setSelected(((Boolean) value).booleanValue());
    			}
    			return checkBox;
    		}
    	}
    

    3、给列添加渲染类和编辑类

    CheckBoxRenderer checkBoxRenderer  = new CheckBoxRenderer();
    CheckBoxCellEditor checkBoxCellEditor = new CheckBoxCellEditor();
    table.getColumnModel().getColumn(5).setCellRenderer(checkBoxRenderer);
    table.getColumnModel().getColumn(5).setCellEditor(checkBoxCellEditor);
    

      

  • 相关阅读:
    pythonchallenge(二)
    pythonchallenge(三)
    pythonchallenge(一)
    [译]Python编写虚拟解释器
    [译]用R语言做挖掘数据《七》
    [译]用R语言做挖掘数据《六》
    [译]用R语言做挖掘数据《五》
    编译安装php容易出现的问题以及解决办法
    关于nodejs模块安装后找不到包解决办法
    gulp的入门
  • 原文地址:https://www.cnblogs.com/wwssgg/p/14580463.html
Copyright © 2011-2022 走看看