0
我想創建一個JTable,當另一個面板被點擊時存儲鼠標位置。我創建了兩個面板,一個顯示錶格,另一個點擊鼠標。點擊時,表格沒有得到更新。貝婁是代碼:鼠標點擊時更新JTable?
類:TableGUI繪製表
public class JTableGUI extends JPanel {
private static final int N_ROWS = 8;
private static String[] header = { "X", "Y" };
private DefaultTableModel dtm = new DefaultTableModel(null, header) {
public Class<?> getColumnClass(int col) {
return getValueAt(0, col).getClass();
}
};
private JTable table = new JTable(dtm);
private JScrollPane scrollPane = new JScrollPane(table);
private JScrollBar vScroll = scrollPane.getVerticalScrollBar();
private int row;
private boolean isAutoScroll;
// Constructor
public JTableGUI() {
this.setLayout(new BorderLayout());
Dimension d = new Dimension(320, N_ROWS * table.getRowHeight());
table.setPreferredScrollableViewportSize(d);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
vScroll.addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
isAutoScroll = !e.getValueIsAdjusting();
}
});
this.add(scrollPane, BorderLayout.CENTER);
// Extra Panel
JPanel panel = new JPanel();
this.add(panel, BorderLayout.SOUTH);
}
public void addRow(int x, int y) {
dtm.addRow(new Object[] { x, y });
}
}
類:JPanelGUI爲clickPanel
public class JPanelGUI {
private JTableGUI gt;
private JPanel clickPanel;
private int WIDTH = 300, HEIGHT = 100;
public JPanelGUI() {
clickPanel = new JPanel();
clickPanel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
clickPanel.setBackground(Color.white);
clickPanel.addMouseListener(new MyMouseListener());
}
public JPanel getPanel() {
return clickPanel;
}
public class MyMouseListener implements MouseListener {
@Override
public void mouseClicked(MouseEvent e) {
gt = new JTableGUI();
gt.addRow(e.getX(), e.getY());
}//Other listener methods..
}
}