Dungeoun Dungeoun - 1 month ago 11
Java Question

Java: How to use an object from one mouseListener to another class?

I need to use the object 'urObjectInCell' in mouseListener of 'table' to another class BtnDelete1.

Here's my Mouse Listener Code:

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();


I tried storing the object in friendNo string which has been declared earlier. But I don't think the friendNo is taking the value of the object.

Here's my Class BtnDelete1 code:

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());
}


}
}


The value of urObjectInCell object obtained from mouseListener is to be used to delete a row in the Jtable 'table'.

Answer

I think that you may be thinking this out wrong. Rather than trying to mix a MouseListener and an ActionListener in some unholy matrimony, why not instead simply get the selected cell from the JTable when the ActionListener is notified?

You could do this by giving the JTable-holding class a method for extracting a reference to the selected JTable cell, give the ActionListener a reference to this class, and have the ActionListener call this method when it has been notified and its callback method called.

For example say you have a JTable held in a GUI called NoMouseListenerNeeded:

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());
    }
}

You could use an ActionListener (or AbstractAction) to get the selected cell by passing the GUI into the listener, and calling the GUI's method that returns the selected data:

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);
        }
    }
}