gpt4 book ai didi

java - 在打开时更新 JPopupMenu 菜单项

转载 作者:行者123 更新时间:2023-12-01 11:45:58 29 4
gpt4 key购买 nike

在我的 UI 中,我有一个 JPopMenu,其值为 ,

例如 A、B、C

enter image description here

场景是,

  1. 我打开了 JPopupMenu 并保持打开状态。

  2. 在运行计时器的后端,它会定期将内容 B 更新为其他字母表。

    3.我希望 JPopupMenu 在保持打开状态时得到更新。

在当前行为中,如果我关闭并打开 JPopupMenu,则会显示更新的值。

我尝试了repaint()但它没有做任何事情。

最好的方法是什么?我是 Swing 新手,请帮忙。

最佳答案

菜单项可以在运行时更改其内容。如果不查看代码,很难判断您做错了什么,但这是一个有效的示例:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

public class PopupTest {
private static final String[] messages = {
"You are today's 1000th user!",
"You have won an internet!",
"Claim your prize!"
};

private PopupTest() {
JFrame frame = new JFrame("You have won");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lbl = new JLabel("Check your prize!");
frame.setLocationByPlatform(true);
frame.add(lbl);
frame.pack();

final JPopupMenu menu = new JPopupMenu();
final JMenuItem item = new JMenuItem(messages[0]);
menu.add(item);
menu.add(new JMenuItem("Another item that does not work"));

final Timer timer = new Timer(1000, new ActionListener() {
int count;

@Override
public void actionPerformed(ActionEvent e) {
count++;
count %= messages.length;
item.setText(messages[count]);
}
});

menu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
}

@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
timer.stop();
}

@Override
public void popupMenuCanceled(PopupMenuEvent e) {
timer.stop();
}
});

lbl.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}

@Override
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}

private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
menu.show(e.getComponent(), e.getX(), e.getY());
timer.start();
}
}
});

frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new PopupTest();
}
});
}
}

关于java - 在打开时更新 JPopupMenu 菜单项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29121237/

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