• 怎么在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);
    

      

  • 相关阅读:
    Unrecognized attribute 'targetFramework'.错误解决
    [译]Razor内幕之模板
    [译]Razor内幕之解析
    Java下载中文乱码问题解决方法
    获取矩形中心点与矩形外某点连线和矩形交点的算法
    做产品开发的感想
    [译]Razor内幕之表达式
    Could not find the main class. Program will exit.
    基于SAML的单点登录.NET代理端实现方案
    Linux内核虚拟内存的管理结构说明
  • 原文地址:https://www.cnblogs.com/wwssgg/p/14580463.html
Copyright © 2020-2023  润新知