gpt4 book ai didi

java - ListSelectionListener 将无法正常工作

转载 作者:行者123 更新时间:2023-12-02 09:28:28 26 4
gpt4 key购买 nike

这是我的代码。当您从左向右选择时出现问题..

        import javax.swing.*;
import javax.swing.event.*;
public class swingex7 extends JFrame{
swingex7(){
JFrame f = new JFrame("Table Example");
String row[][]= {{"101","Hein Htet","10000000"},{"102","Hein Htet1","20000000"},{"103","Hein
Htet2","30000000"}};
String column[]= {"Id","Name","Salary"};
final JTable jt = new JTable(row,column);
jt.setCellSelectionEnabled(true);
ListSelectionModel lsm = jt.getSelectionModel();
lsm.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lsm.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
String data=null;
int[] rows=jt.getSelectedRows();
int[] columns = jt.getSelectedColumns();
for(int i=0;i<rows.length;i++) {
for(int j=0;j<columns.length;j++) {
data = (String)jt.getValueAt(rows[i], columns[j]);
}
}
System.out.println("Table element seleted is "+data);
}
});

JScrollPane js = new JScrollPane(jt);
f.add(js);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 400);
f.setVisible(true);
}
public static void main (String[]args) {
new swingex7();
}
}

从左向右选择时出现问题。我还想每个 Action 只输出一次。

最佳答案

代码中有 2 个问题。

1.第一个问题是 ListSelectionListener 在单击鼠标和释放鼠标时被调用两次。但如果您可以将 MouseListener 添加到您的 JTable 中,如下所示。

MouseListener tableMouseListener = new MouseAdapter() {

@Override
public void mouseReleased(MouseEvent e) {
String data = null;
int[] rows = jt.getSelectedRows();
int[] columns = jt.getSelectedColumns();
for (int i = 0; i < rows.length; i++) {
for (int j = 0; j < columns.length; j++) {
data = (String) jt.getValueAt(rows[i], columns[j]);
System.out.println("Table element selected is " + data);
}
}
}
};
jt.addMouseListener(tableMouseListener);

2.第二个问题是打印数据的地方。它应该在 for 循环内。否则,数据将在循环中的每次迭代中被重写,并且仅打印最后一个值。

for (int i = 0; i < rows.length; i++) {
for (int j = 0; j < columns.length; j++) {
data = (String) jt.getValueAt(rows[i], columns[j]);
System.out.println("Table element selected is " + data);
}
}

关于java - ListSelectionListener 将无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58168426/

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