基本上我想要做的是,我有一个JList,其中包含可用驱动器的列表,如果用户选择了其中一个驱动器,那么我将显示位于JTable中所选驱动器中的所有html文件,所以我为我的JList放置一个事件监听器然后我创建一个JTable并将所有数据放在那里并在容器中显示它。代码看起来像这样:
static class HtmlListing implements ListSelectionListener
{
public void valueChanged(ListSelectionEvent event)
{
if (!event.getValueIsAdjusting())
{ //trying to remove and re-add controls in container.
EastCont.removeAll();
globarr = new ArrayList<File>(); // global variable
FileListing fl = new FileListing();
fl.walk(fileList1.getSelectedValue() + "work\\airasia\\html", 500, 0);
//if(globarr.size() > 0)
//{
Object[][] data = new Object[globarr.size()][globarr.size()];
for(int i = 0; i < globarr.size(); i++)
{
if(globarr.get(i).isFile())
{
String filename = globarr.get(i).getName().toString();
String date = sdf.format(globarr.get(i).lastModified());
Object[] obj = new Object[] {filename, filename.substring(filename.lastIndexOf(".") + 1), date, globarr.get(i).getAbsolutePath()};
data[i] = obj;
}
}
Object[] column = new Object[]{"name ", "type", "date modified", "path"};
DefaultTableModel model = new DefaultTableModel(data, column);
model.fireTableDataChanged();
table = new JTable(model)
{
private static final long serialVersionUID = 1L;
public boolean isCellEditable(int row, int column)
{
return false;
};
};
table.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
if (e.getClickCount() == 2)
{
int rowIdx = table.getSelectedRow(); // path to your new file
TableModel tm = table.getModel();
String path = tm.getValueAt(rowIdx, 3).toString();
File htmlFile = new File(path);
try // open the default web browser for the HTML page
{
Desktop.getDesktop().browse(htmlFile.toURI());
//Desktop.getDesktop().open(htmlFile);
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
table.removeColumn(table.getColumnModel().getColumn(3)); //hide column path from display
table.setFillsViewportHeight(true);
table.setIntercellSpacing(new Dimension(0, 5));
table.setShowGrid(false);
scrollPane = new JScrollPane(table);
EastCont = new JPanel();
EastCont.setLayout(new BorderLayout());
EastCont.add(scrollPane);
EastCont.setPreferredSize(new Dimension(1050, 1000));
//EastCont.repaint();
//EastCont.revalidate();
gui.add(EastCont, BorderLayout.EAST);
gui.revalidate();
gui.repaint();
// }
// else
// {
// EastCont.remove(table);
// gui.remove(EastCont);
// gui.revalidate();
// gui.repaint();
// }
}
此代码仅适用于第一次,但不会第二次工作等等,所以我想念这里?任何帮助都会很棒。谢谢。
答案 0 :(得分:1)
DefaultTableModel model = new DefaultTableModel(data, column);
//model.fireTableDataChanged();
//table = new JTable(model)
table.setModel( model );
不要创建新表更改重置当前表的模型。由于您没有创建任何新的GUI组件,因此该方法中的其余代码也不是必需的。
此外,永远不要调用fireXXX方法。这是TableModel的责任。