线程“AWT-EventQueue-0”java.lang中的异常。ClassCastException:javax.swing.JTable

时间:2021-07-16 10:52:16

I have a code which when run generates a table in swing form which contains a set of checkboxes which can be selected or unselected

我有一个代码,在运行时生成一个swing表单,其中包含一组复选框,可以选择或不选择

When I click on the Check All tab I am able to select/unselect all the other below check boxes but when i select one of the below checkboxes individually I get this error :

当我点击Check All选项卡时,我可以选择/取消选择下面所有的复选框,但是当我单独选择下面的一个复选框时,我得到了这个错误:

> Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JTable
    at com.tps.charts.CheckBoxHeader.handleClickEvent(JTableHeaderCheckBox.java:152)
    at com.tps.charts.CheckBoxHeader.mouseClicked(JTableHeaderCheckBox.java:168)
    at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
    at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
    at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
    at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
    at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source) mousePressed......
    at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
    at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
    at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

The code:

代码:

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

public class JTableHeaderCheckBox {

    private Object colNames[] = {"", "String", "String"};
    private Object[][] data = {};
    private DefaultTableModel dtm;
    private JTable table;
    private TableColumn tc;

    public void buildGUI() {
        dtm = new DefaultTableModel(data, colNames);
        table = new JTable(dtm);
        for (int x = 0; x < 5; x++) {
            dtm.addRow(new Object[]{false, "Row " + (x + 1) + " Col 2", "Row " + (x + 1) + " Col 3"});
        }
        JScrollPane sp = new JScrollPane(table);
        tc = table.getColumnModel().getColumn(0);
        tc.setCellEditor(table.getDefaultEditor(Boolean.class));
        tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
        tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener()));
        JFrame f = new JFrame();
        f.getContentPane().add(sp);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }

    private class MyItemListener implements ItemListener {

        @Override
        public void itemStateChanged(ItemEvent e) {
            System.out.println("ItemStateChanged");
            Object source = e.getSource();
            if (source instanceof AbstractButton == false) {
                return;
            }
            boolean checked = e.getStateChange() == ItemEvent.SELECTED;
            for (int x = 0, y = table.getRowCount(); x < y; x++) {
                table.setValueAt(checked, x, 0);
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new JTableHeaderCheckBox().buildGUI();
            }
        });
    }
}

class CheckBoxHeader extends JCheckBox implements TableCellRenderer, MouseListener {

    private static final long serialVersionUID = 1L;
    private CheckBoxHeader rendererComponent;
    private int column;
    private boolean mousePressed = false;

    public CheckBoxHeader(ItemListener itemListener) {
        rendererComponent = this;
        rendererComponent.addItemListener(itemListener);
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
        if (table != null) {
            JTableHeader header = table.getTableHeader();
            table.addMouseListener(rendererComponent);
            if (header != null) {
                rendererComponent.setForeground(header.getForeground());
                rendererComponent.setBackground(header.getBackground());
                rendererComponent.setFont(header.getFont());
                header.addMouseListener(rendererComponent);
            }
        }
        setColumn(column);
        rendererComponent.setText("Check All");
        setBorder(UIManager.getBorder("TableHeader.cellBorder"));
        return rendererComponent;
    }

    protected void setColumn(int column) {
        this.column = column;
    }

    public int getColumn() {
        return column;
    }

    protected void handleClickEvent(MouseEvent e) {
        if (mousePressed) {
            mousePressed = false;
            JTableHeader header = (JTableHeader) (e.getSource());
            JTable tableView = header.getTable();
            TableColumnModel columnModel = tableView.getColumnModel();
            int viewColumn = columnModel.getColumnIndexAtX(e.getX());
            column = tableView.convertColumnIndexToModel(viewColumn);
            if (viewColumn == this.column && e.getClickCount() == 1 && column != -1) {
                System.out.println(" doClick()......");
                doClick();
            }
        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        System.out.println(" mouseClicked()......");
        handleClickEvent(e);
        /* problem occurs from this line */
        ((JTableHeader) e.getSource()).repaint();
    }

    @Override
    public void mousePressed(MouseEvent e) {
        //System.out.println("mousePressed(MouseEvent e).......");
        mousePressed = true;
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        //System.out.println(" mouseReleased()......");
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        //System.out.println(" mouseEntered()......");
    }

    @Override
    public void mouseExited(MouseEvent e) {
        //System.out.println("mouseExited()......");
    }
}

with Exception

除了

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: 
javax.swing.JTable cannot be cast to javax.swing.table.JTableHeader

2 个解决方案

#1


2  

On line 152: JTableHeader header = (JTableHeader)(e.getSource()); you are assuming the event is on the table header. You need to check event source's class to see if it's on the header or an individual checkbox.

第152行:JTableHeader头= (JTableHeader)(. getsource ());假设事件在表头中。您需要检查事件源的类,看看它是在标题中还是在单独的复选框中。

#2


2  

You are casting the source of the event to a JTableHeader:

您正在将事件源转换为JTableHeader:

JTableHeader header = (JTableHeader) (e.getSource());

and the source is a JTable when you click at a cell. I would have two different listeners for the header and the cell selection or you can do a hack by checking event.getSource() instanceof ... in your mouse-click-listener.

当您单击单元格时,源是一个JTable。我将有两个不同的侦听器用于标题和单元格选择,或者您可以通过检查event.getSource() instanceof…在你mouse-click-listener。

#1


2  

On line 152: JTableHeader header = (JTableHeader)(e.getSource()); you are assuming the event is on the table header. You need to check event source's class to see if it's on the header or an individual checkbox.

第152行:JTableHeader头= (JTableHeader)(. getsource ());假设事件在表头中。您需要检查事件源的类,看看它是在标题中还是在单独的复选框中。

#2


2  

You are casting the source of the event to a JTableHeader:

您正在将事件源转换为JTableHeader:

JTableHeader header = (JTableHeader) (e.getSource());

and the source is a JTable when you click at a cell. I would have two different listeners for the header and the cell selection or you can do a hack by checking event.getSource() instanceof ... in your mouse-click-listener.

当您单击单元格时,源是一个JTable。我将有两个不同的侦听器用于标题和单元格选择,或者您可以通过检查event.getSource() instanceof…在你mouse-click-listener。