我对java相当陌生,尤其是java的这一面。我目前正在尝试创建一个 JTable,它将接收一个 CSV 数据文件,然后该表将显示在一个 GUI 上,您可以选择数据的特定部分,从中创建可视化。目前我正在为 mouseClicked 使用 MouseListener - 这会将单元格正确打印到命令行。但是,当对 mouseDragged 使用 MouseMotionListener 时,它只会打印出多次单击(来自 mouseClicked)的单元格。我知道这与 mouseClicked (或至少认为是)有关,但我无法理解它。
代码:
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Color;
public class TableView extends ChartGUI{
/**
*
*/
public JScrollPane GetPanel() {
return scrollPane;
}
public void SetScrollPane(JScrollPane pane) {
scrollPane = pane;
}
public TableView(String title, Object[][] data) {
if(data != null) {
Object[] columnNames = data[0];
Object[][] tableData = new Object[data.length][];
for(int i = 0; i < (data.length - 1); i++){
tableData[i] = data[i+1];
}
table = new JTable(tableData, columnNames);
table.setCellSelectionEnabled(true);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(PANE_WIDTH, PANE_HEIGHT));
SetScrollPane(scrollPane);
} else {
System.out.println("Null Data");
}
/** MouseListener to allow users to select specific cells, printing the data to the command line */
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
col = table.getSelectedColumn();
row = table.getSelectedRow();
selData = GetData(table, row, col);
System.out.println("Selected data: MouseClicked :: " + (String)selData);
}
});
table.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent evt) {
col = table.getSelectedColumn();
row = table.getSelectedRow();
selData = GetData(table, row, col);
System.out.println("Selected data: MouseReleased :: " + (String)selData);
}
});
table.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent evt) {
col = table.getSelectedColumn();
row = table.getSelectedRow();
selData = GetData(table, row, col);
System.out.println("Selected data: MouseDragged :: " + (String)selData);
}
});
}
/** A method to return the values at an index selected by the user, as a String */
public String GetData(JTable table, int row_index, int col_index){
return (String)table.getModel().getValueAt(row_index, col_index);
}
public static void main(String[] args){
System.out.println("Why are you doing this?, maybe we should have some JUnit Tests");
}
private static final long serialVersionUID = 4901866775892531001L;
private JScrollPane scrollPane;
private JTable table;
private String selData;
private int col;
private int row;
private int PANE_WIDTH = 900;
private int PANE_HEIGHT = 600;
}
感谢您的帮助,非常感谢!