我有一个扩展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中调用了一些其他的构造函数,我觉得这个构造函数不管它是什么,都不可能有与我的(我自己的类的对象)相同的参数。 –