import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
/*
*
* 给弹出菜单做事件,只要每个给菜单项添加事件就行
*/
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Jpop extends JFrame implements ActionListener{
JTable table;
DefaultTableModel tableM;
JScrollPane jsp;
Vector<String> name = new Vector<String>();
Vector<String> data = new Vector<String>();
JPopupMenu jpm;
JMenuItem jm1,jm2,jm3;
public static void main(String[] args) {
// TODO 自动生成的方法存根
new Jpop();
}
Jpop(){
name.add("姓名");
name.add("年龄");
data.add("张三");
data.add("19");
tableM = new DefaultTableModel(name,0);
tableM.addRow(data);
tableM.addRow(data);
table = new JTable(tableM);
jsp = new JScrollPane(table);
//将菜单条放到弹出菜单中
jm1 = new JMenuItem("变蓝");
jm2 = new JMenuItem("变红");
jm3 = new JMenuItem("变白");
jm1.setBackground(Color.green);
jm2.setBackground(Color.green);
jm3.setBackground(Color.green);
jpm = new JPopupMenu();
jpm.add(jm1);
jpm.add(jm2);
jpm.add(jm3);
jm1.addActionListener(this);
jm2.addActionListener(this);
jm3.addActionListener(this);
//右键点击表格事件
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
if (e.getButton() == MouseEvent.BUTTON3){
//在table显示
int i = table.rowAtPoint(e.getPoint());
jpm.show(table, e.getX(), e.getY());
}
}
});
this.add(jsp);
this.setVisible(true);
this.setSize(400, 400);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(jm1)){
jm1.setBackground(Color.blue);
jm2.setBackground(Color.blue);
jm3.setBackground(Color.blue);
}
if (e.getSource().equals(jm2)){
jm1.setBackground(Color.red);
jm2.setBackground(Color.red);
jm3.setBackground(Color.red);
}
if (e.getSource().equals(jm3)){
jm1.setBackground(Color.white);
jm2.setBackground(Color.white);
jm3.setBackground(Color.white);
}
}
}
swing JPopupMenu使用和添加事件
最新推荐文章于 2024-03-10 13:43:51 发布