单击鼠标时更新JTable?

时间:2016-06-23 15:02:26

标签: java swing jtable mouselistener

我想创建一个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..

}

}

1 个答案:

答案 0 :(得分:2)

public void mouseClicked(MouseEvent e) {
    gt = new JTableGUI();
    gt.addRow(e.getX(), e.getY());
}//

每次单击鼠标时,都无法继续创建JTableGUI的新实例。

相反,你:

  1. 创建框架时创建实例,然后将此实例添加到框架中。
  2. 然后将JTableGUI面板的引用作为参数传递给JPanelGUI。然后将此参数保存在JTableGUI类中,现在您的ActionLIstener可以访问此变量。