我想创建一个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 });
}
}
类:用于clickPanel的JPanelGUI
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..
}
}
答案 0 :(得分:2)
public void mouseClicked(MouseEvent e) {
gt = new JTableGUI();
gt.addRow(e.getX(), e.getY());
}//
每次单击鼠标时,都无法继续创建JTableGUI的新实例。
相反,你: