我的Java GUI出现意外行为。我想创建一个JScrollPane
包含,JTable
然后将其添加JScrollPane
到中Frame
。
这是代码:
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);
}
}
这就是我所说的:
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH );
frame.setLocationRelativeTo(null);
UrlsScrollPanel panel = new UrlsScrollPanel();
frame.add(panel, BorderLayout.CENTER);
SwingUtilities.updateComponentTreeUI(frame);
}
结果是红色正方形在框的左上方闪烁,然后立即消失。也dataModel
似乎永远不会被调用。
非常感谢您对我做错的事情的帮助,感谢您的宝贵时间!
不要扩展 JScrollPane
。相反,使用yourtable
来构造一个JScrollPane
:
frame.add(new JScrollPane(table), BorderLayout.CENTER);
该方法在这里描述; 这里显示了一个完整的例子; 用另一种方法setViewportView()
进行检查这里。
这两个不相似吗?
JScrollPane panel = new JScrollPane(); panel.add(table);
…
JScrollPane panel = new JScrollPane(table);
否。如“滚动窗格的工作原理”中所示,第一个公式将table
直接添加到中JScrollPane
,替换JViewport
位于中居中位置ScrollPaneLayout
且将用于显示的组件table
。第二个公式在setViewportView(table)
内部调用,它告诉滚动窗格JViewport
要显示的组件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句