仅将JButton添加到JTable中的某些行和列

时间:2017-03-27 11:02:15

标签: java swing jtable jbutton

我想将一些JButton添加到JTable中,但仅限于特定的单元格。 到目前为止,我已经写了一个类,只能将Buttons添加到一行。 我已经找到了很多关于如何将Buttons添加到整个列的教程,但是我无法弄清楚如何只将它们添加到某些行。

这就是我想要的表格:

this is what i want it to look like

理想的解决方案是,如果我可以根据tabledata的值添加按钮。例如,如果数据包含空字符串,我没有显示Button,如果它具有正确的值,则String将是Button的文本。

源代码

Class ConnectionPanel

public class ConnectionPanel extends JFrame{

public ConnectionPanel(){

    Object[][] licData = {{"License 1", "0.0.0.0", "connect", "disconnect", ""},{"License 2", "123.123.123", "", "", ""},{"License 3", "42.23.4", "connect", "disconnect", "delete"}};

    ConnTableModel licConnModel = new ConnTableModel(licData);

    this.setLayout(new MigLayout("", "[grow]", "[][grow][][][][][][][grow][][][][][]"));
    this.setSize(new Dimension(500, 300));
    JLabel lblLicenses = new JLabel("Licenses");
    this.add(lblLicenses, "cell 0 0,growx");

    JTable licenseTable = new JTable(licConnModel);
    licenseTable.setTableHeader(null);

    new ButtonColumn(licenseTable, 2, 0);
    new ButtonColumn(licenseTable, 3, 0);
    new ButtonColumn(licenseTable, 2, 2);
    new ButtonColumn(licenseTable, 3, 2);
    new ButtonColumn(licenseTable, 4, 2);

    JScrollPane scrollPaneLic = new JScrollPane();
    scrollPaneLic.setViewportView(licenseTable);
    this.add(scrollPaneLic, "cell 0 1 1 6,grow");
}

内部静态类ConnTableModel

public static class ConnTableModel extends AbstractTableModel {
    Object[][] data;

    public ConnTableModel(Object[][] data){
        this.data = data;
    }

    @Override
    public int getRowCount() {
        return data.length;
    }

    @Override
    public int getColumnCount() {
        return data[0].length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        return data[rowIndex][columnIndex];
    }

    public boolean isCellEditable(int rowIndex, int columnIndex) { 
        if(columnIndex == 2 || columnIndex == 3 || columnIndex == 4) {
            return true;
        } else {
            return false;
        }
    }   
}

内部类ButtonColumn

class ButtonColumn extends AbstractCellEditor
implements TableCellRenderer, TableCellEditor, ActionListener
{
    JTable table;
    JButton editButton;
    JButton renderButton;
    String text;
    int showRow;

    public ButtonColumn(JTable table, int column, int showRow) {
        super();
        this.table = table;
        this.showRow = showRow;
        renderButton = new JButton();

        editButton = new JButton();
        editButton.setFocusPainted( false );
        editButton.addActionListener( this );

        TableColumnModel columnModel = table.getColumnModel();
        columnModel.getColumn(column).setCellRenderer( this );
        columnModel.getColumn(column).setCellEditor( this );
    }

    @Override
    public Object getCellEditorValue() {
         return text;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        fireEditingStopped();

        if(text.equals("connect")){
            System.out.println("conn");
        }else if(text.equals("disconnect")){
            System.out.println("disc");
        }
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean selected, int row,
            int column) {
        if(row == showRow){
         text = (value == null) ? "" : value.toString();
            editButton.setText( text );
            return editButton;
        }else{
            return null;
        }
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean selected, boolean hasFocus,
            int row, int column) {
        if (hasFocus) {
            renderButton.setForeground(table.getForeground());
            renderButton.setBackground(UIManager.getColor("Button.background"));
        } else if (selected) {
            renderButton.setForeground(table.getSelectionForeground());
             renderButton.setBackground(table.getSelectionBackground());
        } else {
            renderButton.setForeground(table.getForeground());
            renderButton.setBackground(UIManager.getColor("Button.background"));
        }

        renderButton.setText((value == null) ? "" : value.toString());
        if(row == showRow) {
            return renderButton;
        } else {
            return null;
        }
    }

}

主要方法

    public static void main(String[] args) {
        ConnectionPanel con = new ConnectionPanel();
        con.setVisible(true);
    }
}

问题

当我使用" new ButtonColumn(myTable,column,row)"创建新按钮时我为多行执行此操作,它仅显示我在表中为每列创建的最后一个Button。我无法弄清楚它为什么会这样。我想" ButtonColumn" -class有问题? 有没有办法为某些行创建按钮,或者f.e.直接从TableModel创建它们吗?

3 个答案:

答案 0 :(得分:2)

你以完全错误的方式做到了这一点。 无论如何,你提到的问题的根本原因是: 当您创建ButtonColumn实例时,它将是单元格渲染器和该列的编辑器。 当你执行时,

 new ButtonColumn(licenseTable, 2, 2);
 new ButtonColumn(licenseTable, 2, 3);

现在第2列单元格渲染器为ButtonColumn(licenseTable, 2, 3),它将为除3以外的任何行返回null。因此,您将仅在第3行的第3列中看到该按钮。

其他问题:

  1. 不要对编辑器和渲染器使用相同的实例,这可能会导致一些绘画问题

  2. 单元格渲染器旨在提供基于行,列,对象的组件。所以你的渲染器可以评估这些值,然后它可以决定是否应该返回一个按钮或一个空标签。

答案 1 :(得分:1)

这里是mcve简化为基础:

public class ButtonTableTest {

    public static void main(String[] args) {
        final Random random = new Random();
        DefaultTableModel tableModel = new DefaultTableModel(20, 7) {
            @Override
            public Class<?> getColumnClass(int arg0) {
              // provide the default renderer and editor of String for empty cells
                return String.class; 
            }

            @Override
            public boolean isCellEditable(int row, int column) {
               // do not request the editor for empty cells
                return !"".equals(getValueAt(row, column));
            }

            @Override
            public Object getValueAt(int row, int column) {
                // some random table content
                if (null == super.getValueAt(row, column)) {
                    int nextInt = random.nextInt(10);
                    if (nextInt > 5)
                        super.setValueAt(String.format("cell %dx%d", row, column), row, column);
                    else
                        super.setValueAt("", row, column);
                }
                return super.getValueAt(row, column);
            }

            @Override
            public void setValueAt(Object arg0, int arg1, int arg2) {
                // prevent update to NULL
            }

        };

        JTable jTable = new JTable(tableModel);
        jTable.setPreferredSize(new Dimension(800, 350));
        final JButton jButton = new JButton();

        jTable.setDefaultRenderer(String.class, new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) {
                Component tableCellRendererComponent = super.getTableCellRendererComponent(table, value, isSelected,
                        hasFocus, row, column);
                if ("".equals(value)) {
                    // default renderer for empty cells
                    return tableCellRendererComponent;
                } else {
                    jButton.setAction(createSameActionForEditorAndRenderer(table, value));
                    return jButton;
                }
            }
        });
        jTable.setDefaultEditor(String.class, new DefaultCellEditor(new JCheckBox()) { // JCheckBox is closest to a button...

            @Override
            public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row,
                    int column) {
                Component tableCellEditorComponent = super.getTableCellEditorComponent(table, value, isSelected, row,
                        column);
                jButton.setAction(createSameActionForEditorAndRenderer(jTable, value));
                return jButton;
            }

        });
        JOptionPane.showMessageDialog(null, jTable);
    }

    private static AbstractAction createSameActionForEditorAndRenderer(JTable table, Object value) {
        return new AbstractAction((String) value) {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(table, String.format("clicked on %s",value));
                });
                table.getCellEditor().stopCellEditing();
                table.repaint();
            }
        };
    }
}
  

当我点击一个单元格时,它经常显示错误的值。有时它是来自同一行的另一个单元格的值,或者是之前单击过的单元格的值。我无法弄清楚为什么会这样做?

这是因为我对Renderer和Editor使用相同的JButton实例。

这是修改它的更改:

        //final JButton jButton = new JButton();

        jTable.setDefaultRenderer(String.class, new DefaultTableCellRenderer() {
           private final JButton jButton = new JButton();
        // rest of renderer

        jTable.setDefaultEditor(String.class, new DefaultCellEditor(new JCheckBox()) { // JCheckBox is closest to a button...
           private final JButton jButton = new JButton();
        // rest of editor

答案 2 :(得分:1)

致电时

TableColumnModel columnModel = table.getColumnModel();
columnModel.getColumn(column).setCellRenderer(this);
columnModel.getColumn(column).setCellEditor(this);

ButtonColumn的构造函数中,您为列设置了CellRendererCellEditor。对该列的最后一次调用将赢得并覆盖该列的CellRendererCellEditor的旧设置。

问题不是五分钟的问题。我会创建一个容器,它可以容纳ButtonColumn然后可以决定哪个ButtonColumn进行渲染/编辑,但这非常棘手。 可以在下面找到解决渲染问题的快速尝试:

新内部类RowColumn

用于组合行和列以将其关联到Map

的类
static class RowColumn {
    final int row;
    final int column;

    RowColumn(int theColumn, int theRow) {
        this.column = theColumn;
        this.row = theRow;
    }

    public int getRow() {
        return row;
    }

    public int getColumn() {
        return column;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + column;
        result = prime * result + row;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        RowColumn other = (RowColumn) obj;
        if (column != other.column)
            return false;
        if (row != other.row)
            return false;
        return true;
    }


}

新内部类ButtonColumnContainer

容纳多个ButtonColumn s。

的容器
static class ButtonColumnContainer implements TableCellRenderer {
    Map<RowColumn, ButtonColumn> mapIntToColumn = new HashMap<>();

    ButtonColumn createButtonColumn(JTable table, int column, int row) {

        RowColumn rc = new RowColumn(column, row);
        ButtonColumn buttonColumn = new ButtonColumn(column, row);
        mapIntToColumn.put(rc, buttonColumn);

        TableColumnModel columnModel = table.getColumnModel();
        columnModel.getColumn(column).setCellRenderer(this);
        // columnModel.getColumn(column).setCellEditor(this);

        return buttonColumn;
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean selected, boolean hasFocus,
            int row, int column) {
        ButtonColumn buttonColumn = getButtonColumn(column, row);

        if (buttonColumn != null) {
            JButton renderButton = buttonColumn.getRenderButton();
            if (hasFocus) {
                renderButton.setForeground(table.getForeground());
                renderButton.setBackground(UIManager.getColor("Button.background"));
            } else if (selected) {
                renderButton.setForeground(table.getSelectionForeground());
                renderButton.setBackground(table.getSelectionBackground());
            } else {
                renderButton.setForeground(table.getForeground());
                renderButton.setBackground(UIManager.getColor("Button.background"));
            }

            renderButton.setText((value == null) ? "" : value.toString());
            return renderButton;
        } else {
            return null;
        }
    }

    public Component getTableCellEditorComponent(JTable table, Object value, boolean selected, int row,
            int column) {
        ButtonColumn buttonColumn = getButtonColumn(column, row);

        if (buttonColumn != null) {
            JButton editButton = buttonColumn.getEditButton();
            String text = (value == null) ? "" : value.toString();
            editButton.setText(text);
            return editButton;
        } else {
            return null;
        }

    }

    private ButtonColumn getButtonColumn(int column, int row) {
        RowColumn rowColumn = new RowColumn(column, row);
        return mapIntToColumn.get(rowColumn);
    }

}

改编的内部类ButtonColumn

JButton editButton renderButtonstatic class ButtonColumn extends AbstractCellEditor implements ActionListener { final JButton editButton; final JButton renderButton; String text; int showRow; public ButtonColumn(int column, int showRow) { super(); this.showRow = showRow; renderButton = new JButton(); editButton = new JButton(); editButton.setFocusPainted(false); editButton.addActionListener(this); } @Override public Object getCellEditorValue() { return text; } @Override public void actionPerformed(ActionEvent e) { fireEditingStopped(); if (text.equals("connect")) { System.out.println("conn"); } else if (text.equals("disconnect")) { System.out.println("disc"); } } public JButton getEditButton() { return editButton; } public JButton getRenderButton() { return renderButton; } }

添加了原始类的getter和setter
ButtonColumn

而不是对ButtonColumnContainer container = new ButtonColumnContainer(); container.createButtonColumn(licenseTable, 2, 0); container.createButtonColumn(licenseTable, 3, 0); container.createButtonColumn(licenseTable, 2, 2); container.createButtonColumn(licenseTable, 3, 2); container.createButtonColumn(licenseTable, 4, 2);

的构造函数的初始调用
{{1}}

请注意,此代码没有能力编辑任何内容,但至少应该解决渲染问题。