制作可点击的JXTable或JTable

时间:2015-03-26 15:37:23

标签: java swing jtable swingx jxtable

我已经创建了一个网络爬虫,然后是一个GUI,供用户搜索数据库等...我现在想要的是JXTable可以点击进入URL。这是我的JXTable代码:

outPut = new JXTable(tableModel);
add(new JScrollPane(outPut), BorderLayout.CENTER);
outPut.setEditable(false);
AbstractHyperlinkAction<Object> simpleAction = new AbstractHyperlinkAction<Object>(null) {
    @Override
        public void actionPerformed(ActionEvent e) {
        //No idea what goes here
    }
};

我已经从数据库中显示它,如下所示,但不知道如何使单元格可点击。

只显示搜索结果的输出

这应该是表的鼠标监听器。不幸的是,他们都没有工作。我也将表格编辑设置为false。我不知道在这之后该去哪里因为我不确定我读过的研究是否正确。

private static boolean isURLColumn(JTable outPut, int column) {
    return column>=0 && outPut.getColumnClass(column).equals(URL.class);
}
public void mouseClicked(MouseEvent e) {
    outPut = (JTable)e.getSource();
    Point pt = e.getPoint();
    int ccol = outPut.columnAtPoint(pt);
    if(isURLColumn(outPut, ccol)) {
        int crow = outPut.rowAtPoint(pt);
        URL url = (URL)outPut.getValueAt(crow, ccol);
        try {
            if(Desktop.isDesktopSupported()) {
                Desktop.getDesktop().browse(url.toURI());
            }
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}

这是使用默认表模型填充JTable的代码:

ResultSetMetaData metaData = rS.getMetaData();
// Names of columns
Vector<String> columnNames = new Vector<>();
int columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
    columnNames.add(metaData.getColumnName(i));
}

// Data of the table
Vector<Vector<Object>> data = new Vector<>();
while (rS.next()) {
    Vector<Object> vector = new Vector<>();
    for (int i = 1; i <= columnCount; i++) {
        vector.add(rS.getObject(i));
    }
    data.add(vector);
}

tableModel.setDataVector(data, columnNames);
tableModel.setRowCount(maxRow);

1 个答案:

答案 0 :(得分:1)

您可以使用自定义编辑器。请查看Using Other Editor上Swing教程中的部分。双击单元格时,该示例显示JColorChooser对话框。您可以自定义代码以显示您的URL是一个网页。

查看目录。本教程还有一个关于How to Integrate With the Desktop Class的部分,可以很容易地显示您的系统浏览器。

或者另一个选项是将MouseListener添加到表中,然后再次使用桌面类显示浏览器。本教程还有一个关于How to Write a MouseListener的部分。

相关问题