我有一個擴展JScrollPane的類,即創建另一個可擴展JTable的類的對象。基本上,它看起來是這樣的:覆蓋JTable的構造函數之前調用的方法
class CustomScrollPane{
private CustomTable table
public CustomScrollPane(..){
table = new CustomTable(this);
..
}
public void scrollToBottom(){
...
}
}
在CustomTable I類重寫tableChanged:
public class CustomTable extends JTable{
private CustomScrollPane scrollPane;
public CustomTable(CustomScrollPane scrollPane){
super();
this.scrollPane = scrollPane;
}
@Override
public void tableChanged(TableModelEvent e) {
super.tableChanged(e);
scrollPane.scrollToBottom();
}
當我運行此我tableChanged()得到一個NullPointerException上滾動面板,這怎麼可能?在構造函數中設置時,scrollPane如何爲null?在調試器中運行它表明tableChanged()在構造函數之前被調用。添加條件
if (scrollPane != null)
實際上解決了這個問題,因爲後來的構造函數被調用。此外,定義JTable中作爲其構成,如:
table = new JTable(){
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
final Component c = super.prepareRenderer(new CustomTableCellRenderer(), row, column);
if (c instanceof JComponent){
((JComponent) c).setOpaque(true);
}
return c;
}
@Override
public void paint(Graphics g) {
int scrolling = scrollPane.getViewport().getViewPosition().y;
super.paint(g);
g.drawImage(image.getImage(), -30, -50 + scrolling, null, null);
}
@Override
public void tableChanged(TableModelEvent e) {
super.tableChanged(e);
scrollPane.scrollToBottom();
}
};
直接在CustomScrollPane構造也有效。爲什麼不能把它分解成一個單獨的課程?
你確定你沒有另一個構造無論是在CustomScrollPane或CustomTable,實際上是越來越叫什麼名字?再次運行調試器,查看CustomTable中的哪個構造函數是從CustomScrollPane中的哪個構造函數調用的。 –
是的,我想你是對的。它似乎從JPanel中調用了一些其他的構造函數,我覺得這個構造函數不管它是什麼,都不可能有與我的(我自己的類的對象)相同的參數。 –