首页 > 代码库 > Jtable添加菜单
Jtable添加菜单
package com.batc.ecn.icon;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.util.Vector;import javax.swing.JMenuItem;import javax.swing.JPopupMenu;import javax.swing.JTable;import javax.swing.event.MouseInputListener;import javax.swing.table.DefaultTableModel;public class JtableMenu implements ActionListener { private JTable table; private JPopupMenu popup = new JPopupMenu(); private String[] menuStrs = { "增加", "删除"}; public JtableMenu(JTable table) { this.table = table; for (String menuStr : menuStrs) { JMenuItem menu = new JMenuItem(menuStr); menu.addActionListener(this); popup.add(menu); } init(); } private void init() { MouseInputListener mil = new MouseInputListener() { public void mouseReleased(MouseEvent e) { if ((e.getModifiers() & MouseEvent.BUTTON3_MASK) != 0 && !e.isControlDown() && !e.isShiftDown()) { popup.show(table, e.getX(), e.getY()); } } public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseDragged(MouseEvent e) { } public void mouseMoved(MouseEvent e) { } }; table.addMouseListener(mil); table.addMouseMotionListener(mil); } @Override public void actionPerformed(ActionEvent e) { DefaultTableModel model = (DefaultTableModel) table.getModel(); if (e.getActionCommand() == "增加") { model.insertRow(model.getRowCount(), new Vector<Object>(model .getColumnCount())); } if (e.getActionCommand() == "删除") { int selectedRow = table.getSelectedRow();// 获得选中行的索引 if (selectedRow != -1) // 存在选中行 { model.removeRow(selectedRow); // 删除行 } } }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。