我想在某人单击单元格时执行操作。例如打开另一个gui。但是,如何让单元格可点击但是不可编辑?这些是sql查询的结果。尽管如此,我无法让桌子变得不可编辑。我需要听众吗?如果是的话我应该在哪里放?JTable单元格不可编辑但可点击
这里是我的代码:
public class AllResultsFromDB extends JFrame
{
GUI ins = new GUI();
public AllResultsFromDB(GUI x)
{
Vector columnNames = new Vector();
Vector data = new Vector();
this.ins = x;
try
{
// Initializing GUI class in order to call getSelectedTable() method.
// GUI ins = new GUI();
//System.out.println(ins.getSelectedTable());
Login sgui = new Login();
String dburl = "jdbc:oracle:thin:@localhost:1521:ORCL";
Connection connection = DriverManager.getConnection(dburl, sgui.getUsername(), sgui.getPassword());
// Fetch data from table specified by user
String query = "SELECT * FROM " + ins.getSelectedTable() + " ORDER BY id";
System.out.println(query);
Statement stmt = connection.createStatement();
ResultSet rset = stmt.executeQuery(query);
ResultSetMetaData metad = rset.getMetaData();
int columns = metad.getColumnCount();
// This loop gets the names of the columns
for (int i = 1; i <= columns; i++)
{
columnNames.addElement(metad.getColumnName(i));
//columnNames.addElement("PROFILES");
}
// This loop gets the data inside the rows
while (rset.next())
{
Vector row = new Vector(columns);
//Vector b = new Vector((Collection)button);
for (int i = 1; i <= columns; i++)
{
row.addElement(rset.getObject(i));
}
data.addElement(row);
//data.addElement(b);
}
rset.close();
stmt.close();
connection.close();
// Create table with results
JTable table = new JTable(data, columnNames)
{
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object obj = getValueAt(row, column);
if (obj != null)
{
return obj.getClass();
}
}
return Object.class;
}
};
JScrollPane scroll = new JScrollPane(table);
getContentPane().add(scroll);
//table.addMouseListener(l);
//table.setEnabled(false);
//table.setDragEnabled(true);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.SOUTH);
} catch (SQLException e) {
}
}
}
为OP理解,我认为关键的一点,就是他们必须提供一个'TableModel'到JTable,而不是只是直接使用数据构建它。带有'isCellEditable()'的新的DefaultTableModel(){...}'应该可以解决这个问题。 – Josh
它可能没有足够突出 - *“通过使用类似DefaultTableModel的,你可以重写此方法,而不会有太多麻烦”* ... – MadProgrammer
是的,我抓住了那部分,这就是为什么我评论,而不是添加一个新的回答。我自己可能不够清楚;我的意思是,新手可能不太理解_how_或_where_“使用类似于”DefaultTableModel“的东西” - 我的评论中的重点应该是“向JTable'提供一个TableModel ......” ,你发布的教程应该可以做到。 – Josh