Java:如何使用一个mouseListener中的对象到另一个类?

时间:2016-10-26 01:19:42

标签: java swing jtable mouselistener

我需要将'table'的mouseListener中的对象'urObjectInCell'用于另一个类BtnDelete1。

这是我的鼠标侦听器代码:

    JTable table;
    public FirstSwingApp(){
       super();
       table = new JTable(model);

       table.addMouseListener(new MouseAdapter() {

         public void mouseClicked(final MouseEvent e) {
             if (e.getClickCount() == 1) {
                final JTable target = (JTable)e.getSource();
                final int row = target.getSelectedRow();
                final int column = 1;
                // Cast to ur Object type
                urObjctInCell = target.getValueAt(row, column);

             }
         }
       });
       friendNo = urObjctInCell.toString();

我尝试将对象存储在之前声明的friendNo字符串中。但我不认为朋友没有拿走对象的价值。

这是我的Class BtnDelete1代码:

public class BtnDelete1 implements ActionListener {

    public void actionPerformed(ActionEvent e) {



        String fnumber = friendNo;

        CallableStatement dstmt = null;
        CallableStatement cstmt = null;

        ResultSet rs;


        try {

            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Contact_Manager?user=root");


            String SQL = "{call delete_contact (?)}";

            String disQuery = "select * from FRIEND";

            dstmt = conn.prepareCall(disQuery);
            cstmt = conn.prepareCall(SQL);

            cstmt.setString(1, fnumber);

            cstmt.executeQuery();

            rs = dstmt.executeQuery();

            ResultSetMetaData metaData = rs.getMetaData();

            // names of columns
            Vector<String> columnNames = new Vector<String>();
            int columnCount = metaData.getColumnCount();
            for (int column = 1; column <= columnCount; column++) {
                columnNames.add(metaData.getColumnName(column));
            }

            // data of the table
            Vector<Vector<Object>> data = new Vector<Vector<Object>>();
            while (rs.next()) {
                Vector<Object> vector = new Vector<Object>();
                for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
                    vector.add(rs.getObject(columnIndex));
                }
                data.add(vector);
            }

            // It creates and displays the table


            model.setDataVector(data, columnNames);

            // Closes the Connection

            dstmt.close();
            System.out.println("Success!!");
        } catch (SQLException ex) {

            System.out.println("Error in connection: " + ex.getMessage());
        }


    }
}

从mouseListener获取的urObjectInCell对象的值将用于删除Jtable“table”中的行。

1 个答案:

答案 0 :(得分:2)

我认为你可能会认为这是错误的。而不是试图在一些邪恶的婚姻中混合使用MouseListener和ActionListener,为什么不在ActionListener被通知时简单地从JTable中获取所选单元?

您可以通过为JTable-holding类提供一个方法来提取对所选JTable单元的引用,为ActionListener提供对此类的引用,并让ActionListener在通知及其回调时调用此方法来实现此目的。方法叫做。

例如,假设您在一个名为NoMouseListenerNeeded的GUI中保存了一个JTable:

import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

@SuppressWarnings("serial")
public class NoMouseListenerNeeded extends JPanel {
    private static final Integer[][] DATA = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
    private static final String[] COLS = { "A", "B", "C" };
    private DefaultTableModel tblModel = new DefaultTableModel(DATA, COLS);
    private JTable table = new JTable(tblModel);

    public NoMouseListenerNeeded() {
        JPanel btnPanel = new JPanel();
        btnPanel.add(new JButton(new MyButtonListener(this)));

        setLayout(new BorderLayout());
        add(new JScrollPane(table));
        add(btnPanel, BorderLayout.PAGE_END);
    }

    // get data held by selected cell in JTable
    // returns null if no cell selected
    public Object getSelectedCell() {
        int col = table.getSelectedColumn();
        int row = table.getSelectedRow();

        if (col < 0 || row < 0) {
            return null; // no selection made, return null
        } else {
            return table.getValueAt(row, col);
        }
    }

    private static void createAndShowGui() {
        NoMouseListenerNeeded mainPanel = new NoMouseListenerNeeded();

        JFrame frame = new JFrame("NoMouseListenerNeeded");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

您可以使用ActionListener(或AbstractAction)通过将GUI传递给侦听器来获取所选单元格,并调用返回所选数据的GUI方法:

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JOptionPane;

@SuppressWarnings("serial")
public class MyButtonListener extends AbstractAction {
    private NoMouseListenerNeeded mainGui;

    public MyButtonListener(NoMouseListenerNeeded mainGui) {
        super("Press Me");
        putValue(MNEMONIC_KEY, KeyEvent.VK_P);
        this.mainGui = mainGui;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object cell = mainGui.getSelectedCell();

        if (cell != null) {
            String message = "Selection is: " + cell;
            JOptionPane.showMessageDialog(mainGui, message, "Selection", JOptionPane.PLAIN_MESSAGE);
        }
    }
}