gpt4 book ai didi

java - 如何通过选择标题来选择 JDialog 中 JTable 的列

转载 作者:太空宇宙 更新时间:2023-11-04 06:14:56 24 4
gpt4 key购买 nike

enter image description here

我一直在尝试用 JDialog 做的是......

  1. 通过单击标题选择 JTable 的列
  2. 检查用户选择了哪一列
  3. 获取列内单元格的值

根据this postthis page ,可以通过单击标题并设置 JTableHeader 来选择列。

但是,它们似乎都不适合我想做的事情。

首先,我不确定将JTableHeader放在哪里。上面的示例似乎已将其用于初始化,但我在编码中没有看到任何合适的空间来执行此操作。

至少我知道第二个例子是JPanel。因此,为了在 JDialog 中拥有 JTableHeaderJTableHeader 需要设置在完全不同的位置,因为默认情况下无法手动修改 JDialog 的 initComponents()

此外,我找不到如何选择标题(与单个单元格不同)。我假设我需要事先设置一个 JTableHeader

最后,我没有看到任何方法来检测选择了哪一列。至少我找到了jTable.getValueAt(int, int)方法,但这个方法似乎是为了获取单个单元格。

现在我怀疑用 JTable 和 JDialog 可能无法完成它们。如果您能提供任何见解,我将不胜感激。

我添加了 initComponents() 的一部分,以便您轻松理解它。

private void initComponents() {

//here are irrelevant codes
jTable1 = new javax.swing.JTable();

setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

jLabel1.setFont(new java.awt.Font("MS UI Gothic", 3, 18)); // NOI18N
jLabel1.setText("Choose level(s) or unit(s)");

//irrelevant codes

jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"EN6", "EN3", "EN5", "IN1"},
{"EN2", "EN3", null, "IN4"},
{null, null, null, "IN1"},
{null, null, null, "IN2"},

new String [] {
"EN2", "EN3", "EN5", "IN1"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
//lots of lines, seem to be irrelevant
pack();
}

最佳答案

"[...]it would be possible to select a column by clicking the header, by setting a JTableHeader."

根据您的要求,我认为您不需要提供自己的表头,而是附加 MouseListener改为默认值。这样,并使用行和列选择模型,您就可以轻松实现您的目标。

代码片段

final JTable table = new JTable(tableModel);
table.setColumnSelectionAllowed(true);
table.getTableHeader().addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// Get the right column based on MouseEvent#getPoint()
int columnIndex = table.columnAtPoint(e.getPoint());
// Set this column as the selected one in the columns selection model
table.getColumnModel().getSelectionModel().setSelectionInterval(columnIndex, columnIndex);
// Set all the rows as the selected ones in the rows selection model
table.getSelectionModel().setSelectionInterval(0, table.getRowCount() - 1);
// Print the values in selected column
for (int rowIndex = 0; rowIndex < table.getRowCount(); rowIndex++) {
System.out.println(table.getValueAt(rowIndex, columnIndex));
}
}
});

注意:不要忘记允许选择列。

参见:

关于java - 如何通过选择标题来选择 JDialog 中 JTable 的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28210022/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com