如何将 JRadioButton 添加到 JTable 的两列并对其进行 ButtonGroup。

2023-12-10

我想要一个JTable它由 2 列组成(有RadioButton) 活动和非活动,这样如果活动列是Selected然后 Inactive RadioButton 得到Unselected反之亦然意味着在单行中只能从 2 个单选按钮中选择 1 个单选按钮。单选按钮的代码如下。我无法为这两列添加 2 个按钮组。

 public class NewJFrame extends javax.swing.JFrame {
    DefaultTableModel dt;
    public JRadioButton radioButton=new JRadioButton();


       public class RadioButtonCellEditorRenderer extends AbstractCellEditor implements TableCellRenderer, TableCellEditor, ActionListener {



            public RadioButtonCellEditorRenderer() {

                radioButton.addActionListener(this);
                radioButton.setOpaque(false);
            }

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                radioButton.setSelected(Boolean.TRUE.equals(value));
                return radioButton;
            }

            @Override
            public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
                radioButton.setSelected(Boolean.TRUE.equals(value));
                return radioButton;
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                stopCellEditing();
            }

            @Override
            public Object getCellEditorValue() {
                return radioButton.isSelected();
            }

        }

        public NewJFrame() {
            initComponents();

            for(int i=0;i <10;i++)
            {


                  //ButtonGroup bp[i]= new ButtonGroup();
            dt.addRow(new Object[]{null,false,false});


            }
           // jTable1.setValueAt(false, 5, 1);

        }

        /**
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {

            buttonGroup1 = new javax.swing.ButtonGroup();
            jScrollPane4 = new javax.swing.JScrollPane();
            jTable1 = new javax.swing.JTable();

            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

            dt= (new javax.swing.table.DefaultTableModel(new Object[][]{{null,null,null}},new String [] {"Name","Select", "Unselect"})
                {
                    Class[] types = new Class [] {java.lang.Integer.class,java.lang.String.class, java.lang.String.class};

                    public Class getColumnClass(int columnIndex) {
                        return types [columnIndex];
                    }
                    public boolean isCellEditable(int r,int c)
                    {

                        return true;
                    }
                });

                //JTextField textBox= new JTextField();
                jTable1.setModel(dt);
                TableColumn column = jTable1.getColumnModel().getColumn(1);
                column.setCellEditor(new RadioButtonCellEditorRenderer());
                column.setCellRenderer(new RadioButtonCellEditorRenderer());
                TableColumn column1 = jTable1.getColumnModel().getColumn(2);
                column1.setCellEditor(new RadioButtonCellEditorRenderer());
                column1.setCellRenderer(new RadioButtonCellEditorRenderer());
                jTable1.getTableHeader().setReorderingAllowed(false);
                jScrollPane4.setViewportView(jTable1);

                javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
                getContentPane().setLayout(layout);
                layout.setHorizontalGroup(
                    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(13, Short.MAX_VALUE))
                );
                layout.setVerticalGroup(
                    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(29, Short.MAX_VALUE))
                );

                pack();
            }// </editor-fold>

        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>

            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
                }
            });
        }

这是我的示例代码,我修改了它并放置了另一个JRadioButton在第 2 列中满足您的要求。第一列和第二列都像 ButtonGroup 一样按行分组。

Output:

enter image description here

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;

 /** Dialog class **/
public class DisplayTable extends JDialog {
   public void initialize() {

   SourceTableModel stm = new SourceTableModel();
   JTable sourceTable = new JTable(stm);

   sourceTable.getColumnModel().getColumn(0).setCellRenderer(new RadioButtonRenderer());
   sourceTable.getColumnModel().getColumn(0).setCellEditor(new RadioButtonEditor(new JCheckBox()));

sourceTable.getColumnModel().getColumn(1).setCellRenderer(new RadioButtonRenderer());
sourceTable.getColumnModel().getColumn(1).setCellEditor(new RadioButtonEditor(new JCheckBox()));

JPanel panel = new JPanel();
panel.add(new JScrollPane(sourceTable));
add(panel, BorderLayout.CENTER);

JPanel btnPanel = new JPanel();
JButton btnApply = new JButton("Close");
btnPanel.add(btnApply);

btnApply.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        System.exit(0);
    }
});

add(btnPanel, BorderLayout.SOUTH);

setTitle("Radio Button in JTable Example");
setModal(true);
pack();
setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new DisplayTable().initialize();
        }
    });
}

}

/** Table Model class for the Table **/
class SourceTableModel extends AbstractTableModel  {

private static final long serialVersionUID = 1L;

private List<SourceModel> sourceList = new ArrayList<SourceModel>(); 
private String[] columnNamesList = {"Active", "InActive", "One", "Two"};

public SourceTableModel() {
    this.sourceList = getSourceDOList();
}

@Override
public String getColumnName(int column) {
    return columnNamesList[column];
}

@Override
public int getRowCount() {
    return sourceList.size();
}

@Override
public int getColumnCount() {
    return columnNamesList.length;
}

@Override
public Class<?> getColumnClass(int columnIndex) {
    return ((columnIndex == 0 || columnIndex == 1) ? Boolean.class : String.class);
}

@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
    return ((columnIndex == 0 || columnIndex == 1) ? true : false);
}

/**
     **Important:** Here when ever user clicks on the column one then other column values should be made false. Similarly vice-versa is also true.
**/
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    SourceModel model = (SourceModel) sourceList.get(rowIndex);
    switch (columnIndex) {
case 0: 
        model.setSelect(true);
        model.setInActive(false);
        fireTableRowsUpdated(0, getRowCount() - 1);
        break;
case 1:
        model.setSelect(false);
        model.setInActive(true);
        fireTableRowsUpdated(0, getRowCount() - 1);
        break;
case 2: 
    model.setFactory((String) aValue);
    break;
case 3: 
    model.setSupplier((String) aValue);
    break;
}
fireTableCellUpdated(rowIndex, columnIndex);
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
SourceModel source = sourceList.get(rowIndex);
//SourceModel source = getSourceDOList().get(rowIndex);
switch(columnIndex){
case 0:
    return source.isSelect();
case 1:
    return source.isInActive();    
case 2:
    return source.getFactory();
case 3:
    return source.getSupplier();
default:
    return null;
}
}

/**
 * List for populating the table.
 * @return list of sourceDO's.
 */
private List<SourceModel> getSourceDOList() {
   List<SourceModel> tempSourceList = new ArrayList<SourceModel>();
   for (int index = 0; index < 5; index++) {

    SourceModel source = new SourceModel();
    source.setSelect(false);
    source.setInActive(false);
    source.setFactory("One " + index);
    source.setSupplier("Two " + index);

    tempSourceList.add(source);
}
return tempSourceList;
}
}

/** Class that is holding the model for each row **/
class SourceModel {

private boolean active;
private boolean inActive;
private String factory;
private String supplier;

public SourceModel() {
    // No Code;
}

public SourceModel(boolean select, boolean inActive, String factory, String supplier) {
    super();
    this.active = select;
    this.inActive = inActive;
    this.factory = factory;
    this.supplier = supplier;
}

public boolean isSelect() {
    return active;
}

public void setSelect(boolean select) {
    this.active = select;
}

public String getFactory() {
    return factory;
}

public boolean isInActive() {
    return inActive;
}

public void setInActive(boolean inActive) {
    this.inActive = inActive;
}

public void setFactory(String factory) {
    this.factory = factory;
}

public String getSupplier() {
    return supplier;
}

public void setSupplier(String supplier) {
    this.supplier = supplier;
}
}

/** Renderer class for JRadioButton **/
class RadioButtonRenderer implements TableCellRenderer {

    public JRadioButton btn = new JRadioButton();
    public Component getTableCellRendererComponent(JTable table, Object value,
      boolean isSelected, boolean hasFocus, int row, int column) {

      if (value == null) 
          return null;
      btn.setSelected((Boolean) value);
      return btn;
  }
}

/** Editor class for JRadioButton **/
class RadioButtonEditor extends DefaultCellEditor implements ItemListener {

public JRadioButton btn = new JRadioButton();

public RadioButtonEditor(JCheckBox checkBox) {
    super(checkBox);
}

public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {

    if (value == null) 
        return null;

    btn.addItemListener(this);

    if (((Boolean) value).booleanValue())
        btn.setSelected(true);
    else
        btn.setSelected(false);

    return btn;
}

public Object getCellEditorValue() {
    if(btn.isSelected() == true)
        return new Boolean(true);
    else 
        return new Boolean(false);
}

public void itemStateChanged(ItemEvent e) {
    super.fireEditingStopped();
}
}

EDIT:在表模型中定义列后,您需要使用Rendering and Editing对于第 0 列和第 1 列,使用以下语句。

sourceTable.getColumnModel().getColumn(1).setCellRenderer(new RadioButtonRenderer());
sourceTable.getColumnModel().getColumn(1).setCellEditor(new RadioButtonEditor(new JCheckBox()));

同样,您也需要对第二列和第三列执行操作(根据需要)。您必须注意的一个重要步骤是setValueAt(..)TableModel 中的方法,您需要对列 (0, 1) 和 (2, 3) 进行分组,因此当第 0 列是selected然后将第一列设为deselected2 列和 3 列也是如此。看着那(这setValueAt(..)下面是案例 2 的方法代码。当用户选择第二列时,我们将将该列设置为 true,将第三列设置为 false。您只需对第 2 列和第 3 列执行相同的操作即可。

   case 2:
        model.setSelect(true);
        model.setInActive(false);
        break;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 JRadioButton 添加到 JTable 的两列并对其进行 ButtonGroup。 的相关文章

随机推荐

  • 如何将图像转换为灰度而不丢失透明度?

    我在将带有一些透明像素的彩色图像转换为灰度时遇到问题 我已经在该网站上搜索并找到了相关问题 但我无法用来解决我的问题 我定义了一个方法 convertType 如下所示 attempts to convert the type of the
  • Polymer-AngularJS 双向数据绑定

    我创建了一些自定义元素Polymer 我们称之为 x input 它看起来像这样
  • 如何使用 Google Translate API 翻译 Microsoft Excel 中的文本

    我希望这里有人可以帮助我使用谷歌翻译 API 我有一个大约有 80k 行的 Excel 文件 我正在尝试构建一个宏 它可以翻译列中除第一行之外的所有内容 作为示例 我在 Microsoft Excel 中有六列 如下所示 Excel 列标题
  • 不同浏览器的字体大小差异很大

    Update 添加了简单的测试示例http jsfiddle net 7UhrW 1 使用normalize css Chrome WebKit 和 Firefox 有不同的渲染引擎 它们以不同的方式渲染字体 特别是不同尺寸的字体 这并不太
  • 仅显示一次 RDLC 标头

    通常在 RDLC 报告中 如果您使用标题 它将在每个页面上重复 如果我只想在第一页上显示标题而不显示其余部分 有什么解决方案 有什么方法可以告诉哪些页面的标题可见 您不能使用页眉来执行此操作 为此 您需要将标题控件移至正文部分
  • 按中心裁剪图像

    我有一个大小为 218 178 的 PNG 图像 我正在使用 matplotlib 的函数 imread 将其转换为 ndarray 我想裁剪它以获得图像的中间 64X64 部分 我尝试用 np reshape 进行裁剪 但没有意义 我也尝
  • 存储软件文档的最佳方式是什么? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心以获得指导 一个明显的答案是 内部维基
  • 动态 Sass 变量

    有什么方法可以根据 html 元素上的类设置颜色变量吗 或者还有其他方法可以实现同样的目标吗 html sunrise accent 37CCBD base 3E4653 flat eceef1 moonlight accent 18c b
  • SSIS 转换——将一列拆分为多列

    我试图找出如何拆分表中的一列 并在将结果导出到 CSV 文件后将其拆分为三列 例如 我有一个名为 fullpatentname 的字段 它以以下文本格式列出 Smith John C 期望将其分为三个单独的列 Smith John C 我很
  • 如何参数化复杂的 OleDB 查询?

    我正在尝试重构一些使用字符串连接来创建 SQL 命令的代码 这使得它容易受到 SQL 注入的攻击 基本上我想做的就是更换所有string sqlToExecute String Format 带有 SQL 命令和 OleDB 参数列表的语句
  • 启动画面前的白屏

    我的问题SplashScreenActivity 当我在手机上启动应用程序时 它会显示白屏约 0 5 秒 这MainActitivy延伸FragmentActivity并在AndroidManifest我声明SplashScreenActi
  • php regex:删除超过双倍的空格

    tags preg replace s s tags 这将删除不止一个空格 我需要删除任何超过两倍空格的内容 我认为 超过双倍空格 是指 3 个或更多空格 tags preg replace s 3 tags 这会将 3 个或更多连续出现的
  • 如何让Python XMLGenerator输出CDATA

    这是 Java 问题的 Python 等效项如何从 Sax XmlHandler 输出 CDATA 部分 Neither xml sax saxutils XMLGenerator or lxml sax ElementTreeConten
  • 如何格式化和遍历一个包含数组的数组,并且每个数组又包含一个数组?

    我正在尝试在数组中包含的数组中创建多维 tests 0 1 2 4 5 6 在测试中的每个数组中 我想要有子数组 使用第一个数组 0 1 2 创建另一个 for 循环来遍历子数组的内容 从 bash 4 3 开始 3 个级别 第一个仅包含一
  • 在 Android Studio 3.2 Canary 16 Kotlin 项目上找不到符号 DataBindingComponent

    我刚刚在 Android Studio 3 2 Canary 16 上创建了一个启用了 Kotlin 的新项目 然后我还启用了数据绑定 但收到一条错误消息 指出找不到 DataBindingComponent 类 这是我的项目等级 Top
  • 如何在mongodb中找到匹配的记录?

    我的集合中有一条记录 我想获取 id 为 1 的人的详细信息 但是我获取了 2 次而不是 1 次的详细信息 db mycollection insert person id 1 details name Aswini Age 10 id 2
  • 核心图跳过值图

    我正在尝试绘制一个带有用户友好的时间线的图表 其中每天 每周 由时间范围决定 作为 x 轴的标签 但是 数据源值是根据另一种基础给出的 一天可能有 10 个条目 一个月内可能有 11 个条目 请参阅 Photoshop 图像 使用最新的 C
  • 什么时候应该在类中使用静态方法?有什么好处?

    我有静态变量的概念 但是类中静态方法有什么好处 我参与过一些项目 但我没有将方法设为静态 每当我需要调用类的方法时 我都会创建该类的一个对象并调用所需的方法 Q 方法中的静态变量即使在执行方法时也保留其值 但只能在其包含方法中访问 但是静态
  • Backand.signup() - “创建我的应用程序用户”执行失败

    我正在尝试使用以下方法注册新用户 Backand signup firstName lastName username password password2 但我最终得到 POST https api backand com 1 user
  • 如何将 JRadioButton 添加到 JTable 的两列并对其进行 ButtonGroup。

    我想要一个JTable它由 2 列组成 有RadioButton 活动和非活动 这样如果活动列是Selected然后 Inactive RadioButton 得到Unselected反之亦然意味着在单行中只能从 2 个单选按钮中选择 1