按下按钮后,Java将颜色设置为jtable

时间:2014-10-23 05:05:59

标签: java

我有一个带有删除按钮的jtable,当我选择一行并单击删除按钮时我希望将该行设置为绿色。

然而,当我点击时,行颜色不会保留在那里,我选择的每一行都变成绿色而不是默认的蓝色

public class table extends javax.swing.JFrame {

    DefaultTableModel model;
    private boolean btnClicked = false;

    public table() {
        initComponents();
        model = (DefaultTableModel) tbltable.getModel();

    }

    public class CustomTableCellRenderer extends DefaultTableCellRenderer {

        public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) {

            Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column);


            if (isSelected) {

                cell.setBackground(getBackground());                
                String type = (String) String.valueOf(model.getValueAt(tbltable.getSelectedRow(), 3));
                if (("deleted").equals(type)) {
                    cell.setBackground(Color.GREEN);
                }

            }
            return cell;

        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        txtCol1 = new javax.swing.JTextField();
        txtCol2 = new javax.swing.JTextField();
        txtCol3 = new javax.swing.JTextField();
        btnAdd = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbltable = new javax.swing.JTable();
        btnEdit = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        txtCol1.setText("jTextField1");

        txtCol2.setText("jTextField2");

        txtCol3.setText("jTextField3");

        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        tbltable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Col1", "Col2", "Col3", "Col4"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        tbltable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbltableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbltable);

        btnEdit.setText("edit");
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });

        btnDelete.setText("delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(92, 92, 92)
                        .addComponent(txtCol1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(txtCol2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtCol3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(87, 87, 87)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnAdd)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnEdit)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnDelete)))))
                .addContainerGap(283, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtCol1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtCol2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtCol3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAdd)
                    .addComponent(btnEdit)
                    .addComponent(btnDelete))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 273, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(95, Short.MAX_VALUE))
        );

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

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {                                       

        String chkcol = "notdeleted";
        model.insertRow(model.getRowCount(), new Object[]{txtCol1.getText(), txtCol2.getText(), txtCol3.getText(), chkcol});
    }                                      

    private void tbltableMouseClicked(java.awt.event.MouseEvent evt) {                                      
        txtCol1.setText(String.valueOf(model.getValueAt(tbltable.getSelectedRow(), 0)));
        txtCol2.setText(String.valueOf(model.getValueAt(tbltable.getSelectedRow(), 1)));
        txtCol3.setText(String.valueOf(model.getValueAt(tbltable.getSelectedRow(), 2)));
        int rowIndex = tbltable.getSelectedRow();
        System.out.println("rowIndex " + rowIndex);
    }                                     

    private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {                                        
        model.setValueAt(txtCol1.getText(), tbltable.getSelectedRow(), 0);
        model.setValueAt(txtCol2.getText(), tbltable.getSelectedRow(), 1);
        model.setValueAt(txtCol3.getText(), tbltable.getSelectedRow(), 2);
    }                                       
    TableColumn tcol;
    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                          
        model.setValueAt("deleted", tbltable.getSelectedRow(), 3);

        if (String.valueOf(model.getValueAt(tbltable.getSelectedRow(), 3)).equals("deleted")) {
            tcol = tbltable.getColumnModel().getColumn(0);
            tcol.setCellRenderer(new CustomTableCellRenderer());

            tcol = tbltable.getColumnModel().getColumn(1);
            tcol.setCellRenderer(new CustomTableCellRenderer());

            tcol = tbltable.getColumnModel().getColumn(2);
            tcol.setCellRenderer(new CustomTableCellRenderer());

            tcol = tbltable.getColumnModel().getColumn(3);
            tcol.setCellRenderer(new CustomTableCellRenderer());
        }


    }                                         

    /**
     * @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(table.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(table.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(table.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(table.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 table().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbltable;
    private javax.swing.JTextField txtCol1;
    private javax.swing.JTextField txtCol2;
    private javax.swing.JTextField txtCol3;
    // End of variables declaration                   
}

以下是展示我的问题的图片。

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

我建议您在TableModel中保留一个包含布尔值的列,以指示该行是否已删除。此列不应显示在JTable中。您可以使用以下命令将其从JTable视图中删除:

table.removeColumn( table.getColumn(...) );

然后您可以查看Table Row Rendering,其中显示了如何根据行中的值呈现行。

当您测试需要使用的行的布尔值时,请不要忘记:

table.getModel().getValueAt(...);

因为该表无法访问该值,因为它未显示在表中。

答案 1 :(得分:0)

首先看看Using Custom RenderersConcepts: Editors and Renderers

重要的是,表中的每个单元格都使用相同的TableCellRenderer进行渲染(至少在您的情况下,如果您有不同的数据类型,它会更复杂),这意味着{ {1}}是无状态的,它的上下文通过TableCellRenderer

的参数传递给它

每次调用getTableCellRendererComponent时,您都需要更新每个单元格的状态

您需要以某种方式确定是否删除该行,并在具体情况下呈现状态。