码迷,mamicode.com
首页 > 其他好文 > 详细

Jtable添加菜单

时间:2014-06-15 06:52:21      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   color   

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); // 删除行
            }
        }
    }
}

 

Jtable添加菜单,布布扣,bubuko.com

Jtable添加菜单

标签:style   class   blog   code   java   color   

原文地址:http://www.cnblogs.com/sosomaxba/p/3785919.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!