2
我實現了由JTable實例使用的自定義標頭單元渲染器。如何將鼠標監聽器添加到自定義JTable標頭單元格渲染器中的組件
private final class TableHeaderCellRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 6288512805541476242L;
public TableHeaderCellRenderer() {
setHorizontalAlignment(CENTER);
setHorizontalTextPosition(LEFT);
setVerticalAlignment(BOTTOM);
setOpaque(false);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setIcon(getIcon(table, column));
JPanel headerContainer = new JPanel();
headerContainer.setLayout(new BorderLayout());
headerContainer.setBorder(UIManager.getBorder("TableHeader.cellBorder"));
Box buttonBox = Box.createHorizontalBox();
JButton pinButton = new JButton();
pinButton.setOpaque(false);
pinButton.setMaximumSize(new Dimension(16, 16));
pinButton.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
JOptionPane.showMessageDialog(null, "ASD");
}
});
buttonBox.add(pinButton);
headerContainer.add(this, BorderLayout.CENTER);
headerContainer.add(buttonBox, BorderLayout.EAST);
return headerContainer;
}
}
當我點擊「Pin Button」時,消息對話框不會出現,而只會發生排序。請注意,相應的JTable實例使用setAutoCreateRowSorter(true);.這可能是按鈕沒有收到任何mousePressed事件的原因嗎?
+1非常好的解釋,@ jilt3d示例爲此http://stackoverflow.com/questions/7556380/sorting-jtable-causes-nullpointerexception/7557018#7557018 – mKorbel
嗯,所以渲染器只是...讓我們說...一個圖形?我需要通過鼠標指針的座標來分配哪些內容?有趣的知道。謝謝你的解釋。 – jilt3d
+1這裏有一個相關的[問答](http://stackoverflow.com/questions/7137786/how-can-i-put-a-control-in-the-jtableheader-of-a-jtable)。 – trashgod