这是我的代码:我点击鼠标右键,然后选择test1代码创建一个JLabel并将其放在那个位置。
public class Test extends JFrame {
int x;
int y;
JPopupMenu menu = new JPopupMenu("Popup");
class MyLabel extends JLabel {
public MyLabel(String text) {
super(text);
addMouseListener(new PopupTriggerListener());
}
class PopupTriggerListener extends MouseAdapter {
public void mousePressed(MouseEvent ev) {
if (ev.isPopupTrigger()) {
menu.show(ev.getComponent(), ev.getX(), ev.getY());
x = ev.getX();
y = ev.getY();
}
}
public void mouseReleased(MouseEvent ev) {
if (ev.isPopupTrigger()) {
menu.show(ev.getComponent(), ev.getX(), ev.getY());
x = ev.getX();
y = ev.getY();
}
}
public void mouseClicked(MouseEvent ev) {
}
}
}
JLabel label = new MyLabel("right-click");
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuItem item = new JMenuItem("Test1");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Menu item Test1");
JLabel newLabel = new JLabel("test");
label.add(newLabel);
newLabel.setBounds(x, y, 40, 10);
}
});
menu.add(item);
item = new JMenuItem("Test2");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Menu item Test2");
}
});
menu.add(item);
getContentPane().add(label);
pack();
setSize(300, 100);
}
public static void main(String[] args) {
new Test().setVisible(true);
}
但我不知道之后,我如何访问该标签(例如,修改他们的文本)。如果用户用右键单击它并选择“删除”,我也想删除那些标签,但在actionPerformed代码中netbeans不要让我添加另一个actionListener ..任何人都可以帮助我吗?感谢
答案 0 :(得分:0)
所有更改都在Test
构造函数中:
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Change the name here from "Test1" to whatever you want
JMenuItem item = new JMenuItem("Test1");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Menu item Test1");
JLabel newLabel = new JLabel("test");
label.add(newLabel);
newLabel.setBounds(x, y, 40, 10);
}
});
menu.add(item);
// Change the name here from "Test2" to whatever you want
item = new JMenuItem("Test2");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Menu item Test2");
}
});
menu.add(item);
// Implement a "Delete" option
item = new JMenuItem("Delete");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Menu item Delete");
// Get the component at the mouse coordinates
Component comp = label.getComponentAt(x, y);
// If the component is a JLabel, delete it
if (comp instanceof JLabel) {
label.remove(comp);
// Repaint the screen to remove the label
repaint();
}
}
});
menu.add(item);
getContentPane().add(label);
pack();
setSize(300, 100);
}