Java 在包含JTable的JScrollPane中未调用TableModel
我在Java GUI中遇到了意外行为。我想创建一个包含Java 在包含JTable的JScrollPane中未调用TableModel,java,swing,jtable,jscrollpane,abstracttablemodel,Java,Swing,Jtable,Jscrollpane,Abstracttablemodel,我在Java GUI中遇到了意外行为。我想创建一个包含JTable的JScrollPane,然后将这个JScrollPane添加到框架中 代码如下: public class UrlsScrollPanel extends JScrollPane { private static final long serialVersionUID = 1L; public UrlsScrollPanel() { //setup urls and collections ArrayList
JTable
的JScrollPane
,然后将这个JScrollPane
添加到框架中
代码如下:
public class UrlsScrollPanel extends JScrollPane {
private static final long serialVersionUID = 1L;
public UrlsScrollPanel() {
//setup urls and collections
ArrayList<URL> urls = URL.getAll();
ArrayList<Collection> collections = new ArrayList<>();
for(URL url : urls) collections.add(new Collection(url));
//table
String[] columns = {
"database",
"status",
"consumption",
"last snapshot date",
"last message",
"details",
"stop collect"
};
AbstractTableModel dataModel = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
System.out.printf("row: %d, column: %d \n", rowIndex, columnIndex); //is never called.
URL url = urls.get(rowIndex);
Collection collection = collections.get(rowIndex);
ArrayList<Message> lastMessages = collection.getLastSnapshot().getMessages();
Message lastMessage = lastMessages.get(lastMessages.size() - 1);
if(columnIndex == 0) return url.toString();
if(columnIndex == 1) return collection.getStatus();
if(columnIndex == 2) return ConsumptionChart.getChartPanel(collection);
if(columnIndex == 3) return collection.getLastSnapshot().getDate();
if(columnIndex == 4) return String.format("[ %s ] %s", lastMessage.getDate(), lastMessage.getBody());
return "Comming soon.";
}
@Override
public int getRowCount() {
return urls.size();
}
@Override
public int getColumnCount() {
return columns.length;
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
JTable table = new JTable(dataModel);
add(table);
setBackground(Color.red);
setSize(500, 500);
}
}
结果是一个红色方块在画面左上角闪烁,然后立即消失。而且,dataModel
似乎从未被调用过
非常感谢您对我所做错事的任何帮助,谢谢您的时间 不要扩展JScrollPane
。相反,使用表
构建JScrollPane
:
frame.add(new JScrollPane(table), BorderLayout.CENTER);
描述了该方法;给出了一个完整的例子;研究了使用setViewportView()
的另一种方法
这两个不一样吗
否。如中所示,第一个公式将表直接添加到中,替换占据中的中心位置并将用于显示表的组件。第二个公式在内部调用setViewportView(table)
,它告诉滚动窗格的JViewport
要显示什么组件。好的,我刚刚更改了,我的类不再扩展JScrollPane,而是拥有一个方法getPanel()。然而,我仍然不明白为什么我以前的方法不起作用。IsJScrollPane panel=new JScrollPane();面板。添加(表)代码>与JScrollPane panel=newjscrollpane(表)
不相似?谢谢你的帮助!PS:在向JFrame添加组件时,不需要指定BorderLayout.CENTER,因为这是默认布局;我已经在上面详细阐述了。谢谢你的解释,现在它有意义了!
frame.add(new JScrollPane(table), BorderLayout.CENTER);
JScrollPane panel = new JScrollPane(); panel.add(table);
…
JScrollPane panel = new JScrollPane(table);