在JTable中禁用JButton

时间:2014-04-23 10:50:25

标签: java swing jtable jbutton

我正在尝试创建一个应用程序,它将从数据库中检索一些数据并将数据填充到JTable中。在表中将有2个按钮,它们将更新我的数据库列的状态字段(即该行的模型的自定义对象)。

执行此操作后,第一个按钮将被禁用,第二个按钮将为该行/对象启用。

我尝试使用JButtonColumn作为测试,但问题是当我点击2个不同的按钮时,其间的其他按钮也会被禁用。这是我到目前为止所尝试的:

import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

public class JavaApplication1 extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;
    private MyTableModel myModel = new MyTableModel();

    public JavaApplication1() {


        table = new JTable(myModel);
        addTableDatas();
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
        ButtonColumn buttonColumn = new ButtonColumn(table, delete, 3);
        buttonColumn.setMnemonic(KeyEvent.VK_D);
    }

    public static void main(String[] args) {
        JavaApplication1 frame = new JavaApplication1();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    private void addTableDatas() {
        Vector<String> columnNameS = new Vector<String>();
        columnNameS.add("Date");
        columnNameS.add("String");
        columnNameS.add("Decimal");
        columnNameS.add("Remove");
        myModel.setColumnNames(columnNameS);

        Vector<Object> row1 = new Vector<Object>();
        row1.add(new Date());
        row1.add("A");
        row1.add(new Double(5.1));
        row1.add("Remove");
        myModel.addRow(row1);

        row1 = new Vector<Object>();
        row1.add(new Date());
        row1.add("B");
        row1.add(new Double(6.2));
        row1.add("Remove");
        myModel.addRow(row1);

        row1 = new Vector<Object>();
        row1.add(new Date());
        row1.add("B");
        row1.add(new Double(8.4));
        row1.add("Remove");
        myModel.addRow(row1);

        row1 = new Vector<Object>();
        row1.add(new Date());
        row1.add("B");
        row1.add(new Double(5.1));
        row1.add("Remove");
        myModel.addRow(row1);

        row1 = new Vector<Object>();
        row1.add(new Date());
        row1.add("B");
        row1.add(new Double(6.2));
        row1.add("Remove");
        myModel.addRow(row1);
    }

    private class MyTableModel extends AbstractTableModel {

        private static final long serialVersionUID = 1L;
        private Vector<Vector<Object>> data;
        private Vector<String> colNames;
        private boolean[] _columnsVisible = {true, true, true, true};

        public MyTableModel() {
            this.colNames = new Vector<String>();
            this.data = new Vector<Vector<Object>>();
        }

        public MyTableModel(Vector<String> colnames) {
            this.colNames = colnames;
            this.data = new Vector<Vector<Object>>();
        }

        public void resetTable() {
            this.colNames.removeAllElements();
            this.data.removeAllElements();
        }

        public void setColumnNames(Vector<String> colNames) {
            this.colNames = colNames;
            this.fireTableStructureChanged();
        }

        public void addRow(Vector<Object> data) {
            this.data.add(data);
            this.fireTableRowsInserted(data.size() - 1, data.size() - 1);
        }

        public void removeRowAt(int row) {
            this.data.removeElementAt(row);
            this.fireTableRowsDeleted(row - 1, data.size() - 1);
        }

        @Override
        public int getColumnCount() {
            return this.colNames.size();
        }

        @Override
        public Class<?> getColumnClass(int colNum) {
            switch (colNum) {
                case 0:
                    return Date.class;
                case 2:
                    return Double.class;
                default:
                    return String.class;
            }
        }

        @Override
        public boolean isCellEditable(int row, int colNum) {
            switch (colNum) {
                default:
                    return true;
            }
        }

        @Override
        public String getColumnName(int colNum) {
            return this.colNames.get(colNum);
        }

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

        @Override
        public Object getValueAt(int row, int col) {
            Vector<Object> value = this.data.get(row);
            return value.get(col);
        }

        @Override
        public void setValueAt(Object newVal, int row, int col) {
            Vector<Object> aRow = data.elementAt(row);
            aRow.remove(col);
            aRow.insertElementAt(newVal, col);
            fireTableCellUpdated(row, col);
        }

        public void setColumnVisible(int index, boolean visible) {
            this._columnsVisible[index] = visible;
            this.fireTableStructureChanged();
        }
    }
    //
    private Action delete = new AbstractAction() {

        private static final long serialVersionUID = 1L;

        public void actionPerformed(ActionEvent e)
        {
            JTable table = (JTable) e.getSource();
            int modelRow = Integer.valueOf(e.getActionCommand());
            //(MyTableModel) table.getModel()).removeRowAt(modelRow);

            //table.clearSelection();
        }
    };
}

JButtonColumn.Java:

    import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;

public class ButtonColumn extends AbstractCellEditor
    implements TableCellRenderer, TableCellEditor, ActionListener,MouseListener
{
    private JTable table;
    private Action action;
    private int mnemonic;
    private Border originalBorder;
    private Border focusBorder;

    private JButton renderButton;
    private JButton editButton;
    private Object editorValue;
    private boolean isButtonColumnEditor;

    public ButtonColumn(JTable table, Action action, int column)
    {
        this.table = table;
        this.action = action;

        renderButton = new JButton();
        editButton = new JButton();
        editButton.setFocusPainted( false );
        editButton.addActionListener( this );
        originalBorder = editButton.getBorder();
        setFocusBorder( new LineBorder(Color.BLUE) );

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


    public Border getFocusBorder()
    {
        return focusBorder;
    }

    public void setFocusBorder(Border focusBorder)
    {
        this.focusBorder = focusBorder;
        editButton.setBorder( focusBorder );
    }

    public int getMnemonic()
    {
        return mnemonic;
    }

    public void setMnemonic(int mnemonic)
    {
        this.mnemonic = mnemonic;
        renderButton.setMnemonic(mnemonic);
        editButton.setMnemonic(mnemonic);
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, 
                Object value,boolean isSelected, int row, int column)
    {
        if (value == null)
        {
            editButton.setText( "" );
            editButton.setIcon( null );
        }
        else if (value instanceof Icon)
        {
            editButton.setText( "" );
            editButton.setIcon( (Icon)value );
        }
        else
        {
            editButton.setText( value.toString() );
            editButton.setIcon( null );
        }

        this.editorValue = value;
        return editButton;
    }

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

    public Component getTableCellRendererComponent(
        JTable table, Object value, boolean isSelected, 
                      boolean hasFocus, int row, int column)
    {
        if (isSelected)
        {
            renderButton.setForeground(table.getSelectionForeground());
            renderButton.setBackground(table.getSelectionBackground());
        }
        else
        {                

renderButton.setForeground(table.getForeground());                  

               renderButton.setBackground(UIManager.getColor("Button.background"));
        }

        if (hasFocus)
        {
            renderButton.setBorder( focusBorder );
        }
        else
        {
            renderButton.setBorder( originalBorder );
        }


        if (value == null)
        {
            renderButton.setText( "" );
            renderButton.setIcon( null );
        }
        else if (value instanceof Icon)
        {
            renderButton.setText( "" );
            renderButton.setIcon( (Icon)value );
        }
        else
        {
            renderButton.setText( value.toString() );
            renderButton.setIcon( null );
        }

        return renderButton;
    }

    public void actionPerformed(ActionEvent e)
    {
        int row = table.convertRowIndexToModel( table.getEditingRow() );
        fireEditingStopped();

        //  Invoke the Action

        ActionEvent event = new ActionEvent(
            table,
            ActionEvent.ACTION_PERFORMED,
            "" + row);
        action.actionPerformed(event);
    }

    public void mousePressed(MouseEvent e)
    {
        if (table.isEditing()
        &&  table.getCellEditor() == this)
            isButtonColumnEditor = true;
    }

    public void mouseReleased(MouseEvent e)
    {
        if (isButtonColumnEditor
        &&  table.isEditing())
            table.getCellEditor().stopCellEditing();

                    //Disabling the button here
                    renderButton.setEnabled(false); 

                    System.out.println("ROW CLICKED");

        isButtonColumnEditor = false;
    }

    public void mouseClicked(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
}

import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.table.*; public class ButtonColumn extends AbstractCellEditor implements TableCellRenderer, TableCellEditor, ActionListener,MouseListener { private JTable table; private Action action; private int mnemonic; private Border originalBorder; private Border focusBorder; private JButton renderButton; private JButton editButton; private Object editorValue; private boolean isButtonColumnEditor; public ButtonColumn(JTable table, Action action, int column) { this.table = table; this.action = action; renderButton = new JButton(); editButton = new JButton(); editButton.setFocusPainted( false ); editButton.addActionListener( this ); originalBorder = editButton.getBorder(); setFocusBorder( new LineBorder(Color.BLUE) ); TableColumnModel columnModel = table.getColumnModel(); columnModel.getColumn(column).setCellRenderer( this ); columnModel.getColumn(column).setCellEditor( this ); table.addMouseListener( this ); } public Border getFocusBorder() { return focusBorder; } public void setFocusBorder(Border focusBorder) { this.focusBorder = focusBorder; editButton.setBorder( focusBorder ); } public int getMnemonic() { return mnemonic; } public void setMnemonic(int mnemonic) { this.mnemonic = mnemonic; renderButton.setMnemonic(mnemonic); editButton.setMnemonic(mnemonic); } @Override public Component getTableCellEditorComponent(JTable table, Object value,boolean isSelected, int row, int column) { if (value == null) { editButton.setText( "" ); editButton.setIcon( null ); } else if (value instanceof Icon) { editButton.setText( "" ); editButton.setIcon( (Icon)value ); } else { editButton.setText( value.toString() ); editButton.setIcon( null ); } this.editorValue = value; return editButton; } @Override public Object getCellEditorValue() { return editorValue; } public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (isSelected) { renderButton.setForeground(table.getSelectionForeground()); renderButton.setBackground(table.getSelectionBackground()); } else { renderButton.setForeground(table.getForeground()); renderButton.setBackground(UIManager.getColor("Button.background")); } if (hasFocus) { renderButton.setBorder( focusBorder ); } else { renderButton.setBorder( originalBorder ); } if (value == null) { renderButton.setText( "" ); renderButton.setIcon( null ); } else if (value instanceof Icon) { renderButton.setText( "" ); renderButton.setIcon( (Icon)value ); } else { renderButton.setText( value.toString() ); renderButton.setIcon( null ); } return renderButton; } public void actionPerformed(ActionEvent e) { int row = table.convertRowIndexToModel( table.getEditingRow() ); fireEditingStopped(); // Invoke the Action ActionEvent event = new ActionEvent( table, ActionEvent.ACTION_PERFORMED, "" + row); action.actionPerformed(event); } public void mousePressed(MouseEvent e) { if (table.isEditing() && table.getCellEditor() == this) isButtonColumnEditor = true; } public void mouseReleased(MouseEvent e) { if (isButtonColumnEditor && table.isEditing()) table.getCellEditor().stopCellEditing(); //Disabling the button here renderButton.setEnabled(false); System.out.println("ROW CLICKED"); isButtonColumnEditor = false; } public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }

1 个答案:

答案 0 :(得分:0)

该课程为ButtonColumn。见:Table Button Column

您无法在编辑器中禁用该按钮。该按钮由表中的所有行共享。这是所有渲染器/编辑器的工作方式。

您需要自定义渲染器/编辑器代码。也就是说,您需要覆盖TableModel的isCellEditable(...),以根据表格中的数据确定单元格何时可编辑:

  1. 如果您尚未更新数据库状态,则button1将是可编辑的,而button2将无法编辑
  2. 如果您更新了数据库状态,则button1将无法编辑且button2可编辑
  3. 然后,您可以在渲染器中自定义按钮的禁用状态:

    1. 如果单元格可编辑,则启用按钮状态
    2. 如果单元格不可编辑,则禁用按钮状态。
    3. 阅读How to use Tables上Swing教程中的部分,了解有关渲染器/编辑器和isCellEditable()方法的更多信息。