gpt4 book ai didi

java - 通过右键单击 JTable 中的 MySql 表删除行

转载 作者:行者123 更新时间:2023-11-29 09:36:00 26 4
gpt4 key购买 nike

我有一个如下所示的 Java 类,它显示数据库中的表。我想添加一个函数来打开弹出菜单并从表中删除行。我怎样才能做到这一点?

    import java.awt.BorderLayout;
import javax.swing.*;
import java.sql.*;
import java.util.Vector;

public class Test {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String s;

try {
con = DriverManager.getConnection("jdbc:mysql://localhost/sms", "root", "");
st = con.createStatement();
s = "select * from sent_messages";
rs = st.executeQuery(s);
ResultSetMetaData rsmt = rs.getMetaData();
int c = rsmt.getColumnCount();
Vector column = new Vector(c);

for (int i = 1; i <= c; i++) {
column.add(rsmt.getColumnName(i));
}

Vector data = new Vector();
Vector row = new Vector();

while (rs.next()) {
row = new Vector(c);

for (int i = 1; i <= c; i++) {
row.add(rs.getString(i));
}

data.add(row);
}

JFrame frame = new JFrame();
frame.setSize(500, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JTable table = new JTable(data, column);
JScrollPane jsp = new JScrollPane(table);
panel.setLayout(new BorderLayout());
panel.add(jsp, BorderLayout.CENTER);
frame.setContentPane(panel);
frame.setVisible(true);

} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR");
} finally {
try {
st.close();
rs.close();
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
}
}

作为引用,我查看了 this page但我无法从这里绑定(bind)方法。

最佳答案

我找到了an example我把它作为引用。

我必须处理并重写代码,如下所示的 3 个类:

JTablePopupMenuExample.java

    import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class JTablePopupMenuExample extends JFrame implements ActionListener {


private JTable table;
private DefaultTableModel tableModel;
private JPopupMenu popupMenu;
private JMenuItem menuItemAdd;
private JMenuItem menuItemRemove;
private JMenuItem menuItemRemoveAll;
List<SentMessagesTable> msgList;

public JTablePopupMenuExample() throws Exception{
super("JTable Popup Menu Example");

// sample table data
String[] columnNames = new String[] {"id", "receiver", "sender", "msg_text", "status", "x_date"};



msgList = new ArrayList<SentMessagesTable>();


ResultSet rs = getTableRows();


while (rs.next()) {

SentMessagesTable msg = new SentMessagesTable();

msg.setId(rs.getInt("id"));
msg.setReceiver(rs.getString("receiver"));
msg.setSender(rs.getString("sender"));
msg.setMsgText(rs.getString("msg_text"));
msg.setStatus(rs.getString("status"));
msg.setxDate(rs.getString("x_date"));

msgList.add(msg);

}

String[][] rowDataTable = new String[34400][6];

for(int i = 0 ; i < msgList.size();i++) {
//burda jtable listesini doldur
rowDataTable[i][0] = String.valueOf(msgList.get(i).getId());
rowDataTable[i][1] = msgList.get(i).getReceiver();
rowDataTable[i][2] = msgList.get(i).getSender();
rowDataTable[i][3] = msgList.get(i).getMsgText();
rowDataTable[i][4] = msgList.get(i).getStatus();
rowDataTable[i][5] = msgList.get(i).getxDate();
}

// constructs the table with sample data
tableModel = new DefaultTableModel(rowDataTable, columnNames);
table = new JTable(tableModel);

// constructs the popup menu
popupMenu = new JPopupMenu();
menuItemAdd = new JMenuItem("Add New Row");
menuItemRemove = new JMenuItem("Remove Current Row");
menuItemRemoveAll = new JMenuItem("Remove All Rows");

menuItemAdd.addActionListener(this);
menuItemRemove.addActionListener(this);
menuItemRemoveAll.addActionListener(this);

popupMenu.add(menuItemAdd);
popupMenu.add(menuItemRemove);
popupMenu.add(menuItemRemoveAll);

// sets the popup menu for the table
table.setComponentPopupMenu(popupMenu);

table.addMouseListener(new TableMouseListener(table));

// adds the table to the frame
add(new JScrollPane(table));

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800,1000);
setLocationRelativeTo(null);
}

public static void main(String[] args){

SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
new JTablePopupMenuExample().setVisible(true);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}

@Override
public void actionPerformed(ActionEvent event) {
JMenuItem menu = (JMenuItem) event.getSource();
if (menu == menuItemAdd) {
addNewRow();
} else if (menu == menuItemRemove) {
removeCurrentRow();
} else if (menu == menuItemRemoveAll) {
removeAllRows();
}
}

private void addNewRow() {
tableModel.addRow(new String[0]);
}

private void removeCurrentRow(){
int selectedRow = table.getSelectedRow();
tableModel.removeRow(selectedRow);



String jdbcUrl = "jdbc:mysql://localhost/sms";
String username = "root";
String password = "";
String sql = "delete from sent_messages where id = '"+msgList.get(selectedRow).getId()+"'";
// java.sql.Statement stmt = null;

try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password);
java.sql.Statement stmt = conn.createStatement();) {

stmt.executeUpdate(sql);
System.out.println("Record deleted successfully");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

private void removeAllRows() {
int rowCount = tableModel.getRowCount();
for (int i = 0; i < rowCount; i++) {
tableModel.removeRow(0);
}
}


private ResultSet getTableRows() throws SQLException {
Connection con = null;
java.sql.Statement st = null;
ResultSet rs = null;
String s;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost/sms", "root", "");
st = con.createStatement();
s = "select * from sent_messages";
rs = ((java.sql.Statement) st).executeQuery(s);


}catch(Exception e) {
System.out.println(e.toString());
}
finally {
//con.close();
}

return rs;
}
}

SentMessagesTable.java 其中涉及(getter 和 setter)



public class SentMessagesTable {

int id;
String receiver;
String sender;
String msgText;
String status;
String xDate;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getReceiver() {
return receiver;
}

public void setReceiver(String receiver) {
this.receiver = receiver;
}

public String getSender() {
return sender;
}

public void setSender(String sender) {
this.sender = sender;
}

public String getMsgText() {
return msgText;
}

public void setMsgText(String msgText) {
this.msgText = msgText;
}

public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}

public String getxDate() {
return xDate;
}

public void setxDate(String xDate) {
this.xDate = xDate;
}

}

TableMouse Listener.java



import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JTable;

public class TableMouseListener extends MouseAdapter {

private JTable table;

public TableMouseListener(JTable table) {
this.table = table;
}

@Override
public void mousePressed(MouseEvent event) {
// selects the row at which point the mouse is clicked
Point point = event.getPoint();
int currentRow = table.rowAtPoint(point);
table.setRowSelectionInterval(currentRow, currentRow);
}
}

使用该代码,我能够从 JTable 以及我的数据库中删除记录。

关于java - 通过右键单击 JTable 中的 MySql 表删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57574068/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com